ai.js 531 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956
  1. /*
  2. _ ___ ____ _
  3. / \ |_ _| | __ ) __ _ ___(_) ___
  4. / _ \ | | | _ \ / _` / __| |/ __|
  5. / ___ \ | | | |_) | (_| \__ \ | (__
  6. /_/ \_\___| |____/ \__,_|___/_|\___|
  7. */
  8. Blockly.Blocks['ai_v831_button_read_pressed'] = {
  9. init: function () {
  10. this.appendDummyInput()
  11. .appendField(Blockly.Msg.ai_basic_button_when)
  12. .appendField(new Blockly.FieldDropdown([
  13. ["A", "A"],
  14. ["B", "B"],
  15. ["C", "C"],
  16. ["D", "D"]
  17. ]), "button_type")
  18. .appendField(Blockly.Msg.ai_basic_pressed)
  19. this.setOutput(true, null);
  20. this.setColour("#d42b03");
  21. var thisBlock = this;
  22. this.setTooltip(function () {
  23. var mode = thisBlock.getFieldValue('button_type');
  24. var TOOLTIPS = {
  25. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  26. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  27. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  28. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  29. };
  30. return TOOLTIPS[mode];
  31. });
  32. this.setHelpUrl("");
  33. }
  34. };
  35. Blockly.Python['ai_v831_button_read_pressed'] = function (block) {
  36. var _type = block.getFieldValue('button_type');
  37. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  38. sys.path.append("/root/")`
  39. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  40. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  41. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  42. key_B = BUTTON(8)
  43. key_C = BUTTON(13)
  44. key_D = BUTTON(7)
  45. `
  46. var code = `key_${_type}.is_pressed()`
  47. return [code, Blockly.Python.ORDER_CONDITIONAL];
  48. };
  49. Blockly.Blocks['ai_v831_button_read_released'] = {
  50. init: function () {
  51. this.appendDummyInput()
  52. .appendField(Blockly.Msg.ai_basic_button_when)
  53. .appendField(new Blockly.FieldDropdown([
  54. ["A", "A"],
  55. ["B", "B"],
  56. ["C", "C"],
  57. ["D", "D"]
  58. ]), "button_type_released")
  59. .appendField(Blockly.Msg.ai_basic_released)
  60. this.setOutput(true, null);
  61. this.setColour("#d42b03");
  62. var thisBlock = this;
  63. this.setTooltip(function () {
  64. var mode = thisBlock.getFieldValue('button_type_released');
  65. var TOOLTIPS = {
  66. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  67. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  68. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  69. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  70. };
  71. return TOOLTIPS[mode];
  72. });
  73. this.setHelpUrl("");
  74. }
  75. };
  76. Blockly.Python['ai_v831_button_read_released'] = function (block) {
  77. var _type = block.getFieldValue('button_type_released');
  78. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  79. sys.path.append("/root/")`
  80. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  81. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  82. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  83. key_B = BUTTON(8)
  84. key_C = BUTTON(13)
  85. key_D = BUTTON(7)
  86. `
  87. var code = `key_${_type}.is_pressed() == False`
  88. return [code, Blockly.Python.ORDER_CONDITIONAL];
  89. };
  90. Blockly.Blocks['ai_v831_button_del'] = {
  91. init: function () {
  92. this.appendDummyInput()
  93. .appendField(Blockly.Msg.ai_basic_button_when)
  94. .appendField(new Blockly.FieldDropdown([
  95. ["A", "A"],
  96. ["B", "B"],
  97. ["C", "C"],
  98. ["D", "D"]
  99. ]), "button_type_released")
  100. .appendField(Blockly.Msg.ai_basic_released)
  101. this.setPreviousStatement(true, null);
  102. this.setNextStatement(true, null);
  103. this.setColour("#d42b03");
  104. var thisBlock = this;
  105. this.setTooltip(function () {
  106. var mode = thisBlock.getFieldValue('button_type_released');
  107. var TOOLTIPS = {
  108. '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
  109. '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
  110. '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
  111. '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
  112. };
  113. return TOOLTIPS[mode];
  114. });
  115. this.setHelpUrl("");
  116. }
  117. };
  118. Blockly.Python['ai_v831_button_del'] = function (block) {
  119. var _type = block.getFieldValue('button_type_released');
  120. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  121. sys.path.append("/root/")`
  122. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  123. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  124. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  125. key_B = BUTTON(8)
  126. key_C = BUTTON(13)
  127. key_D = BUTTON(7)
  128. `
  129. var code = `key_${_type}.button.release()
  130. del key_${_type}
  131. `
  132. return code;
  133. };
  134. Blockly.Blocks['ai_v831_led_light_up'] = {
  135. init: function () {
  136. this.appendDummyInput()
  137. .appendField(Blockly.Msg.ai_basic_led_set)
  138. .appendField(new Blockly.FieldDropdown([
  139. [Blockly.Msg.ai_basic_led_blue, "blue"],
  140. // [Blockly.Msg.ai_basic_led_red, "red"]
  141. ]), "type")
  142. .appendField(Blockly.Msg.ai_basic_led_on);
  143. this.setPreviousStatement(true, null);
  144. this.setNextStatement(true, null);
  145. this.setColour("#d42b03");
  146. var thisBlock = this;
  147. this.setTooltip(function () {
  148. var mode = thisBlock.getFieldValue('type');
  149. var TOOLTIPS = {
  150. 'blue': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
  151. 'red': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
  152. };
  153. return TOOLTIPS[mode];
  154. });
  155. this.setHelpUrl("");
  156. }
  157. };
  158. Blockly.Python['ai_v831_led_light_up'] = function (block) {
  159. var dropdown_type = block.getFieldValue('type');
  160. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  161. sys.path.append("/root/")`
  162. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  163. Blockly.Python.definitions_['v831_import_time'] = `import time`
  164. Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED
  165. LED = LED()
  166. `
  167. // TODO: Assemble Python into code variable.
  168. var code = `LED.out(1)
  169. `;
  170. return code;
  171. };
  172. Blockly.Blocks['ai_v831_led_light_off'] = {
  173. init: function () {
  174. this.appendDummyInput()
  175. .appendField(Blockly.Msg.ai_basic_led_set)
  176. .appendField(new Blockly.FieldDropdown([
  177. [Blockly.Msg.ai_basic_led_blue, "blue"],
  178. // [Blockly.Msg.ai_basic_led_red, "red"]
  179. ]), "type")
  180. .appendField(Blockly.Msg.ai_basic_led_off);
  181. this.setPreviousStatement(true, null);
  182. this.setNextStatement(true, null);
  183. this.setColour("#d42b03");
  184. var thisBlock = this;
  185. this.setTooltip(function () {
  186. var mode = thisBlock.getFieldValue('type');
  187. var TOOLTIPS = {
  188. 'blue': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
  189. 'red': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
  190. };
  191. return TOOLTIPS[mode];
  192. });
  193. this.setHelpUrl("");
  194. }
  195. };
  196. Blockly.Python['ai_v831_led_light_off'] = function (block) {
  197. var dropdown_type = block.getFieldValue('type');
  198. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  199. sys.path.append("/root/")`
  200. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  201. Blockly.Python.definitions_['v831_import_time'] = `import time`
  202. Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED
  203. LED = LED()
  204. `
  205. // TODO: Assemble Python into code variable.
  206. var code = `LED.out(0)
  207. `;
  208. return code;
  209. };
  210. Blockly.Blocks['ai_v831_rgb_light_up'] = {
  211. init: function () {
  212. this.appendDummyInput()
  213. .appendField(Blockly.Msg.ai_basic_rgb_set_on)
  214. this.appendValueInput("rgb_value")
  215. .setCheck(null)
  216. .appendField("");
  217. this.appendDummyInput()
  218. .appendField(Blockly.Msg.LED_BRTN).appendField(new Blockly.FieldNumber(50, 0, 255), "uart_bps");
  219. this.setPreviousStatement(true, null);
  220. this.setNextStatement(true, null);
  221. this.setColour("#d42b03");
  222. this.setTooltip(Blockly.Msg.ai_basic_rgb_set_on);
  223. this.setHelpUrl("");
  224. }
  225. };
  226. Blockly.Python['ai_v831_rgb_light_up'] = function (block) {
  227. var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
  228. var content = block.getFieldValue('uart_bps');
  229. console.log(value_name.slice(1, -1))
  230. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  231. sys.path.append("/root/")`
  232. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  233. Blockly.Python.definitions_['v831_import_time'] = `import time`
  234. Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb
  235. singleRgb=singleRgb()`;
  236. var code = `singleRgb.setBrightness(${content})
  237. singleRgb.setColor(${value_name.slice(1, -1)})
  238. time.sleep(0.05)
  239. singleRgb.show()
  240. `;
  241. return code;
  242. };
  243. Blockly.Blocks['ai_v831_rgb_light_off'] = {
  244. init: function () {
  245. this.appendDummyInput()
  246. .appendField(Blockly.Msg.ai_basic_rgb_set_off)
  247. this.setPreviousStatement(true, null);
  248. this.setNextStatement(true, null);
  249. this.setColour("#d42b03");
  250. this.setTooltip(Blockly.Msg.ai_basic_rgb_set_off);
  251. this.setHelpUrl("");
  252. }
  253. };
  254. Blockly.Python['ai_v831_rgb_light_off'] = function (block) {
  255. var dropdown_type = block.getFieldValue('type');
  256. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  257. sys.path.append("/root/")`
  258. Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2`
  259. Blockly.Python.definitions_['v831_import_time'] = `import time`
  260. Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb
  261. singleRgb=singleRgb()`;
  262. // TODO: Assemble Python into code variable.
  263. var code = `singleRgb.setColor(0,0,0)
  264. time.sleep(0.05)
  265. singleRgb.show()
  266. `;
  267. return code;
  268. };
  269. Blockly.Blocks['ai_basic_light_up_led_analog'] = {
  270. init: function () {
  271. this.appendValueInput("brightness")
  272. .setCheck(null)
  273. .appendField(Blockly.Msg.ai_basic_led_analog_set)
  274. .appendField(new Blockly.FieldDropdown([
  275. [Blockly.Msg.ai_basic_led_analog_led1, "1"],
  276. [Blockly.Msg.ai_basic_led_analog_led2, "2"]
  277. ]), "type")
  278. .appendField(Blockly.Msg.ai_basic_led_analog_brightness_text);
  279. this.appendDummyInput()
  280. .appendField(Blockly.Msg.ai_basic_led_analog_range_text);
  281. this.setInputsInline(true);
  282. this.setPreviousStatement(true, null);
  283. this.setNextStatement(true, null);
  284. this.setColour("#d42b03");
  285. var thisBlock = this;
  286. this.setTooltip(function () {
  287. var mode = thisBlock.getFieldValue('type');
  288. var TOOLTIPS = {
  289. '1': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led1),
  290. '2': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led2)
  291. };
  292. return TOOLTIPS[mode];
  293. });
  294. this.setHelpUrl("");
  295. }
  296. };
  297. Blockly.Python['ai_basic_light_up_led_analog'] = function (block) {
  298. var dropdown_type = block.getFieldValue('type');
  299. var value_brightness = Blockly.Python.valueToCode(block, 'brightness', Blockly.Python.ORDER_ATOMIC);
  300. Blockly.Python.definitions_['v831_import_time'] = `import time`
  301. Blockly.Python.definitions_['ai_basic_light_up_led_analog_def'] = '' +
  302. 'from machine import Timer,PWM\n' +
  303. '\n' +
  304. 'led_left_tim = Timer(Timer.TIMER2, Timer.CHANNEL0, mode=Timer.MODE_PWM)\n' +
  305. 'led_right_tim = Timer(Timer.TIMER2, Timer.CHANNEL1, mode=Timer.MODE_PWM)\n' +
  306. 'led_left_ctrl = PWM(led_left_tim, freq=500000, duty=50, pin=31)\n' +
  307. 'led_right_ctrl = PWM(led_right_tim, freq=500000, duty=50, pin=32)\n' +
  308. '\n' +
  309. 'def analog_light(which, brightness):\n' +
  310. ' if which == 1:\n' +
  311. ' led_left_ctrl.duty(brightness)\n' +
  312. ' if which == 2:\n' +
  313. ' led_right_ctrl.duty(brightness)\n' +
  314. '';
  315. // TODO: Assemble Python into code variable.
  316. var code = 'analog_light(' + dropdown_type + ',' + value_brightness + ')\n';
  317. return code;
  318. };
  319. /*
  320. _ ___ ___ ____
  321. / \ |_ _| |_ _|_ __ ___ __ _ __ _ ___ | _ \ _ __ ___ ___ ___ ___ ___
  322. / _ \ | | | || '_ ` _ \ / _` |/ _` |/ _ \ | |_) | '__/ _ \ / __/ _ \/ __/ __|
  323. / ___ \ | | | || | | | | | (_| | (_| | __/ | __/| | | (_) | (_| __/\__ \__ \
  324. /_/ \_\___| |___|_| |_| |_|\__,_|\__, |\___| |_| |_| \___/ \___\___||___/___/
  325. |___/
  326. */
  327. Blockly.Blocks["ai_lcd_screeninit"] = {
  328. init: function () {
  329. this.appendDummyInput()
  330. .appendField(new Blockly.FieldImage("blockly/media/screen_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  331. this.appendDummyInput()
  332. .appendField(Blockly.Msg.image_process_lcd_init);
  333. this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_direction)
  334. .appendField(new Blockly.FieldDropdown([
  335. [Blockly.Msg.image_process_lcd_landscape_screen, "False"],
  336. [Blockly.Msg.image_process_lcd_vertical_screen, "True"]
  337. ]), "isScreen")
  338. this.setInputsInline(false);
  339. this.setPreviousStatement(true);
  340. this.setNextStatement(true);
  341. this.setColour("#5cb2d6");
  342. this.setTooltip(Blockly.Msg.ai_lcd_screeninit_TOOLTIP);
  343. this.setHelpUrl('');
  344. }
  345. }
  346. Blockly.Python.ai_lcd_screeninit = function (block) {
  347. var isScreen = block.getFieldValue('isScreen');
  348. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  349. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  350. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  351. Blockly.Python.definitions_['v831_import_os'] = `import os`
  352. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  353. def CAMERATYPE():
  354. global cameraSize
  355. try:
  356. if os.path.exists("/etc/cameraSize.cfg"):
  357. cameraSize = True
  358. else:
  359. cameraSize = False
  360. except:
  361. cameraSize = False
  362. image.load_freetype("/root/preset/fonts/simhei.ttf")
  363. CAMERATYPE()
  364. `
  365. Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = ${isScreen}`, true)
  366. var _code = `
  367. if cameraSize==True:
  368. camera.camera.config(size=(320,240))
  369. else:
  370. camera.camera.config(size=(240,320))
  371. `;
  372. return _code;;
  373. }
  374. Blockly.Blocks['ai_lcd_rotation'] = {
  375. init: function () {
  376. this.appendDummyInput()
  377. .appendField(Blockly.Msg.LCD_CANVAS)
  378. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  379. .appendField(Blockly.Msg.image_process_set_lcd_rotation)
  380. .appendField(new Blockly.FieldDropdown([
  381. ["0°", "0"],
  382. ["90°", "90"],
  383. ["180°", "180"],
  384. ["270°", "270"]
  385. ]), "DEGREE")
  386. .appendField(Blockly.Msg.CATEGORY_SHOW)
  387. this.setInputsInline(true);
  388. this.setPreviousStatement(true, null);
  389. this.setNextStatement(true, null);
  390. this.setColour("#5bb2d6");
  391. this.setTooltip(Blockly.Msg.ai_lcd_rotation_TOOLTIP);
  392. this.setHelpUrl('');
  393. }
  394. }
  395. Blockly.Python.ai_lcd_rotation = function (block) {
  396. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  397. var dropdown_name = block.getFieldValue('DEGREE');
  398. Blockly.Python.definitions_['v831_rotation_fun'] = `
  399. def screenShow(inputImg,rotationAngle):
  400. #global img_drop
  401. if rotationAngle==90 or rotationAngle == 270:
  402. screenCapture=inputImg.crop(0,0,240,320)
  403. else:
  404. screenCapture=inputImg.crop(0,0,320,240)
  405. ${variable_name}_screenShow = screenCapture.rotate(-rotationAngle,adjust=1)
  406. display.show(${variable_name}_screenShow)
  407. `
  408. let w = ''
  409. let h = ''
  410. if (dropdown_name == 90 || dropdown_name == 270) {
  411. w = 240
  412. h = 320
  413. } else {
  414. w = 320
  415. h = 240
  416. }
  417. var _code = `screenShow(${variable_name},${dropdown_name})
  418. `;
  419. return _code;;
  420. }
  421. Blockly.Blocks['ai_lcd_font'] = {
  422. init: function () {
  423. this.appendDummyInput().appendField(Blockly.Msg.image_lcd_set_font)
  424. this.appendValueInput("save_path")
  425. .setCheck(null)
  426. this.setInputsInline(true);
  427. this.setPreviousStatement(true, null);
  428. this.setNextStatement(true, null);
  429. this.setColour("#5bb2d6");
  430. this.setTooltip(Blockly.Msg.image_lcd_set_font);
  431. this.setHelpUrl('');
  432. }
  433. }
  434. Blockly.Python.ai_lcd_font = function (block) {
  435. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  436. var font_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  437. Blockly.Python.definitions_['ai_lcd_font'] = `image.load_freetype(${font_path})
  438. `
  439. var _code = "";
  440. return _code;;
  441. }
  442. Blockly.Blocks['ai_lcd_filp'] = {
  443. init: function () {
  444. this.appendDummyInput()
  445. .appendField(Blockly.Msg.image_process_set_lcd_mirror_flip)
  446. .appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox');
  447. this.setInputsInline(true);
  448. this.setPreviousStatement(true, null);
  449. this.setNextStatement(true, null);
  450. this.setColour("#5bb2d6");
  451. this.setTooltip(Blockly.Msg.ai_lcd_filp_TOOLTIP);
  452. this.setHelpUrl('');
  453. }
  454. }
  455. Blockly.Python.ai_lcd_filp = function (block) {
  456. var _tf = block.getFieldValue('TextCheckBox') == 'TRUE' ? "True" : "False";
  457. var _code = "lcd.mirror(" + _tf + ")\n";
  458. return _code;
  459. }
  460. Blockly.Blocks['ai_lcd_screen'] = {
  461. init: function () {
  462. this.appendDummyInput()
  463. .appendField(Blockly.Msg.image_process_set_filled_screen_color)
  464. .appendField(new Blockly.FieldDropdown([
  465. [Blockly.Msg.image_process_set_filled_screen_color_red, "RED"],
  466. [Blockly.Msg.image_process_set_filled_screen_color_green, "GREEN"],
  467. [Blockly.Msg.image_process_set_filled_screen_color_blue, "BLUE"],
  468. [Blockly.Msg.image_process_set_filled_screen_color_purple, "PURPLE"],
  469. [Blockly.Msg.image_process_set_filled_screen_color_cyan, "CYAN"],
  470. [Blockly.Msg.image_process_set_filled_screen_color_orange, "ORANGE"],
  471. [Blockly.Msg.image_process_set_filled_screen_color_yellow, "YELLOW"],
  472. [Blockly.Msg.image_process_set_filled_screen_color_black, "BLACK"],
  473. [Blockly.Msg.image_process_set_filled_screen_color_white, "WHITE"]
  474. ]), "COLOR");
  475. this.setInputsInline(true);
  476. this.setPreviousStatement(true, null);
  477. this.setNextStatement(true, null);
  478. this.setColour("#5bb2d6");
  479. var thisBlock = this;
  480. this.setTooltip(function () {
  481. var mode = thisBlock.getFieldValue('COLOR');
  482. var TOOLTIPS = {
  483. 'RED': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_red),
  484. 'GREEN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_green),
  485. 'BLUE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_blue),
  486. 'PURPLE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_purple),
  487. 'CYAN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_cyan),
  488. 'ORANGE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_orange),
  489. 'YELLOW': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_yellow),
  490. 'BLACK': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_black),
  491. 'WHITE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_white)
  492. };
  493. return TOOLTIPS[mode];
  494. });
  495. this.setHelpUrl('');
  496. }
  497. };
  498. Blockly.Python.ai_lcd_screen = function (block) {
  499. var colour_name = block.getFieldValue('COLOR');
  500. var _code = "lcd.clear(lcd." + colour_name + ")\n";
  501. return _code;
  502. }
  503. Blockly.Blocks['ai_lcd_fill_screen_with_rgb'] = {
  504. init: function () {
  505. this.appendDummyInput()
  506. .appendField(Blockly.Msg.image_process_text_let_canvas)
  507. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  508. .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
  509. this.appendValueInput("rgb_value")
  510. .setCheck(null)
  511. .appendField("");
  512. this.setInputsInline(true);
  513. this.setPreviousStatement(true, null);
  514. this.setNextStatement(true, null);
  515. this.setColour("#5bb2d6");
  516. this.setTooltip(Blockly.Msg.ai_lcd_fill_screen_with_rgb_TOOLTIP);
  517. this.setHelpUrl("");
  518. }
  519. };
  520. Blockly.Python['ai_lcd_fill_screen_with_rgb'] = function (block) {
  521. var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
  522. // TODO: Assemble Python into code variable.
  523. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  524. if (value_name.charAt(0) == '#') {
  525. var d = 0,
  526. e = 0,
  527. f = 0;
  528. try {
  529. 7 == value_name.length && (d = parseInt(value_name.substring(1, 3), 16),
  530. e = parseInt(value_name.substring(3, 5), 16),
  531. f = parseInt(value_name.substring(5, 7), 16))
  532. } catch (g) { }
  533. // TODO: Assemble Python into code variable.
  534. value_name = "(" + d + "," + e + "," + f + ")";
  535. }
  536. var code = `if ScreenOrientation:
  537. ${variable_name} = image.new(size = (240, 320), color = ${value_name}, mode = "RGB")
  538. else:
  539. ${variable_name} = image.new(size = (320, 240), color = ${value_name}, mode = "RGB")
  540. `;
  541. return code;
  542. };
  543. Blockly.Blocks['ai_lcd_clear'] = {
  544. init: function () {
  545. this.appendDummyInput()
  546. .appendField(Blockly.Msg.image_process_clear_lcd);
  547. this.setInputsInline(true);
  548. this.setPreviousStatement(true, null);
  549. this.setNextStatement(true, null);
  550. this.setColour("#5bb2d6");
  551. this.setTooltip(Blockly.Msg.ai_lcd_clear_TOOLTIP);
  552. this.setHelpUrl('');
  553. }
  554. };
  555. Blockly.Python.ai_lcd_clear = function (block) {
  556. var _code = "lcd.clear(lcd.BLACK)\n";
  557. return _code;
  558. }
  559. Blockly.Blocks['ai_lcd_rgb_value_input'] = {
  560. init: function () {
  561. this.appendDummyInput()
  562. .appendField(Blockly.Msg.image_process_rgb_r);
  563. this.appendValueInput("rgb_value_r")
  564. .setCheck(null)
  565. .appendField("");
  566. this.appendDummyInput()
  567. .appendField(Blockly.Msg.image_process_rgb_g);
  568. this.appendValueInput("rgb_value_g")
  569. .setCheck(null)
  570. .appendField("");
  571. this.appendDummyInput()
  572. .appendField(Blockly.Msg.image_process_rgb_b);
  573. this.appendValueInput("rgb_value_b")
  574. .setCheck(null)
  575. .appendField("");
  576. this.setInputsInline(true);
  577. this.setOutput(true, null);
  578. this.setColour("#5bb2d6");
  579. this.setTooltip(Blockly.Msg.ai_lcd_rgb_value_input_TOOLTIP);
  580. this.setHelpUrl("");
  581. }
  582. };
  583. Blockly.Python['ai_lcd_rgb_value_input'] = function (block) {
  584. var value_rgb_value_r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
  585. var value_rgb_value_g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
  586. var value_rgb_value_b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
  587. // TODO: Assemble Python into code variable.
  588. var code = '' + value_rgb_value_r + ',' + value_rgb_value_g + ',' + value_rgb_value_b + '';
  589. // TODO: Change ORDER_NONE to the correct strength.
  590. return [code, Blockly.Python.ORDER_NONE];
  591. };
  592. Blockly.Blocks.ai_lcd_XY = {
  593. init: function () {
  594. var _input = this.appendDummyInput();
  595. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  596. this.setTooltip(Blockly.Msg.ai_lcd_XY_TOOLTIP);
  597. this.setColour("#5bb2d6");
  598. this.setOutput(!0, "Boolean");
  599. _input.appendField(Blockly.Msg.image_process_xy_x);
  600. this.appendValueInput("A").setCheck("Number");
  601. _input = this.appendDummyInput();
  602. _input.appendField(Blockly.Msg.image_process_xy_y)
  603. this.appendValueInput("B").setCheck("Number");
  604. this.setInputsInline(!0);
  605. }
  606. };
  607. Blockly.Python.ai_lcd_XY = function (block) {
  608. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  609. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  610. var code = "" + _x + ", " + _y + "";
  611. return [code, Blockly.Python.ORDER_ATOMIC];
  612. };
  613. Blockly.Blocks.ai_lcd_WH = {
  614. init: function () {
  615. var _input = this.appendDummyInput();
  616. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  617. this.setTooltip(Blockly.Msg.ai_lcd_WH_TOOLTIP);
  618. this.setColour("#5bb2d6");
  619. this.setOutput(!0, "Boolean");
  620. _input.appendField(Blockly.Msg.image_process_wh_width);
  621. this.appendValueInput("A").setCheck("Number");
  622. _input = this.appendDummyInput();
  623. _input.appendField(Blockly.Msg.image_process_wh_height)
  624. this.appendValueInput("B").setCheck("Number");
  625. this.setInputsInline(!0);
  626. }
  627. };
  628. Blockly.Python.ai_lcd_WH = function (block) {
  629. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  630. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  631. var code = "" + _x + ", " + _y + "";
  632. return [code, Blockly.Python.ORDER_ATOMIC];
  633. };
  634. Blockly.Blocks['ai_lcd_colortext'] = {
  635. init: function () {
  636. this.appendDummyInput()
  637. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  638. this.appendDummyInput()
  639. .appendField(Blockly.Msg.image_process_lcd_show_text);
  640. this.appendDummyInput()
  641. .appendField(Blockly.Msg.image_process_lcd_show_text_color)
  642. .appendField(new Blockly.FieldDropdown([
  643. [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"],
  644. [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"],
  645. [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"],
  646. [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"],
  647. [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"],
  648. [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"],
  649. [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"],
  650. [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"],
  651. [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]
  652. ]), "COLOR");
  653. this.appendDummyInput()
  654. .appendField(Blockly.Msg.image_process_lcd_show_text_bg_color)
  655. .appendField(new Blockly.FieldDropdown([
  656. [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"],
  657. [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"],
  658. [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"],
  659. [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"],
  660. [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"],
  661. [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"],
  662. [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"],
  663. [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"],
  664. [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]
  665. ]), "BCOLOR");
  666. this.appendValueInput("CONTENT")
  667. .setCheck("String")
  668. .appendField(Blockly.Msg.image_process_text_content);
  669. /* this.appendDummyInput()
  670. .appendField(Blockly.Msg.LCDDT); */
  671. this.appendValueInput("POSA")
  672. .setCheck("String")
  673. .appendField(Blockly.Msg.image_process_text_start_coord);
  674. this.setPreviousStatement(true, null);
  675. this.setNextStatement(true, null);
  676. this.setColour("#5bb2d6");
  677. this.setTooltip('');
  678. this.setHelpUrl('');
  679. }
  680. };
  681. Blockly.Python['ai_lcd_colortext'] = function (block) {
  682. var color = block.getFieldValue("COLOR");
  683. var bcolor = block.getFieldValue("BCOLOR");
  684. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  685. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  686. //var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  687. var _code = "lcd_draw_string(lcd," + xy + ", " + content + ", color=" + color + ")\n"; //, scale=" + size + "
  688. // return [_code, Blockly.Python.ORDER_ATOMIC]
  689. return _code;
  690. };
  691. Blockly.Blocks["ai_lcd_createnonecarvas"] = {
  692. init: function () {
  693. this.appendDummyInput()
  694. .appendField(Blockly.Msg.image_process_create_blank_canvas)
  695. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  696. this.appendValueInput("wh")
  697. .setCheck(null)
  698. .appendField(Blockly.Msg.image_process_text_size);
  699. // this.appendDummyInput()
  700. // .appendField(Blockly.Msg.LCDDCC_F)
  701. // .appendField(new Blockly.FieldCheckbox("TRUE"), "check")
  702. // .appendField(Blockly.Msg.LCDDCC_I)
  703. // .appendField(new Blockly.FieldTextInput(""), "text");
  704. this.setInputsInline(true);
  705. this.setPreviousStatement(true, null);
  706. this.setNextStatement(true, null);
  707. this.setColour("#5cb2d6");
  708. this.setTooltip(Blockly.Msg.ai_lcd_createnonecarvas_TOOLTIP);
  709. this.setHelpUrl('');
  710. }
  711. }
  712. Blockly.Python.ai_lcd_createnonecarvas = function (block) {
  713. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  714. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  715. var _code = variable_name + " = image.new(size = (" + value_wh + "))\n";
  716. return _code;
  717. }
  718. Blockly.Blocks["ai_lcd_fillcanvas"] = {
  719. init: function () {
  720. this.appendDummyInput()
  721. .appendField(Blockly.Msg.image_process_text_let_canvas)
  722. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  723. this.appendValueInput("color")
  724. .setCheck(null)
  725. .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
  726. this.setInputsInline(true);
  727. this.setPreviousStatement(true, null);
  728. this.setNextStatement(true, null);
  729. this.setColour("#5cb2d6");
  730. this.setTooltip(Blockly.Msg.ai_lcd_fillcanvas_TOOLTIP);
  731. this.setHelpUrl('');
  732. }
  733. }
  734. Blockly.Python.ai_lcd_fillcanvas = function (block) {
  735. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  736. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  737. var _code = variable_name + '.draw_rectangle(0,0, ' + variable_name + '.width(),' + variable_name + '.height(), color=' + value_color + ', thickness=1, fill=True)\n';
  738. return _code;
  739. }
  740. Blockly.Blocks["ai_lcd_createcarvas"] = {
  741. init: function () {
  742. this.appendDummyInput()
  743. .appendField(Blockly.Msg.image_process_create_image_canvas)
  744. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  745. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.image_process_create_image_canvas_path);
  746. this.setPreviousStatement(true, null);
  747. this.setNextStatement(true, null);
  748. // this.setInputsInline(true);
  749. this.setColour("#5cb2d6");
  750. this.setTooltip(Blockly.Msg.ai_lcd_createcarvas_TOOLTIP);
  751. this.setHelpUrl('');
  752. }
  753. }
  754. Blockly.Python.ai_lcd_createcarvas = function (block) {
  755. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  756. // var checkbox_name = block.getFieldValue('check') == 'TRUE' ? "True" : "False";
  757. var text_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  758. var _code = variable_name + " = image.open(" + text_name + ")\n";
  759. return _code;
  760. }
  761. Blockly.Blocks['ai_lcd_showcarvas_set_cord'] = {
  762. init: function () {
  763. this.appendDummyInput()
  764. .appendField(Blockly.Msg.image_process_text_set_canvas_setup)
  765. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  766. this.appendValueInput("xy")
  767. .setCheck(null)
  768. .appendField(Blockly.Msg.image_process_text_start_coord_as);
  769. this.setInputsInline(true);
  770. this.setPreviousStatement(true, null);
  771. this.setNextStatement(true, null);
  772. this.setColour("#5cb2d6");
  773. this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_cord_TOOLTIP);
  774. this.setHelpUrl("");
  775. }
  776. };
  777. Blockly.Python.ai_lcd_showcarvas_set_cord = function (block) {
  778. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  779. var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  780. // TODO: Assemble Python into code variable.
  781. var code = "_" + variable_name + "_x, _" + variable_name + "_y = " + value_name + "\n";
  782. return code;
  783. };
  784. Blockly.Blocks['ai_lcd_showcarvas_set_display'] = {
  785. init: function () {
  786. this.appendDummyInput()
  787. .appendField(Blockly.Msg.image_process_show_canvas)
  788. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  789. this.setInputsInline(false);
  790. this.setPreviousStatement(true, null);
  791. this.setNextStatement(true, null);
  792. this.setColour("#5cb2d6");
  793. this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_display_TOOLTIP);
  794. this.setHelpUrl("");
  795. }
  796. };
  797. Blockly.Python.ai_lcd_showcarvas_set_display = function (block) {
  798. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  799. Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
  800. Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
  801. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  802. Blockly.Python.definitions_['v831_import_time'] = `import time`
  803. Blockly.Python.addVariable(`_${variable_name}_x`, `_${variable_name}_x = 0`, true)
  804. Blockly.Python.addVariable(`_${variable_name}_y`, `_${variable_name}_y = 0`, true)
  805. Blockly.Python.definitions_[`v831_display_show_${variable_name}`] = `def v831_display_show_${variable_name}(displayShow):
  806. global _${variable_name}_y,_${variable_name}_x,ScreenOrientation,cameraSize
  807. CANVASSHOWIMGAGE = ""
  808. if ScreenOrientation:
  809. displayShowCanvas = image.new(size = (240, 320))
  810. displayShowCanvas.draw_rectangle(0,0,240,320, color=(0,0,0), thickness=-1)
  811. displayShowCanvas.draw_image(displayShow,_${variable_name}_x,_${variable_name}_y,alpha=1)
  812. displayShowVER = displayShowCanvas.crop(0,0,240,320)
  813. displayShowVER = displayShowVER.rotate(-90, adjust=1)
  814. display.show(displayShowVER)
  815. else:
  816. displayShowCanvas = image.new(size = (320, 240))
  817. displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1)
  818. displayShowCanvas.draw_image(displayShow,_${variable_name}_x,_${variable_name}_y,alpha=1)
  819. display.show(displayShowCanvas)
  820. `
  821. var code = `v831_display_show_${variable_name}(${variable_name})
  822. `;
  823. return code;
  824. };
  825. Blockly.Blocks['ai_lcd_showcarvas'] = {
  826. init: function () {
  827. this.appendDummyInput()
  828. .appendField(Blockly.Msg.image_process_show_canvas)
  829. .appendField(new Blockly.FieldVariable("canvas"), "varitem");
  830. this.appendValueInput("xy")
  831. .setCheck(null)
  832. .appendField(Blockly.Msg.image_process_text_start_coord);
  833. this.setInputsInline(false);
  834. this.setPreviousStatement(true, null);
  835. this.setNextStatement(true, null);
  836. this.setColour("#5cb2d6");
  837. this.setTooltip("");
  838. this.setHelpUrl("");
  839. }
  840. };
  841. Blockly.Python.ai_lcd_showcarvas = function (block) {
  842. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  843. var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  844. // TODO: Assemble Python into code variable.
  845. var code = "lcd.display(" + variable_name + ", oft=(" + value_name + "))\n";
  846. return code;
  847. };
  848. Blockly.Blocks['ai_lcd_clearcanvas'] = {
  849. init: function () {
  850. this.appendDummyInput()
  851. .appendField(Blockly.Msg.image_process_clear_canvas_1)
  852. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  853. .appendField(Blockly.Msg.image_process_clear_canvas_2);
  854. this.setPreviousStatement(true, null);
  855. this.setNextStatement(true, null);
  856. this.setColour("#5bb2d6");
  857. this.setTooltip(Blockly.Msg.ai_lcd_clearcanvas_TOOLTIP);
  858. this.setHelpUrl('');
  859. }
  860. }
  861. Blockly.Python.ai_lcd_clearcanvas = function (block) {
  862. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  863. var _code = variable_name + ".clear()\n";
  864. return _code;;
  865. }
  866. Blockly.Blocks['lcd_set_position'] = {
  867. init: function () {
  868. this.appendValueInput("POSX")
  869. .setCheck("Number")
  870. .appendField("X:");
  871. this.appendValueInput("POSY")
  872. .setCheck("Number")
  873. .appendField("Y:");
  874. this.setOutput(true, "String");
  875. this.setInputsInline(true);
  876. this.setColour("#5bb2d6");
  877. this.setTooltip("");
  878. this.setHelpUrl("");
  879. }
  880. };
  881. Blockly.Python['lcd_set_position'] = function (block) {
  882. // var reg = /^?[0-9]\d*$/
  883. var pos_x = Blockly.Python.valueToCode(block, 'POSX', Blockly.Python.ORDER_ATOMIC);
  884. var pos_y = Blockly.Python.valueToCode(block, 'POSY', Blockly.Python.ORDER_ATOMIC);
  885. //var code = posConvert(pos_x, pos_y);
  886. var code = pos_x + "," + pos_y;
  887. return [code, Blockly.Python.ORDER_ATOMIC];
  888. };
  889. Blockly.Blocks['lcd_set_color'] = {
  890. init: function () {
  891. this.appendDummyInput()
  892. .appendField(Blockly.Msg.COLOR)
  893. .appendField(new Blockly.FieldColour("#ff0000"), "COLOR");
  894. this.setOutput(true, "String");
  895. this.setColour("#5bb2d6");
  896. this.setTooltip("");
  897. this.setHelpUrl("");
  898. }
  899. };
  900. Blockly.Python['lcd_set_color'] = function (block) {
  901. var code = block.getFieldValue('COLOR');
  902. return [code, Blockly.Python.ORDER_ATOMIC];
  903. };
  904. Blockly.Blocks['lcd_set_width_height'] = {
  905. init: function () {
  906. this.appendValueInput("WIDTH")
  907. .setCheck("Number")
  908. .appendField(Blockly.Msg.OLCD_WIDTH);
  909. this.appendValueInput("HEIGHT")
  910. .setCheck("Number")
  911. .appendField(Blockly.Msg.OLCD_HEIGHT);
  912. this.setOutput(true, "String");
  913. this.setInputsInline(true);
  914. this.setColour("#5bb2d6");
  915. this.setTooltip("");
  916. this.setHelpUrl("");
  917. }
  918. };
  919. Blockly.Python['lcd_set_width_height'] = function (block) {
  920. var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC);
  921. var height = Blockly.Python.valueToCode(block, 'HEIGHT', Blockly.Python.ORDER_ATOMIC);
  922. var code = width + ', ' + height;
  923. return [code, Blockly.Python.ORDER_ATOMIC];
  924. };
  925. // ai_lcd_textcarvas_new_line
  926. Blockly.Blocks['ai_lcd_textcarvas_new_line'] = {
  927. init: function () {
  928. this.appendDummyInput()
  929. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  930. this.appendDummyInput()
  931. .appendField(Blockly.Msg.image_process_text_on_canvas)
  932. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  933. .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text);
  934. this.appendValueInput("POSA")
  935. .setCheck("String")
  936. .appendField(Blockly.Msg.image_process_text_start_coord);
  937. this.appendValueInput("CONTENT")
  938. .setCheck("String")
  939. .appendField(Blockly.Msg.image_process_text_content);
  940. this.appendValueInput("dispalyStr")
  941. .setCheck("Number")
  942. .appendField(Blockly.Msg.image_process_text_dispalyStr);
  943. this.appendValueInput("buttonUp")
  944. .setCheck("String")
  945. .appendField(Blockly.Msg.image_process_text_buttonUp);
  946. this.appendValueInput("buttonDown")
  947. .setCheck("String")
  948. .appendField(Blockly.Msg.image_process_text_buttonDown);
  949. this.appendValueInput("COLOR")
  950. .setCheck("String")
  951. .appendField(Blockly.Msg.image_process_text_color);
  952. this.appendValueInput("Scale")
  953. .setCheck("Number")
  954. .appendField(Blockly.Msg.image_process_draw_text_font_size);
  955. this.appendValueInput("LineNum")
  956. .setCheck("Number")
  957. .appendField(Blockly.Msg.image_process_text_line_heigit);
  958. // this.appendDummyInput()
  959. // .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
  960. // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
  961. this.setInputsInline(false);
  962. this.setPreviousStatement(true);
  963. this.setNextStatement(true);
  964. this.setColour("#5bb2d6");
  965. this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
  966. this.setHelpUrl('');
  967. }
  968. };
  969. Blockly.Python.ai_lcd_textcarvas_new_line = function (block) {
  970. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  971. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  972. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  973. var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  974. var LineNum = Blockly.Python.valueToCode(block, 'LineNum', Blockly.Python.ORDER_ATOMIC);
  975. var dispalyStr = Blockly.Python.valueToCode(block, 'dispalyStr', Blockly.Python.ORDER_ATOMIC);
  976. var buttonUp = Blockly.Python.valueToCode(block, 'buttonUp', Blockly.Python.ORDER_ATOMIC);
  977. var buttonDown = Blockly.Python.valueToCode(block, 'buttonDown', Blockly.Python.ORDER_ATOMIC);
  978. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  979. var _code = ""
  980. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  981. sys.path.append("/root/")`
  982. Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
  983. // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
  984. Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14)
  985. key_B = BUTTON(8)
  986. key_C = BUTTON(13)
  987. key_D = BUTTON(7)`
  988. Blockly.Python.definitions_["ai_lcd_textcarvas_new_line"] = `BUTTONNUMBER = 0
  989. def textCanvasNewLine(canvasName,posax,posay,text,Num,buttonUp,buttonDown,Scale,Color,LineNum):
  990. global BUTTONNUMBER
  991. numText = len(text)//Num + 1
  992. lineHeight = 240
  993. if ScreenOrientation:
  994. lineHeight = 320
  995. if numText>(lineHeight//LineNum):
  996. if buttonUp:
  997. time.sleep(0.1)
  998. if BUTTONNUMBER<int(numText-(lineHeight//LineNum))+ int(posay/LineNum):
  999. BUTTONNUMBER = BUTTONNUMBER + 1
  1000. elif buttonDown:
  1001. time.sleep(0.1)
  1002. if BUTTONNUMBER>0:
  1003. BUTTONNUMBER = BUTTONNUMBER - 1
  1004. #BUTTONNUMBER = BUTTONNUMBER + (posay/LineNum)
  1005. for i in range(numText):
  1006. canvasName.draw_string(posax,posay+int(i*LineNum),text[int((i+BUTTONNUMBER)*Num):int((i+1+BUTTONNUMBER)*Num)], scale = Scale, color = Color, thickness = 1)
  1007. # canvasName.draw_string(posax,posay,str(text), scale = Scale, color = Color, thickness = 1)
  1008. `
  1009. if (color.charAt(0) == '#') {
  1010. var d = 0,
  1011. e = 0,
  1012. f = 0;
  1013. try {
  1014. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1015. e = parseInt(color.substring(3, 5), 16),
  1016. f = parseInt(color.substring(5, 7), 16))
  1017. } catch (g) { }
  1018. var bool = "False";
  1019. // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
  1020. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1021. // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
  1022. _code = `textCanvasNewLine(${variable_name},${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},(${d} ,${e}, ${f}),${LineNum})\n`
  1023. // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
  1024. } else if (color.charAt(0) != '#') {
  1025. var d = 0,
  1026. e = 0,
  1027. f = 0;
  1028. try {
  1029. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1030. e = parseInt(color.substring(3, 5), 16),
  1031. f = parseInt(color.substring(5, 7), 16))
  1032. } catch (g) { }
  1033. _code = `textCanvasNewLine(${variable_name},${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},${color},${LineNum})\n`
  1034. // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
  1035. // '';
  1036. }
  1037. return _code;
  1038. }
  1039. Blockly.Blocks['ai_lcd_textcarvas'] = {
  1040. init: function () {
  1041. this.appendDummyInput()
  1042. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1043. this.appendDummyInput()
  1044. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1045. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1046. .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text);
  1047. this.appendValueInput("POSA")
  1048. .setCheck("String")
  1049. .appendField(Blockly.Msg.image_process_text_start_coord);
  1050. this.appendValueInput("CONTENT")
  1051. .setCheck("String")
  1052. .appendField(Blockly.Msg.image_process_text_content);
  1053. this.appendValueInput("COLOR")
  1054. .setCheck("String")
  1055. .appendField(Blockly.Msg.image_process_text_color);
  1056. this.appendValueInput("Scale")
  1057. .setCheck("Number")
  1058. .appendField(Blockly.Msg.image_process_draw_text_font_size);
  1059. // this.appendDummyInput()
  1060. // .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
  1061. // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
  1062. this.setInputsInline(false);
  1063. this.setPreviousStatement(true);
  1064. this.setNextStatement(true);
  1065. this.setColour("#5bb2d6");
  1066. this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
  1067. this.setHelpUrl('');
  1068. }
  1069. };
  1070. Blockly.Python.ai_lcd_textcarvas = function (block) {
  1071. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1072. var _code = ""
  1073. if (color.charAt(0) == '#') {
  1074. var d = 0,
  1075. e = 0,
  1076. f = 0;
  1077. try {
  1078. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1079. e = parseInt(color.substring(3, 5), 16),
  1080. f = parseInt(color.substring(5, 7), 16))
  1081. } catch (g) { }
  1082. var bool = "False";
  1083. // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
  1084. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1085. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1086. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1087. var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1088. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1089. // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
  1090. _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
  1091. } else if (color.charAt(0) != '#') {
  1092. var d = 0,
  1093. e = 0,
  1094. f = 0;
  1095. try {
  1096. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1097. e = parseInt(color.substring(3, 5), 16),
  1098. f = parseInt(color.substring(5, 7), 16))
  1099. } catch (g) { }
  1100. var bool = "False";
  1101. // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
  1102. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1103. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1104. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1105. var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1106. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1107. _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
  1108. '';
  1109. }
  1110. return _code;
  1111. }
  1112. Blockly.Blocks['ai_lcd_characterscarvas'] = {
  1113. init: function () {
  1114. this.appendDummyInput()
  1115. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_hanzi_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1116. this.appendDummyInput()
  1117. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1118. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1119. .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_characters);
  1120. this.appendValueInput("POSA")
  1121. .setCheck("String")
  1122. .appendField(Blockly.Msg.image_process_text_start_coord);
  1123. this.appendValueInput("CONTENT")
  1124. .setCheck("String")
  1125. .appendField(Blockly.Msg.image_process_text_content);
  1126. this.appendValueInput("COLOR")
  1127. .setCheck("String")
  1128. .appendField(Blockly.Msg.image_process_text_color);
  1129. this.appendDummyInput()
  1130. .appendField(Blockly.Msg.image_process_draw_text_font_size + ":")
  1131. // .setCheck(null)
  1132. .appendField(new Blockly.FieldDropdown([
  1133. [Blockly.Msg.SMALL, "1"],
  1134. [Blockly.Msg.MIDDLE, "2"],
  1135. [Blockly.Msg.LARGE, "3"]
  1136. ]), "fonts");
  1137. // this.appendDummyInput()
  1138. // .appendField(Blockly.Msg.Set_Auto_Wrap + ":")
  1139. // // .setCheck(null)
  1140. // .appendField(new Blockly.FieldDropdown([
  1141. // [Blockly.Msg.LED_SCROLL_YES, "True"],
  1142. // [Blockly.Msg.LED_SCROLL_NO, "False"]
  1143. // ]), "wraps");
  1144. this.setInputsInline(false);
  1145. this.setPreviousStatement(true);
  1146. this.setNextStatement(true);
  1147. this.setColour("#5bb2d6");
  1148. this.setTooltip(Blockly.Msg.ai_lcd_characterscarvas_TOOLTIP);
  1149. this.setHelpUrl('');
  1150. }
  1151. };
  1152. Blockly.Python.ai_lcd_characterscarvas = function (block) {
  1153. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1154. var _code = ''
  1155. if (color.charAt(0) == '#') {
  1156. var d = 0,
  1157. e = 0,
  1158. f = 0;
  1159. try {
  1160. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1161. e = parseInt(color.substring(3, 5), 16),
  1162. f = parseInt(color.substring(5, 7), 16))
  1163. } catch (g) { }
  1164. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1165. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1166. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1167. var size = block.getFieldValue('fonts');;
  1168. // var wraps = block.getFieldValue('wraps');
  1169. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1170. _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n";
  1171. } else if (color.charAt(0) != '#') {
  1172. var d = 0,
  1173. e = 0,
  1174. f = 0;
  1175. try {
  1176. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1177. e = parseInt(color.substring(3, 5), 16),
  1178. f = parseInt(color.substring(5, 7), 16))
  1179. } catch (g) { }
  1180. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1181. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1182. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1183. var size = block.getFieldValue('fonts');;
  1184. // var wraps = block.getFieldValue('wraps');
  1185. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1186. _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=" + color + ", font_size=" + size + ")\n";
  1187. }
  1188. return _code;
  1189. }
  1190. Blockly.Blocks['ai_lcd_linecarvas'] = {
  1191. init: function () {
  1192. this.appendDummyInput()
  1193. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1194. this.appendDummyInput()
  1195. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1196. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1197. .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_line);
  1198. this.appendValueInput("POSA")
  1199. .setCheck("String")
  1200. .appendField(Blockly.Msg.image_process_text_start_coord);
  1201. this.appendValueInput("POSB")
  1202. .setCheck("String")
  1203. .appendField(Blockly.Msg.image_process_text_end_coord);
  1204. this.appendValueInput("COLOR")
  1205. .setCheck("String")
  1206. .appendField(Blockly.Msg.image_process_text_color);
  1207. this.appendValueInput("Scale")
  1208. .setCheck("Number")
  1209. .appendField(Blockly.Msg.image_process_text_thick);
  1210. this.setInputsInline(false);
  1211. this.setPreviousStatement(true);
  1212. this.setNextStatement(true);
  1213. this.setColour("#5bb2d6");
  1214. this.setTooltip(Blockly.Msg.ai_lcd_linecarvas_TOOLTIP);
  1215. this.setHelpUrl('');
  1216. }
  1217. };
  1218. Blockly.Python.ai_lcd_linecarvas = function (block) {
  1219. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1220. if (color.charAt(0) == '#') {
  1221. var d = 0,
  1222. e = 0,
  1223. f = 0;
  1224. try {
  1225. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1226. e = parseInt(color.substring(3, 5), 16),
  1227. f = parseInt(color.substring(5, 7), 16))
  1228. } catch (g) { }
  1229. var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1230. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1231. var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1232. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1233. var _code = variable_name + ".draw_line(" + xy + ", " + xy2 + ", color=(" + d + "," + e + "," + f + "), thickness=" + size + ")\n";
  1234. } else if (color.charAt(0) != '#') {
  1235. var d = 0,
  1236. e = 0,
  1237. f = 0;
  1238. try {
  1239. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1240. e = parseInt(color.substring(3, 5), 16),
  1241. f = parseInt(color.substring(5, 7), 16))
  1242. } catch (g) { }
  1243. var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1244. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1245. var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1246. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1247. var _code = variable_name + ".draw_line(" + xy + ", " + xy2 + ", color=" + color + ", thickness=" + size + ")\n";
  1248. }
  1249. return _code;
  1250. }
  1251. Blockly.Blocks['ai_lcd_draw_rectangle'] = {
  1252. init: function () {
  1253. // this.appendDummyInput()
  1254. // .appendField(
  1255. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  1256. this.appendDummyInput()
  1257. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1258. this.appendDummyInput()
  1259. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1260. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1261. .appendField(Blockly.Msg.image_process_text_on_draw)
  1262. .appendField(new Blockly.FieldDropdown([
  1263. [Blockly.Msg.image_process_text_filled, "fillrect"],
  1264. [Blockly.Msg.image_process_text_stroked, "rect"]
  1265. ]), "rect_type")
  1266. .appendField(Blockly.Msg.image_process_draw_rectangle_text);
  1267. this.appendValueInput("POSA")
  1268. .setCheck("String")
  1269. .appendField(Blockly.Msg.image_process_text_start_coord);
  1270. this.appendValueInput("POSB")
  1271. .setCheck("String")
  1272. .appendField(Blockly.Msg.image_process_text_size);
  1273. this.appendValueInput("COLOR")
  1274. .setCheck("String")
  1275. .appendField(Blockly.Msg.image_process_text_color);
  1276. // this.appendValueInput("Scale")
  1277. // .setCheck("Number")
  1278. // .appendField(Blockly.Msg.image_process_text_thick);
  1279. this.setInputsInline(false);
  1280. this.setPreviousStatement(true);
  1281. this.setNextStatement(true);
  1282. this.setColour("#5bb2d6");
  1283. var thisBlock = this;
  1284. this.setTooltip(function () {
  1285. var mode = thisBlock.getFieldValue('rect_type');
  1286. var TOOLTIPS = {
  1287. 'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
  1288. 'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
  1289. };
  1290. return TOOLTIPS[mode];
  1291. });
  1292. this.setHelpUrl('');
  1293. }
  1294. };
  1295. Blockly.Python.ai_lcd_draw_rectangle = function (block) {
  1296. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1297. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1298. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1299. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1300. var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1301. // console.log(xy.split(','),size.split(','))
  1302. let a = xy.split(',')
  1303. let b = size.split(',')
  1304. let w = Number(a[0])+Number(b[0])
  1305. let h = Number(a[1])+Number(b[1])
  1306. var _code = ''
  1307. if (color.charAt(0) == '#') {
  1308. var d = 0,
  1309. e = 0,
  1310. f = 0;
  1311. try {
  1312. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1313. e = parseInt(color.substring(3, 5), 16),
  1314. f = parseInt(color.substring(5, 7), 16))
  1315. } catch (g) { }
  1316. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1317. // var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1318. // var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1319. // var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1320. // var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1321. _code = `${variable_name}.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=(${d},${e},${f}), thickness=${type})
  1322. `
  1323. } else if (color.charAt(0) != '#') {
  1324. _code = `${variable_name}.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=${color}, thickness=${type})
  1325. `
  1326. }
  1327. return _code;
  1328. }
  1329. Blockly.Blocks['ai_lcd_ractanglecarvas'] = {
  1330. init: function () {
  1331. // this.appendDummyInput()
  1332. // .appendField(
  1333. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  1334. this.appendDummyInput()
  1335. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1336. this.appendDummyInput()
  1337. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1338. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1339. .appendField(Blockly.Msg.image_process_text_on_draw)
  1340. .appendField(new Blockly.FieldDropdown([
  1341. [Blockly.Msg.image_process_text_filled, "fillrect"],
  1342. [Blockly.Msg.image_process_text_stroked, "rect"]
  1343. ]), "rect_type")
  1344. .appendField(Blockly.Msg.image_process_draw_rectangle_text);
  1345. this.appendValueInput("POSA")
  1346. .setCheck("String")
  1347. .appendField(Blockly.Msg.image_process_text_start_coord);
  1348. this.appendValueInput("POSB")
  1349. .setCheck("String")
  1350. .appendField(Blockly.Msg.image_process_text_end_coord);
  1351. this.appendValueInput("COLOR")
  1352. .setCheck("String")
  1353. .appendField(Blockly.Msg.image_process_text_color);
  1354. // this.appendValueInput("Scale")
  1355. // .setCheck("Number")
  1356. // .appendField(Blockly.Msg.image_process_text_thick);
  1357. this.setInputsInline(false);
  1358. this.setPreviousStatement(true);
  1359. this.setNextStatement(true);
  1360. this.setColour("#5bb2d6");
  1361. var thisBlock = this;
  1362. this.setTooltip(function () {
  1363. var mode = thisBlock.getFieldValue('rect_type');
  1364. var TOOLTIPS = {
  1365. 'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
  1366. 'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
  1367. };
  1368. return TOOLTIPS[mode];
  1369. });
  1370. this.setHelpUrl('');
  1371. }
  1372. };
  1373. Blockly.Python.ai_lcd_ractanglecarvas = function (block) {
  1374. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1375. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1376. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1377. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1378. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1379. var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1380. // console.log(size,"111111111111")
  1381. // // console.log(xy.split(','),size.split(','))
  1382. // let a = xy.split(',')
  1383. // let b = size.split(',')
  1384. // let w = Number(a[0])+Number(b[0])
  1385. // let h = Number(a[1])+Number(b[1])
  1386. // let wh = `${w},${h}`
  1387. // console.log('wh',wh)
  1388. var _code = ''
  1389. if (color.charAt(0) == '#') {
  1390. var d = 0,
  1391. e = 0,
  1392. f = 0;
  1393. try {
  1394. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1395. e = parseInt(color.substring(3, 5), 16),
  1396. f = parseInt(color.substring(5, 7), 16))
  1397. } catch (g) { }
  1398. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1399. // var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1400. // var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1401. // var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1402. // var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
  1403. _code = `${variable_name}.draw_rectangle(${xy},${size}, color=(${d},${e},${f}), thickness=${type})
  1404. `
  1405. } else if (color.charAt(0) != '#') {
  1406. _code = `${variable_name}.draw_rectangle(${xy},${size}, color=${color}, thickness=${type})
  1407. `
  1408. }
  1409. return _code;
  1410. }
  1411. Blockly.Blocks['ai_lcd_drawcirclecarvas'] = {
  1412. init: function () {
  1413. this.appendDummyInput()
  1414. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1415. // this.appendDummyInput()
  1416. // .appendField(
  1417. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  1418. this.appendDummyInput()
  1419. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1420. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1421. .appendField(Blockly.Msg.image_process_text_on_draw)
  1422. .appendField(new Blockly.FieldDropdown([
  1423. [Blockly.Msg.image_process_text_filled, "fillrect"],
  1424. [Blockly.Msg.image_process_text_stroked, "rect"]
  1425. ]), "rect_type")
  1426. .appendField(Blockly.Msg.image_process_draw_circle_text);
  1427. this.appendValueInput("POSA")
  1428. .setCheck("String")
  1429. .appendField(Blockly.Msg.image_process_draw_circle_text_start);
  1430. this.appendValueInput("Scale")
  1431. .setCheck("Number")
  1432. .appendField(Blockly.Msg.image_process_text_radius);
  1433. this.appendValueInput("COLOR")
  1434. .setCheck("String")
  1435. .appendField(Blockly.Msg.image_process_text_color);
  1436. this.appendValueInput("Scale_0")
  1437. .setCheck("Number")
  1438. .appendField(Blockly.Msg.image_process_text_thick);
  1439. this.setInputsInline(false);
  1440. this.setPreviousStatement(true);
  1441. this.setNextStatement(true);
  1442. this.setColour("#5bb2d6");
  1443. var thisBlock = this;
  1444. this.setTooltip(function () {
  1445. var mode = thisBlock.getFieldValue('rect_type');
  1446. var TOOLTIPS = {
  1447. 'fillrect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
  1448. 'rect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
  1449. };
  1450. return TOOLTIPS[mode];
  1451. });
  1452. this.setHelpUrl('');
  1453. }
  1454. };
  1455. Blockly.Python.ai_lcd_drawcirclecarvas = function (block) {
  1456. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1457. if (color.charAt(0) == '#') {
  1458. var d = 0,
  1459. e = 0,
  1460. f = 0;
  1461. try {
  1462. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1463. e = parseInt(color.substring(3, 5), 16),
  1464. f = parseInt(color.substring(5, 7), 16))
  1465. } catch (g) { }
  1466. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1467. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1468. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1469. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1470. var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
  1471. var _code = variable_name + ".draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + type + ")\n";
  1472. } else if (color.charAt(0) != '#') {
  1473. var d = 0,
  1474. e = 0,
  1475. f = 0;
  1476. try {
  1477. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1478. e = parseInt(color.substring(3, 5), 16),
  1479. f = parseInt(color.substring(5, 7), 16))
  1480. } catch (g) { }
  1481. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1482. var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
  1483. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1484. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1485. var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
  1486. var _code = variable_name + ".draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + type + ")\n";
  1487. }
  1488. return _code;
  1489. }
  1490. // 椭圆,暂无具体位置参数
  1491. Blockly.Blocks['ai_lcd_drawcir_ellipse'] = {
  1492. init: function () {
  1493. this.appendDummyInput()
  1494. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1495. // this.appendDummyInput()
  1496. // .appendField(
  1497. // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
  1498. this.appendDummyInput()
  1499. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1500. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1501. .appendField(Blockly.Msg.image_process_text_on_draw)
  1502. .appendField(new Blockly.FieldDropdown([
  1503. [Blockly.Msg.image_process_text_filled, "fillrect"],
  1504. [Blockly.Msg.image_process_text_stroked, "rect"]
  1505. ]), "rect_type")
  1506. .appendField(Blockly.Msg.image_process_draw_ellipse_text);
  1507. this.appendValueInput("POSA")
  1508. .setCheck("String")
  1509. .appendField(Blockly.Msg.image_process_draw_circle_text_start);
  1510. this.appendValueInput("Scale")
  1511. .setCheck("Number")
  1512. .appendField(Blockly.Msg.image_process_text_radius);
  1513. this.appendValueInput("COLOR")
  1514. .setCheck("String")
  1515. .appendField(Blockly.Msg.image_process_text_color);
  1516. this.appendValueInput("Scale_0")
  1517. .setCheck("Number")
  1518. .appendField(Blockly.Msg.image_process_text_thick);
  1519. this.setInputsInline(false);
  1520. this.setPreviousStatement(true);
  1521. this.setNextStatement(true);
  1522. this.setColour("#5bb2d6");
  1523. var thisBlock = this;
  1524. this.setTooltip(function () {
  1525. var mode = thisBlock.getFieldValue('rect_type');
  1526. var TOOLTIPS = {
  1527. 'fillrect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
  1528. 'rect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
  1529. };
  1530. return TOOLTIPS[mode];
  1531. });
  1532. this.setHelpUrl('');
  1533. }
  1534. };
  1535. Blockly.Python.ai_lcd_drawcir_ellipse = function (block) {
  1536. var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
  1537. if (color.charAt(0) == '#') {
  1538. var d = 0,
  1539. e = 0,
  1540. f = 0;
  1541. try {
  1542. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1543. e = parseInt(color.substring(3, 5), 16),
  1544. f = parseInt(color.substring(5, 7), 16))
  1545. } catch (g) { }
  1546. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1547. var type = block.getFieldValue('rect_type') == "fillrect" ? "1" : "-1";
  1548. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1549. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1550. var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
  1551. var _code = variable_name + ".draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + type + ")\n";
  1552. } else if (color.charAt(0) != '#') {
  1553. var d = 0,
  1554. e = 0,
  1555. f = 0;
  1556. try {
  1557. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1558. e = parseInt(color.substring(3, 5), 16),
  1559. f = parseInt(color.substring(5, 7), 16))
  1560. } catch (g) { }
  1561. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1562. var type = block.getFieldValue('rect_type') == "fillrect" ? "1" : "-1";
  1563. var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1564. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1565. var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
  1566. var _code = variable_name + ".draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + type + ")\n";
  1567. }
  1568. return _code;;
  1569. }
  1570. Blockly.Blocks['ai_lcd_draw_cross_sign'] = {
  1571. init: function () {
  1572. this.appendDummyInput()
  1573. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_cross.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1574. this.appendDummyInput()
  1575. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1576. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1577. .appendField(Blockly.Msg.image_process_draw_cross_title);
  1578. this.appendValueInput("xy")
  1579. .setCheck(null)
  1580. .appendField(Blockly.Msg.image_process_draw_cross_centerpos);
  1581. this.appendValueInput("size")
  1582. .setCheck(null)
  1583. .appendField(Blockly.Msg.image_process_draw_cross_length);
  1584. this.appendValueInput("thickness")
  1585. .setCheck(null)
  1586. .appendField(Blockly.Msg.image_process_draw_cross_thick);
  1587. this.appendValueInput("color")
  1588. .setCheck(null)
  1589. .appendField(Blockly.Msg.image_process_draw_cross_color);
  1590. this.setInputsInline(false);
  1591. this.setPreviousStatement(true, null);
  1592. this.setNextStatement(true, null);
  1593. this.setColour("#5bb2d6");
  1594. this.setTooltip(Blockly.Msg.ai_lcd_draw_cross_sign_TOOLTIP);
  1595. this.setHelpUrl("");
  1596. }
  1597. };
  1598. Blockly.Python['ai_lcd_draw_cross_sign'] = function (block) {
  1599. var color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  1600. if (color.charAt(0) == '#') {
  1601. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1602. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  1603. var value_size = Blockly.Python.valueToCode(block, 'size', Blockly.Python.ORDER_ATOMIC);
  1604. var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC);
  1605. var d = 0,
  1606. e = 0,
  1607. f = 0;
  1608. try {
  1609. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1610. e = parseInt(color.substring(3, 5), 16),
  1611. f = parseInt(color.substring(5, 7), 16))
  1612. } catch (g) { }
  1613. // TODO: Assemble Python into code variable.
  1614. var code = variable_name + '.draw_cross(' + value_xy + ', color=(' + d + ', ' + e + ', ' + f + '), size=' + value_size + ', thickness=' + value_thickness + ')\n';
  1615. } else if (color.charAt(0) != '#') {
  1616. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1617. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  1618. var value_size = Blockly.Python.valueToCode(block, 'size', Blockly.Python.ORDER_ATOMIC);
  1619. var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC);
  1620. // TODO: Assemble Python into code variable.
  1621. var code = variable_name + '.draw_cross(' + value_xy + ', color=' + color + ', size=' + value_size + ', thickness=' + value_thickness + ')\n';
  1622. }
  1623. return code;
  1624. };
  1625. Blockly.Blocks['ai_lcd_draw_arrow_sign'] = {
  1626. init: function () {
  1627. this.appendDummyInput()
  1628. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_arrow.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1629. this.appendDummyInput()
  1630. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1631. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1632. .appendField(Blockly.Msg.image_process_draw_arrow_title);
  1633. this.appendValueInput("xy1")
  1634. .setCheck(null)
  1635. .appendField(Blockly.Msg.image_process_draw_arrow_start);
  1636. this.appendValueInput("xy2")
  1637. .setCheck(null)
  1638. .appendField(Blockly.Msg.image_process_draw_arrow_end);
  1639. this.appendValueInput("color")
  1640. .setCheck(null)
  1641. .appendField(Blockly.Msg.image_process_draw_arrow_color);
  1642. this.appendValueInput("thickness")
  1643. .setCheck(null)
  1644. .appendField(Blockly.Msg.image_process_draw_arrow_thick);
  1645. this.setInputsInline(false);
  1646. this.setPreviousStatement(true, null);
  1647. this.setNextStatement(true, null);
  1648. this.setColour("#5bb2d6");
  1649. this.setTooltip(Blockly.Msg.ai_lcd_draw_arrow_sign_TOOLTIP);
  1650. this.setHelpUrl("");
  1651. }
  1652. };
  1653. Blockly.Python['ai_lcd_draw_arrow_sign'] = function (block) {
  1654. // TODO: Assemble Python into code variable.
  1655. var color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  1656. if (color.charAt(0) == '#') {
  1657. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1658. var value_xy1 = Blockly.Python.valueToCode(block, 'xy1', Blockly.Python.ORDER_ATOMIC);
  1659. var value_xy2 = Blockly.Python.valueToCode(block, 'xy2', Blockly.Python.ORDER_ATOMIC);
  1660. var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC);
  1661. var d = 0,
  1662. e = 0,
  1663. f = 0;
  1664. try {
  1665. 7 == color.length && (d = parseInt(color.substring(1, 3), 16),
  1666. e = parseInt(color.substring(3, 5), 16),
  1667. f = parseInt(color.substring(5, 7), 16))
  1668. } catch (g) { }
  1669. // TODO: Assemble Python into code variable.
  1670. var code = variable_name + '.draw_arrow(' + value_xy1 + ',' + value_xy2 + ', color=(' + d + ', ' + e + ', ' + f + '), thickness=' + value_thickness + ')\n';
  1671. } else if (color.charAt(0) != '#') {
  1672. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1673. var value_xy1 = Blockly.Python.valueToCode(block, 'xy1', Blockly.Python.ORDER_ATOMIC);
  1674. var value_xy2 = Blockly.Python.valueToCode(block, 'xy2', Blockly.Python.ORDER_ATOMIC);
  1675. var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC);
  1676. // TODO: Assemble Python into code variable.
  1677. var code = variable_name + '.draw_arrow(' + value_xy1 + ',' + value_xy2 + ', color=(' + color + '), thickness=' + value_thickness + ')\n';
  1678. }
  1679. return code;
  1680. };
  1681. Blockly.Blocks['ai_lcd_draw_image_on_canvas'] = {
  1682. init: function () {
  1683. this.appendDummyInput()
  1684. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_image.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1685. this.appendDummyInput()
  1686. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1687. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1688. .appendField(Blockly.Msg.image_process_draw_image_title);
  1689. this.appendValueInput("image_path")
  1690. .setCheck(null)
  1691. .appendField(Blockly.Msg.image_process_draw_sensor_image_path);
  1692. // this.appendValueInput("alpha")
  1693. // .setCheck(null)
  1694. // .appendField('图片透明度(范围0~1)');
  1695. this.appendValueInput("scale_y")
  1696. .setCheck(null)
  1697. .appendField(Blockly.Msg.OLCD_COORDINATE);
  1698. this.setInputsInline(false);
  1699. this.setPreviousStatement(true, null);
  1700. this.setNextStatement(true, null);
  1701. this.setColour("#5bb2d6");
  1702. this.setTooltip(Blockly.Msg.ai_lcd_draw_image_on_canvas_TOOLTIP);
  1703. this.setHelpUrl("");
  1704. }
  1705. };
  1706. Blockly.Python['ai_lcd_draw_image_on_canvas'] = function (block) {
  1707. // TODO: Assemble Python into code variable.
  1708. // nav_up = image.Image("/sd/preset/images/arrow_up_filled.jpg")
  1709. // splash.draw_image(nav_up, 5, 5)
  1710. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1711. var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC);
  1712. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  1713. var value_scale_x = Blockly.Python.valueToCode(block, 'scale_x', Blockly.Python.ORDER_ATOMIC);
  1714. var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC);
  1715. // let alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC)
  1716. // TODO: Assemble Python into code variable.
  1717. var code = '' +
  1718. variable_name + '.draw_image(' + value_image_path + ',' + value_scale_y + ',alpha=1)\n' +
  1719. '\n';
  1720. return code;
  1721. };
  1722. Blockly.Blocks['ai_lcd_draw_image_sensor_on_canvas'] = {
  1723. init: function () {
  1724. this.appendDummyInput()
  1725. .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_image.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  1726. this.appendDummyInput()
  1727. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1728. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1729. .appendField(Blockly.Msg.image_process_draw_sensor_image_title);
  1730. this.appendValueInput("image_path")
  1731. .setCheck(null)
  1732. .appendField(Blockly.Msg.image_process_draw_sensor_image_path);
  1733. this.appendValueInput("xy")
  1734. .setCheck(null)
  1735. .appendField(Blockly.Msg.image_process_text_start_coord);
  1736. // this.appendValueInput("scale_x")
  1737. // .setCheck(null)
  1738. // .appendField(Blockly.Msg.image_process_draw_image_scale_x);
  1739. // this.appendValueInput("scale_y")
  1740. // .setCheck(null)
  1741. // .appendField(Blockly.Msg.image_process_draw_image_scale_y);
  1742. this.setInputsInline(false);
  1743. this.setPreviousStatement(true, null);
  1744. this.setNextStatement(true, null);
  1745. this.setColour("#5bb2d6");
  1746. this.setTooltip(Blockly.Msg.ai_lcd_draw_sensor_image_on_canvas_TOOLTIP);
  1747. this.setHelpUrl("");
  1748. }
  1749. };
  1750. Blockly.Python['ai_lcd_draw_image_sensor_on_canvas'] = function (block) {
  1751. // TODO: Assemble Python into code variable.
  1752. // nav_up = image.Image("/sd/preset/images/arrow_up_filled.jpg")
  1753. // splash.draw_image(nav_up, 5, 5)
  1754. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1755. var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC);
  1756. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  1757. // var value_scale_x = Blockly.Python.valueToCode(block, 'scale_x', Blockly.Python.ORDER_ATOMIC);
  1758. // var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC);
  1759. // TODO: Assemble Python into code variable.
  1760. var code = '' +
  1761. variable_name + ' = ' + value_image_path + '\n' +
  1762. '_photo_x, _photo_y = ' + value_xy +
  1763. '\n';
  1764. return code;
  1765. };
  1766. Blockly.Blocks['ai_lcd_qrcode'] = {
  1767. init: function () {
  1768. this.appendDummyInput()
  1769. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_qrcode_.png", 35, 35, { alt: "*", flipRtl: "FALSE" }));
  1770. this.appendDummyInput()
  1771. .appendField(Blockly.Msg.image_process_text_on_canvas)
  1772. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1773. .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_qrcode);
  1774. this.appendValueInput("POSA")
  1775. .setCheck("String")
  1776. .appendField(Blockly.Msg.image_process_text_start_coord);
  1777. this.appendValueInput("CONTENT")
  1778. .setCheck("String")
  1779. .appendField(Blockly.Msg.image_process_text_content);
  1780. this.appendValueInput("Scale")
  1781. .setCheck("Number")
  1782. .appendField(Blockly.Msg.image_process_draw_qr_code_size);
  1783. this.setInputsInline(false);
  1784. this.setPreviousStatement(true);
  1785. this.setNextStatement(true);
  1786. this.setColour("#5bb2d6");
  1787. this.setTooltip(Blockly.Msg.ai_lcd_qrcode_TOOLTIP);
  1788. this.setHelpUrl('');
  1789. }
  1790. };
  1791. Blockly.Python.ai_lcd_qrcode = function (block) {
  1792. // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
  1793. var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
  1794. var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
  1795. var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
  1796. // var wraps = block.getFieldValue('wraps');
  1797. Blockly.Python.definitions_.import_qrcode = "from uQR import QRCode";
  1798. Blockly.Python.definitions_['import_define_x_ai_lcd_qrcode'] = '' +
  1799. 'def draw_qr_code(canvas, x, y, text, scale):\n' +
  1800. ' qr = QRCode()\n' +
  1801. ' qr.add_data(str(text))\n' +
  1802. ' matrix = qr.get_matrix()\n' +
  1803. ' for row in matrix:\n' +
  1804. ' for col in row:\n' +
  1805. ' value = (not col) * 255\n' +
  1806. ' a = canvas.draw_rectangle(x, y, scale, scale, color=(value, value, value), thickness=1, fill=True)\n' +
  1807. ' x += scale\n' +
  1808. ' y += scale\n' +
  1809. ' x = 0\n' +
  1810. ' del qr, matrix\n' +
  1811. '\n';
  1812. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1813. var _code = "draw_qr_code(" + variable_name + ", " + xy + ", " + content + ", scale=" + size + ")\n";
  1814. return _code;
  1815. };
  1816. Blockly.Blocks['v831_img_save'] = {
  1817. init: function () {
  1818. this.appendValueInput("save_path")
  1819. .setCheck(null)
  1820. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1821. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1822. .appendField(Blockly.Msg.image_process_img_save);
  1823. // this.appendDummyInput()
  1824. // .appendField(Blockly.Msg.image_process_img_save_quality)
  1825. // .appendField(new Blockly.FieldNumber(90, 0, 100), "compression")
  1826. // .appendField("%");
  1827. this.setInputsInline(false);
  1828. this.setPreviousStatement(true, null);
  1829. this.setNextStatement(true, null);
  1830. this.setColour("#f0983e");
  1831. this.setTooltip(Blockly.Msg.ai_img_save_TOOLTIP);
  1832. this.setHelpUrl("");
  1833. }
  1834. };
  1835. Blockly.Python['v831_img_save'] = function (block) {
  1836. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1837. var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  1838. var compression_rate = block.getFieldValue('compression');
  1839. // TODO: Assemble Python into code variable.
  1840. // , quality=' + compression_rate + ' 图片压缩
  1841. var code = variable_name + '.save(' + save_path_location + ')\n';
  1842. return code;
  1843. };
  1844. Blockly.Blocks['v831_img_open'] = {
  1845. init: function () {
  1846. this.appendValueInput("save_path")
  1847. .setCheck(null)
  1848. .appendField(Blockly.Msg.read_img_path_to)
  1849. // .appendField(Blockly.Msg.image_process_img_save);
  1850. // this.appendDummyInput()
  1851. // .appendField(Blockly.Msg.image_process_img_save_quality)
  1852. // .appendField(new Blockly.FieldNumber(90, 0, 100), "compression")
  1853. // .appendField("%");
  1854. // this.setInputsInline(false);
  1855. this.setOutput(true, null);
  1856. this.setColour("#f0983e");
  1857. this.setTooltip(Blockly.Msg.read_img_path_to);
  1858. this.setHelpUrl("");
  1859. }
  1860. };
  1861. Blockly.Python['v831_img_open'] = function (block) {
  1862. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1863. var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  1864. // var compression_rate = block.getFieldValue('compression');
  1865. // TODO: Assemble Python into code variable.
  1866. // , quality=' + compression_rate + ' 图片压缩
  1867. var code = 'image.open(' + save_path_location + ')';
  1868. return [code, Blockly.Python.ORDER_NONE];
  1869. };
  1870. // 翻转
  1871. Blockly.Blocks['v831_lcd_invert'] = {
  1872. init: function () {
  1873. this.appendDummyInput()
  1874. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1875. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1876. .appendField(Blockly.Msg.image_process_text_image_canvas)
  1877. .appendField(Blockly.Msg.image_process_pixtovec_text_first)
  1878. .appendField(new Blockly.FieldDropdown([
  1879. [Blockly.Msg.display_draw_vertical, "0"],
  1880. [Blockly.Msg.display_draw_horizontal, "1"]
  1881. ]), "invert")
  1882. .appendField(Blockly.Msg.MAIXDUINO_DISPLAY_ORIENTATION_ROTATE);
  1883. this.setOutput(true, null);
  1884. this.setColour("#f0983e");
  1885. // this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
  1886. this.setHelpUrl("");
  1887. }
  1888. };
  1889. Blockly.Python['v831_lcd_invert'] = function (block) {
  1890. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1891. let invert = block.getFieldValue('invert');
  1892. // TODO: Assemble Python into code variable.
  1893. var code = `${variable_name}.flip(${invert})`
  1894. // TODO: Change ORDER_NONE to the correct strength.
  1895. return [code, Blockly.Python.ORDER_NONE];
  1896. };
  1897. // 旋转
  1898. Blockly.Blocks['v831_lcd_rotating'] = {
  1899. init: function () {
  1900. this.appendValueInput('spend')
  1901. .setCheck(null)
  1902. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1903. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1904. .appendField(Blockly.Msg.image_process_text_image_canvas)
  1905. .appendField(Blockly.Msg.image_process_pixtovec_text_first)
  1906. .appendField(new Blockly.FieldDropdown([
  1907. [Blockly.Msg.x_motor_cw_ai, "0"],
  1908. [Blockly.Msg.x_motor_acw_ai, "1"]
  1909. ]), "rotating")
  1910. .appendField(Blockly.Msg.x_motor_set_motor_turns_ai);
  1911. this.appendDummyInput().appendField(Blockly.Msg.robot_dog_ag);
  1912. this.setOutput(true, null);
  1913. this.setColour("#f0983e");
  1914. this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
  1915. this.setHelpUrl("");
  1916. }
  1917. };
  1918. Blockly.Python['v831_lcd_rotating'] = function (block) {
  1919. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1920. let rotating = block.getFieldValue('rotating');
  1921. let spend = (rotating != 0 ? '+' : '-') + Blockly.Python.valueToCode(block, 'spend', Blockly.Python.ORDER_ATOMIC);
  1922. // TODO: Assemble Python into code variable.
  1923. // Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg,rotationAngle):
  1924. // from maix import image
  1925. // imgRotationAim = image.new(size = (320, 240),color=(0,0,0))
  1926. // imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
  1927. // return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1)
  1928. // `
  1929. // console.log(rotating,spend)
  1930. var code = `${variable_name}.rotate(${spend}, adjust=1)`
  1931. // variable_name+'.rotate('+ spend +', adjust=1)';
  1932. // TODO: Change ORDER_NONE to the correct strength.
  1933. return [code, Blockly.Python.ORDER_NONE];
  1934. };
  1935. Blockly.Blocks['ai_lcd_invert_color'] = {
  1936. init: function () {
  1937. this.appendDummyInput()
  1938. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1939. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1940. .appendField(Blockly.Msg.image_process_color_invert);
  1941. this.setOutput(true, null);
  1942. this.setColour("#f0983e");
  1943. this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP);
  1944. this.setHelpUrl("");
  1945. }
  1946. };
  1947. Blockly.Python['ai_lcd_invert_color'] = function (block) {
  1948. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1949. // TODO: Assemble Python into code variable.
  1950. var code = variable_name + '.invert()';
  1951. // TODO: Change ORDER_NONE to the correct strength.
  1952. return [code, Blockly.Python.ORDER_NONE];
  1953. };
  1954. Blockly.Blocks['v831_lcd_resizecanvas'] = {
  1955. init: function () {
  1956. this.appendDummyInput()
  1957. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1958. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1959. .appendField(Blockly.Msg.image_process_text_image_canvas)
  1960. .appendField(Blockly.Msg.image_process_resize_to);
  1961. this.appendValueInput("wh")
  1962. .setCheck(null);
  1963. this.setInputsInline(true);
  1964. this.setOutput(true, null);
  1965. this.setColour("#f0983e");
  1966. this.setTooltip(Blockly.Msg.ai_lcd_resizecanvas_TOOLTIP);
  1967. this.setHelpUrl("");
  1968. }
  1969. };
  1970. Blockly.Python['v831_lcd_resizecanvas'] = function (block) {
  1971. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  1972. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  1973. // TODO: Assemble Python into code variable.
  1974. // Blockly.Python.definitions_['lcd_invert_init'] = `CANVASINVERT = image.new(size = (240, 320), color = (0,0,0), mode = 'RGB')
  1975. // `
  1976. // var code = `CANVASINVERT.draw_image(${variable_name}.crop(0, 0, 240, 320).resize(${wh}),0,0,alpha=1)`
  1977. // variable_name + '.resize(' + wh + ')';
  1978. // TODO: Change ORDER_NONE to the correct strength.
  1979. var code = `${variable_name}.resize(${wh}, padding = 0)`
  1980. return [code, Blockly.Python.ORDER_NONE];
  1981. };
  1982. Blockly.Blocks['ai_lcd_color_scheme'] = {
  1983. init: function () {
  1984. this.appendDummyInput()
  1985. .appendField(Blockly.Msg.image_process_text_let_canvas)
  1986. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  1987. .appendField(Blockly.Msg.image_process_color_scheme_convert)
  1988. .appendField(new Blockly.FieldDropdown([
  1989. [Blockly.Msg.image_process_color_scheme_bw, "to_grayscale(1)"],
  1990. [Blockly.Msg.image_process_color_scheme_rgb, "to_rgb565(1)"]
  1991. ]), "color_scheme");
  1992. this.setOutput(true, null);
  1993. this.setColour("#f0983e");
  1994. var thisBlock = this;
  1995. this.setTooltip(function () {
  1996. var mode = thisBlock.getFieldValue('color_scheme');
  1997. var TOOLTIPS = {
  1998. 'to_grayscale(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_bw),
  1999. 'to_rgb565(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_rgb)
  2000. };
  2001. return TOOLTIPS[mode];
  2002. });
  2003. this.setHelpUrl("");
  2004. }
  2005. };
  2006. Blockly.Python['ai_lcd_color_scheme'] = function (block) {
  2007. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2008. var dropdown_vari = block.getFieldValue('color_scheme');
  2009. // TODO: Assemble Python into code variable.
  2010. var code = variable_name + '.' + dropdown_vari;
  2011. // TODO: Change ORDER_NONE to the correct strength.
  2012. return [code, Blockly.Python.ORDER_NONE];
  2013. };
  2014. Blockly.Blocks['ai_lcd_ai_pix'] = {
  2015. init: function () {
  2016. this.appendDummyInput()
  2017. .appendField(Blockly.Msg.image_process_text_let_canvas)
  2018. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2019. .appendField(Blockly.Msg.image_process_pixtovec_text_first)
  2020. .appendField(new Blockly.FieldDropdown([
  2021. [Blockly.Msg.image_process_pixtovec_v2p, ".ai_to_pix()"],
  2022. [Blockly.Msg.image_process_pixtovec_p2v, ".pix_to_ai()"]
  2023. ]), "ai_pix_type")
  2024. .appendField(Blockly.Msg.image_process_pixtovec_conversion);
  2025. this.setInputsInline(false);
  2026. this.setPreviousStatement(true, null);
  2027. this.setNextStatement(true, null);
  2028. this.setColour("#f0983e");
  2029. this.setTooltip("");
  2030. this.setHelpUrl("");
  2031. }
  2032. };
  2033. Blockly.Python['ai_lcd_ai_pix'] = function (block) {
  2034. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2035. var dropdown_vari = block.getFieldValue('ai_pix_type');
  2036. // TODO: Assemble Python into code variable.
  2037. var code = 'a = ' + variable_name + dropdown_vari + '\n';
  2038. // TODO: Change ORDER_NONE to the correct strength.
  2039. return code;
  2040. };
  2041. Blockly.Blocks['v831_lcd_img_cut'] = {
  2042. init: function () {
  2043. this.appendDummyInput()
  2044. .appendField(Blockly.Msg.image_process_text_let_canvas)
  2045. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2046. .appendField(Blockly.Msg.image_process_text_image_canvas)
  2047. .appendField(Blockly.Msg.image_process_imgcut_cutting);
  2048. this.appendValueInput("xy")
  2049. .setCheck(null)
  2050. .appendField(Blockly.Msg.image_process_imgcut_start_coord);
  2051. this.appendValueInput("wh")
  2052. .setCheck(null)
  2053. .appendField(Blockly.Msg.image_process_imgcut_size);
  2054. this.setInputsInline(false);
  2055. this.setOutput(true, null);
  2056. this.setColour("#f0983e");
  2057. this.setTooltip(Blockly.Msg.ai_lcd_img_cut_TOOLTIP);
  2058. this.setHelpUrl("");
  2059. }
  2060. };
  2061. Blockly.Python['v831_lcd_img_cut'] = function (block) {
  2062. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2063. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2064. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2065. // TODO: Assemble Python into code variable.
  2066. // TODO: Change ORDER_NONE to the correct strength.
  2067. var code = `${variable_name}.crop(${xy},${wh})`;
  2068. return [code, Blockly.Python.ORDER_NONE];
  2069. };
  2070. Blockly.Blocks['ai_vision_get_statistics'] = {
  2071. init: function () {
  2072. this.appendDummyInput()
  2073. .appendField(Blockly.Msg.image_process_get_statistics_to_canvas)
  2074. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2075. .appendField(Blockly.Msg.image_process_get_statistics_get_analysis);
  2076. this.appendValueInput("xy")
  2077. .setCheck(null)
  2078. .appendField(Blockly.Msg.image_process_get_statistics_start_coord);
  2079. this.appendValueInput("wh")
  2080. .setCheck(null)
  2081. .appendField(Blockly.Msg.image_process_get_statistics_size);
  2082. this.appendValueInput("bins")
  2083. .setCheck(null)
  2084. .appendField(Blockly.Msg.image_process_get_statistics_boxes);
  2085. this.setInputsInline(false);
  2086. this.setOutput(true, null);
  2087. this.setColour("#f0983e");
  2088. this.setTooltip(Blockly.Msg.ai_vision_get_statistics_TOOLTIP);
  2089. this.setHelpUrl("");
  2090. }
  2091. };
  2092. Blockly.Python['ai_vision_get_statistics'] = function (block) {
  2093. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2094. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2095. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2096. var bins = Blockly.Python.valueToCode(block, 'bins', Blockly.Python.ORDER_ATOMIC);
  2097. // TODO: Assemble Python into code variable.
  2098. var code = variable_name + '.get_statistics(bins=' + bins + ',roi=(' + xy + ',' + wh + '))';
  2099. // TODO: Change ORDER_NONE to the correct strength.
  2100. return [code, Blockly.Python.ORDER_NONE];
  2101. };
  2102. Blockly.Blocks['ai_vision_get_histogram'] = {
  2103. init: function () {
  2104. this.appendDummyInput()
  2105. .appendField(Blockly.Msg.ai_vision_get_histogram_get)
  2106. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2107. .appendField(Blockly.Msg.ai_vision_get_histogram_compute);
  2108. this.appendDummyInput()
  2109. .appendField(Blockly.Msg.ai_vision_get_histogram_region);
  2110. this.appendValueInput("xy")
  2111. .setCheck(null)
  2112. .appendField(Blockly.Msg.ai_vision_get_histogram_region_xy);
  2113. this.appendValueInput("wh")
  2114. .setCheck(null)
  2115. .appendField(Blockly.Msg.ai_vision_get_histogram_region_wh);
  2116. this.setInputsInline(false);
  2117. this.setOutput(true, null);
  2118. this.setColour("#f0983e");
  2119. this.setTooltip(Blockly.Msg.ai_vision_get_histogram_TOOLTIP);
  2120. this.setHelpUrl("");
  2121. }
  2122. };
  2123. Blockly.Python['ai_vision_get_histogram'] = function (block) {
  2124. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2125. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2126. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2127. // TODO: Assemble Python into code variable.
  2128. var code = variable_name + '.get_histogram(roi=(' + value_xy + ',' + value_wh + '))';
  2129. // TODO: Change ORDER_NONE to the correct strength.
  2130. return [code, Blockly.Python.ORDER_NONE];
  2131. };
  2132. Blockly.Blocks['ai_vision_get_histogram_percentile'] = {
  2133. init: function () {
  2134. this.appendDummyInput()
  2135. .appendField(Blockly.Msg.ai_vision_get_histogram_details_1)
  2136. .appendField(new Blockly.FieldVariable("hist"), "varitem")
  2137. .appendField(Blockly.Msg.ai_vision_get_histogram_details_get);
  2138. this.appendValueInput("perc")
  2139. .setCheck(null);
  2140. this.setInputsInline(true);
  2141. this.setOutput(true, null);
  2142. this.setColour("#f0983e");
  2143. this.setTooltip(Blockly.Msg.ai_vision_get_histogram_percentile_TOOLTIP);
  2144. this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
  2145. }
  2146. };
  2147. Blockly.Python['ai_vision_get_histogram_percentile'] = function (block) {
  2148. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2149. var value_perc = Blockly.Python.valueToCode(block, 'perc', Blockly.Python.ORDER_ATOMIC);
  2150. // TODO: Assemble Python into code variable.
  2151. var code = variable_name + '.get_percentile(' + value_perc + ')';
  2152. // TODO: Change ORDER_NONE to the correct strength.
  2153. return [code, Blockly.Python.ORDER_NONE];
  2154. };
  2155. Blockly.Blocks['ai_vision_get_histogram_percentile_detail'] = {
  2156. init: function () {
  2157. this.appendDummyInput()
  2158. .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_1)
  2159. .appendField(new Blockly.FieldVariable("percentile"), "varitem");
  2160. this.appendDummyInput()
  2161. .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_2)
  2162. .appendField(new Blockly.FieldDropdown([
  2163. [Blockly.Msg.ai_vision_get_histogram_percentile_3, "value()"],
  2164. [Blockly.Msg.ai_vision_get_histogram_percentile_4, "l_value()"],
  2165. [Blockly.Msg.ai_vision_get_histogram_percentile_5, "a_value()"],
  2166. [Blockly.Msg.ai_vision_get_histogram_percentile_6, "b_value()"]
  2167. ]), "option");
  2168. this.setInputsInline(false);
  2169. this.setOutput(true, null);
  2170. this.setColour("#f0983e");
  2171. var thisBlock = this;
  2172. this.setTooltip(function () {
  2173. var mode = thisBlock.getFieldValue('option');
  2174. var TOOLTIPS = {
  2175. 'value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_3),
  2176. 'l_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_4),
  2177. 'a_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_5),
  2178. 'b_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_6)
  2179. };
  2180. return TOOLTIPS[mode];
  2181. });
  2182. this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
  2183. }
  2184. };
  2185. Blockly.Python['ai_vision_get_histogram_percentile_detail'] = function (block) {
  2186. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2187. var dropdown_option = block.getFieldValue('option');
  2188. var code = variable_name + '.' + dropdown_option;
  2189. // TODO: Change ORDER_NONE to the correct strength.
  2190. return [code, Blockly.Python.ORDER_NONE];
  2191. };
  2192. Blockly.Blocks['ai_vision_lab_rgb_conversion'] = {
  2193. init: function () {
  2194. this.appendDummyInput()
  2195. .appendField(Blockly.Msg.image_process_lab_rgb_conversion_exec)
  2196. .appendField(new Blockly.FieldDropdown([
  2197. [Blockly.Msg.image_process_lab_rgb_conversion_torgb, "lab_to_rgb"],
  2198. [Blockly.Msg.image_process_lab_rgb_conversion_tolab, "rgb_to_lab"]
  2199. ]), "rgblab");
  2200. this.appendValueInput("color_tuple")
  2201. .setCheck(null)
  2202. .appendField(Blockly.Msg.image_process_lab_rgb_conversion_tuple);
  2203. this.setOutput(true, null);
  2204. this.setColour("#f0983e");
  2205. var thisBlock = this;
  2206. this.setTooltip(function () {
  2207. var mode = thisBlock.getFieldValue('rgblab');
  2208. var TOOLTIPS = {
  2209. 'lab_to_rgb': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_torgb),
  2210. 'rgb_to_lab': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_tolab)
  2211. };
  2212. return TOOLTIPS[mode];
  2213. });
  2214. this.setHelpUrl("");
  2215. }
  2216. };
  2217. Blockly.Python['ai_vision_lab_rgb_conversion'] = function (block) {
  2218. var type = block.getFieldValue('rgblab');
  2219. var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
  2220. // TODO: Assemble Python into code variable.
  2221. var code = 'image.' + type + '(' + tuple + ')';
  2222. // TODO: Change ORDER_NONE to the correct strength.
  2223. return [code, Blockly.Python.ORDER_NONE];
  2224. };
  2225. Blockly.Blocks['ai_vision_rgb_grayscale_conversion'] = {
  2226. init: function () {
  2227. this.appendDummyInput()
  2228. .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_exec)
  2229. .appendField(new Blockly.FieldDropdown([
  2230. [Blockly.Msg.image_process_rgb_grayscale_conversion_torgb, "grayscale_to_rgb"],
  2231. [Blockly.Msg.image_process_rgb_grayscale_conversion_togray, "rgb_to_grayscale"]
  2232. ]), "rgb_g");
  2233. this.appendValueInput("color_tuple")
  2234. .setCheck(null)
  2235. .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_set);
  2236. this.setOutput(true, null);
  2237. this.setColour("#f0983e");
  2238. var thisBlock = this;
  2239. this.setTooltip(function () {
  2240. var mode = thisBlock.getFieldValue('rgb_g');
  2241. var TOOLTIPS = {
  2242. 'grayscale_to_rgb': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_torgb),
  2243. 'rgb_to_grayscale': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_togray)
  2244. };
  2245. return TOOLTIPS[mode];
  2246. });
  2247. this.setHelpUrl("");
  2248. }
  2249. };
  2250. Blockly.Python['ai_vision_rgb_grayscale_conversion'] = function (block) {
  2251. var type = block.getFieldValue('rgb_g');
  2252. var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
  2253. Blockly.Python.addVariable('rgb_tuple', "rgb_tuple = None", true);
  2254. // TODO: Assemble Python into code variable.
  2255. var code = 'image.' + type + '(' + tuple + ')';
  2256. // TODO: Change ORDER_NONE to the correct strength.
  2257. return [code, Blockly.Python.ORDER_NONE];
  2258. };
  2259. /*
  2260. _ ___ ____
  2261. / \ |_ _| / ___|__ _ _ __ ___ ___ _ __ __ _
  2262. / _ \ | | | | / _` | '_ ` _ \ / _ \ '__/ _` |
  2263. / ___ \ | | | |__| (_| | | | | | | __/ | | (_| |
  2264. /_/ \_\___| \____\__,_|_| |_| |_|\___|_| \__,_|
  2265. */
  2266. Blockly.Blocks.ai_camera_wh = {
  2267. init: function () {
  2268. var _input = this.appendDummyInput();
  2269. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  2270. this.setColour("#60c1bb");
  2271. this.setOutput(!0, "Boolean");
  2272. _input.appendField(Blockly.Msg.W);
  2273. this.appendValueInput("A").setCheck("Number");
  2274. _input = this.appendDummyInput();
  2275. _input.appendField(Blockly.Msg.H)
  2276. this.appendValueInput("B").setCheck("Number");
  2277. this.setInputsInline(!0);
  2278. }
  2279. };
  2280. Blockly.Python.ai_camera_wh = function (block) {
  2281. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2282. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  2283. var code = "" + _x + ", " + _y + "";
  2284. return [code, Blockly.Python.ORDER_ATOMIC];
  2285. };
  2286. Blockly.Blocks['ai_camera_init'] = {
  2287. init: function () {
  2288. this.appendDummyInput()
  2289. .appendField(new Blockly.FieldImage("blockly/media/camera_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  2290. this.appendDummyInput()
  2291. .appendField(Blockly.Msg.ai_camera_camera_init);
  2292. // this.appendDummyInput()
  2293. // .appendField(Blockly.Msg.ai_camera_camera_set_size)
  2294. // .appendField(new Blockly.FieldDropdown([
  2295. // ["QVGA (320*240)", "QVGA"],
  2296. // ["QQVGA (160*120)", "QQVGA"]
  2297. // ]), "DEGREE");
  2298. // this.appendDummyInput()
  2299. // .appendField(Blockly.Msg.ai_camera_camera_color_mode)
  2300. // .appendField(new Blockly.FieldDropdown([
  2301. // [Blockly.Msg.ai_camera_camera_color_mode_rgb, "RGB565"],
  2302. // [Blockly.Msg.ai_camera_camera_color_mode_bw, "GRAYSCALE"]
  2303. // ]), "DEGREE1");
  2304. this.setPreviousStatement(true, null);
  2305. this.setNextStatement(true, null);
  2306. this.setColour("#60c1bb");
  2307. this.setTooltip(Blockly.Msg.ai_camera_init_TOOLTIP);
  2308. this.setHelpUrl('');
  2309. }
  2310. };
  2311. Blockly.Python.ai_camera_init = function (block) {
  2312. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`
  2313. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`
  2314. Blockly.Python.definitions_['v831_import_os'] = `import os`
  2315. Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True
  2316. def CAMERATYPE():
  2317. global cameraSize
  2318. try:
  2319. if os.path.exists("/etc/cameraSize.cfg"):
  2320. cameraSize = True
  2321. else:
  2322. cameraSize = False
  2323. except:
  2324. cameraSize = False
  2325. image.load_freetype("/root/preset/fonts/simhei.ttf")
  2326. CAMERATYPE()
  2327. `
  2328. Blockly.Python.addVariable("SETVFLIP", "SETVFLIP = False", true)
  2329. Blockly.Python.addVariable("SETHMIRROT", "SETHMIRROT = False", true)
  2330. var _code = ``;
  2331. return _code;
  2332. }
  2333. Blockly.Blocks['ai_camera_windows'] = {
  2334. init: function () {
  2335. this.appendDummyInput()
  2336. .appendField(Blockly.Msg.ai_camera_windowing_resize);
  2337. this.appendDummyInput()
  2338. .appendField(Blockly.Msg.ai_camera_windowing_w)
  2339. .appendField(new Blockly.FieldNumber(240), "window_w")
  2340. .appendField(Blockly.Msg.ai_camera_windowing_h)
  2341. .appendField(new Blockly.FieldNumber(320), "window_h")
  2342. // .appendField(Blockly.Msg.ai_camera_windowing_unit);
  2343. this.setPreviousStatement(true, null);
  2344. this.setNextStatement(true, null);
  2345. this.setColour("#60c1bb");
  2346. this.setTooltip(Blockly.Msg.ai_camera_windows_TOOLTIP);
  2347. this.setHelpUrl("");
  2348. }
  2349. };
  2350. Blockly.Python['ai_camera_windows'] = function (block) {
  2351. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2352. var w = block.getFieldValue('window_w');
  2353. var h = block.getFieldValue('window_h');
  2354. // var code = 'sensor.set_windowing((' + w + ',' + h + '))\n';
  2355. var code = 'camera.camera.config(size=(' + w + ',' + h + '))\n';
  2356. return code;
  2357. };
  2358. Blockly.Blocks['ai_camera_fit_to_screen_size'] = {
  2359. init: function () {
  2360. this.appendDummyInput()
  2361. .appendField(Blockly.Msg.ai_camera_camera_fit_set);
  2362. this.appendDummyInput()
  2363. .appendField(new Blockly.FieldVariable("camera"), "varitem");
  2364. this.appendDummyInput()
  2365. .appendField(Blockly.Msg.ai_camera_camera_fit_to)
  2366. .appendField(new Blockly.FieldDropdown([
  2367. [Blockly.Msg.ai_camera_camera_fit_2, "224"]
  2368. ]), "size");
  2369. this.setInputsInline(true);
  2370. this.setPreviousStatement(true, null);
  2371. this.setNextStatement(true, null);
  2372. this.setColour("#60c1bb");
  2373. this.setTooltip(Blockly.Msg.ai_camera_fit_to_screen_size_TOOLTIP);
  2374. this.setHelpUrl("");
  2375. }
  2376. };
  2377. Blockly.Python['ai_camera_fit_to_screen_size'] = function (block) {
  2378. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2379. var dropdown_size = block.getFieldValue('size');
  2380. // TODO: Assemble Python into code variable.
  2381. if (dropdown_size == "224") {
  2382. var code = variable_name + ' = ' + variable_name + '.resize(224,224)\n';
  2383. }
  2384. return code;
  2385. };
  2386. Blockly.Blocks['ai_camera_snapshot'] = {
  2387. init: function () {
  2388. this.appendDummyInput()
  2389. .appendField(Blockly.Msg.ai_camera_snapshot);
  2390. this.setOutput(true, null);
  2391. this.setColour("#60c1bb");
  2392. this.setTooltip(Blockly.Msg.ai_camera_snapshot_TOOLTIP);
  2393. this.setHelpUrl('');
  2394. }
  2395. };
  2396. Blockly.Python.ai_camera_snapshot = function (block) {
  2397. Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg):
  2398. global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
  2399. imageRotationBuffer = inputImg.crop(0, 0, 240, 320)
  2400. if ScreenOrientation:
  2401. imgRotationAim = image.new(size = (240, 320))
  2402. rotationAngle = 180
  2403. else:
  2404. imgRotationAim = image.new(size = (320, 240))
  2405. rotationAngle = 90
  2406. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  2407. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  2408. if SETVFLIP and not SETHMIRROT:
  2409. GETROTATIONs = GETROTATION.flip(0)
  2410. if SETHMIRROT and not SETVFLIP:
  2411. GETROTATIONs = GETROTATION.flip(1)
  2412. if SETVFLIP and SETHMIRROT:
  2413. GETROTATION1 = GETROTATION.flip(0)
  2414. GETROTATION = GETROTATION1.flip(1)
  2415. return GETROTATION
  2416. `
  2417. Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg):
  2418. global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation
  2419. imageRotationBuffer = inputImg.crop(0, 0, 320, 240)
  2420. if ScreenOrientation:
  2421. imgRotationAim = image.new(size = (240, 320))
  2422. rotationAngle = 90
  2423. GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1)
  2424. else:
  2425. imgRotationAim = image.new(size = (320, 240))
  2426. GETROTATION = imageRotationBuffer
  2427. GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1)
  2428. if SETVFLIP and not SETHMIRROT:
  2429. GETROTATIONs = GETROTATION.flip(0)
  2430. elif SETHMIRROT and not SETVFLIP:
  2431. GETROTATIONs = GETROTATION.flip(1)
  2432. elif SETVFLIP and SETHMIRROT:
  2433. GETROTATION1 = GETROTATION.flip(0)
  2434. GETROTATION = GETROTATION1.flip(1)
  2435. return GETROTATION
  2436. `
  2437. Blockly.Python.definitions_['lcd_invert_rotate_camera'] = `def getLcdRotation(cameraCapture):
  2438. global cameraSize
  2439. if cameraSize:
  2440. return lcdRotationNew(cameraCapture)
  2441. else:
  2442. return lcdRotation(cameraCapture)
  2443. `
  2444. // #从摄像头中获取一张图像
  2445. var _code = `getLcdRotation(camera.capture())`;
  2446. return [_code, Blockly.Python.ORDER_ATOMIC];
  2447. }
  2448. // 图传
  2449. Blockly.Blocks['v831_camera_graph_transmission'] = {
  2450. init: function () {
  2451. this.appendDummyInput()
  2452. .appendField(Blockly.Msg.v831_transmission_setup_show);
  2453. this.appendDummyInput()
  2454. .appendField(Blockly.Msg.v831_transmission_init_setup_source)
  2455. .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem");
  2456. this.setPreviousStatement(true, null);
  2457. this.setNextStatement(true, null);
  2458. this.setColour("#60c1bb");
  2459. this.setTooltip(Blockly.Msg.v831_transmission_setup_show);
  2460. this.setHelpUrl('');
  2461. }
  2462. };
  2463. Blockly.Python.v831_camera_graph_transmission = function (block) {
  2464. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2465. Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
  2466. Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
  2467. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  2468. Blockly.Python.definitions_['v831_import_time'] = `import time`
  2469. // #从摄像头中获取一张图像
  2470. var _code = `jpg = utils.rgb2jpg(${variable_name}.convert("RGB").tobytes(), ${variable_name}.width, ${variable_name}.height)
  2471. img_base64 = base64.b64encode(jpg)
  2472. img_base64_str = "data:image/jpg;base64," + str(img_base64)[2:-1]
  2473. time.sleep(0.1)
  2474. try:
  2475. print(img_base64_str)
  2476. pass
  2477. except Exception as e:
  2478. print(str(e))
  2479. pass
  2480. `;
  2481. return _code
  2482. }
  2483. Blockly.Blocks['v831_camera_internet_transmission'] = {
  2484. init: function () {
  2485. this.appendDummyInput()
  2486. .appendField(Blockly.Msg.v831_internet_transmission_setup_show);
  2487. this.appendDummyInput()
  2488. .appendField(Blockly.Msg.v831_transmission_init_setup_source)
  2489. .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem");
  2490. this.setPreviousStatement(true, null);
  2491. this.setNextStatement(true, null);
  2492. this.setColour("#60c1bb");
  2493. this.setTooltip(Blockly.Msg.v831_transmission_setup_show);
  2494. this.setHelpUrl('');
  2495. }
  2496. };
  2497. Blockly.Python.v831_camera_internet_transmission = function (block) {
  2498. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2499. Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg`
  2500. Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils`
  2501. Blockly.Python.definitions_['v831_import_queue'] = `queue = mjpg.Queue(maxsize=8)
  2502. mjpg.MjpgServerThread("0.0.0.0", 18811, mjpg.BytesImageHandlerFactory(q=queue)).start()`
  2503. // #从摄像头中获取一张图像
  2504. var _code = `jpg = utils.rgb2jpg(${variable_name}.convert("RGB").tobytes(), 320, 240)
  2505. queue.put(mjpg.BytesImage(jpg))
  2506. `;
  2507. return _code
  2508. }
  2509. Blockly.Blocks['ai_camera_lens_corr'] = {
  2510. init: function () {
  2511. this.appendValueInput("lens_corr")
  2512. .setCheck(null)
  2513. .appendField(Blockly.Msg.ai_camera_set_lens_corr);
  2514. this.setInputsInline(true);
  2515. this.setOutput(true, null);
  2516. this.setColour("#60c1bb");
  2517. this.setTooltip(Blockly.Msg.ai_camera_lens_corr_TOOLTIP);
  2518. this.setHelpUrl("");
  2519. }
  2520. };
  2521. Blockly.Python['ai_camera_lens_corr'] = function (block) {
  2522. var value_lens_corr = Blockly.Python.valueToCode(block, 'lens_corr', Blockly.Python.ORDER_ATOMIC);
  2523. // TODO: Assemble Python into code variable.
  2524. var code = value_lens_corr + '.lens_corr(strength = 1.8, zoom = 1.0)';
  2525. // TODO: Change ORDER_NONE to the correct strength.
  2526. return [code, Blockly.Python.ORDER_NONE];
  2527. };
  2528. Blockly.Blocks['ai_camera_image_property_change'] = {
  2529. init: function () {
  2530. this.appendDummyInput()
  2531. .appendField(Blockly.Msg.ai_camera_bcs_set_text_2)
  2532. .appendField(new Blockly.FieldDropdown([
  2533. [Blockly.Msg.ai_camera_bcs_vflip, "set_vflip"],
  2534. [Blockly.Msg.ai_camera_bcs_hmirror, "set_hmirror"],
  2535. // [Blockly.Msg.ai_camera_bcs_wb, "set_auto_whitebal"],
  2536. // [Blockly.Msg.ai_camera_bcs_g, "set_auto_gain"],
  2537. // [Blockly.Msg.ai_camera_bcs_e, "set_auto_exposure"]
  2538. ]), "image_property")
  2539. .appendField(Blockly.Msg.ai_camera_bcs_as_2)
  2540. .appendField(new Blockly.FieldDropdown([
  2541. [Blockly.Msg.ai_camera_enable + Blockly.Msg.ai_camera_bcs_status, "True"],
  2542. [Blockly.Msg.ai_camera_disable + Blockly.Msg.ai_camera_bcs_status, "False"]
  2543. ]), "DEGREE");
  2544. this.setPreviousStatement(true, null);
  2545. this.setNextStatement(true, null);
  2546. this.setColour("#60c1bb");
  2547. var thisBlock = this;
  2548. this.setTooltip(function () {
  2549. var mode = thisBlock.getFieldValue('image_property');
  2550. var TOOLTIPS = {
  2551. 'set_vflip': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_vflip),
  2552. 'set_hmirror': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_hmirror),
  2553. 'set_auto_whitebal': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_wb),
  2554. 'set_auto_gain': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_g),
  2555. 'set_auto_exposure': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_e)
  2556. };
  2557. return TOOLTIPS[mode];
  2558. });
  2559. this.setHelpUrl('');
  2560. }
  2561. };
  2562. Blockly.Python.ai_camera_image_property_change = function (block) {
  2563. var degee = block.getFieldValue('DEGREE');
  2564. var dropdown_image_property = block.getFieldValue('image_property');
  2565. var _code = ``;
  2566. if (dropdown_image_property == "set_vflip") {
  2567. _code = `SETVFLIP = ${degee}
  2568. `
  2569. } else if (dropdown_image_property == "set_hmirror") {
  2570. _code = `SETHMIRROT = ${degee}
  2571. `
  2572. }
  2573. return _code;
  2574. }
  2575. Blockly.Blocks['ai_camera_vflip'] = {
  2576. init: function () {
  2577. this.appendDummyInput()
  2578. .appendField(Blockly.Msg.ai_camera_set_vflip)
  2579. .appendField(new Blockly.FieldDropdown([
  2580. [Blockly.Msg.ai_camera_enable, "True"],
  2581. [Blockly.Msg.ai_camera_disable, "False"]
  2582. ]), "DEGREE")
  2583. this.setPreviousStatement(true, null);
  2584. this.setNextStatement(true, null);
  2585. this.setColour("#60c1bb");
  2586. this.setTooltip('');
  2587. this.setHelpUrl('');
  2588. }
  2589. };
  2590. Blockly.Python.ai_camera_vflip = function (block) {
  2591. var degee = block.getFieldValue('DEGREE');
  2592. var _code = "sensor.set_vflip(" + degee + ")\n";
  2593. return _code;
  2594. }
  2595. Blockly.Blocks['ai_camera_hmirror'] = {
  2596. init: function () {
  2597. this.appendDummyInput()
  2598. .appendField(Blockly.Msg.ai_camera_set_hmirror)
  2599. .appendField(new Blockly.FieldDropdown([
  2600. [Blockly.Msg.ai_camera_enable, "True"],
  2601. [Blockly.Msg.ai_camera_disable, "False"]
  2602. ]), "DEGREE")
  2603. this.setPreviousStatement(true, null);
  2604. this.setNextStatement(true, null);
  2605. this.setColour("#60c1bb");
  2606. this.setTooltip('');
  2607. this.setHelpUrl('');
  2608. }
  2609. };
  2610. Blockly.Python.ai_camera_hmirror = function (block) {
  2611. var degee = block.getFieldValue('DEGREE');
  2612. var _code = "sensor.set_hmirror(" + degee + ")\n"
  2613. return _code;
  2614. }
  2615. Blockly.Blocks['ai_camera_auto_whitebal'] = {
  2616. init: function () {
  2617. this.appendDummyInput()
  2618. .appendField(Blockly.Msg.ai_camera_set_auto_whitebal)
  2619. .appendField(new Blockly.FieldDropdown([
  2620. [Blockly.Msg.ai_camera_enable, "True"],
  2621. [Blockly.Msg.ai_camera_disable, "False"]
  2622. ]), "DEGREE")
  2623. this.setPreviousStatement(true, null);
  2624. this.setNextStatement(true, null);
  2625. this.setColour("#60c1bb");
  2626. this.setTooltip('');
  2627. this.setHelpUrl('');
  2628. }
  2629. };
  2630. Blockly.Python.ai_camera_auto_whitebal = function (block) {
  2631. var degee = block.getFieldValue('DEGREE');
  2632. var _code = "sensor.set_auto_whitebal(" + degee + ")\n"
  2633. return _code;
  2634. }
  2635. Blockly.Blocks['ai_camera_auto_gain'] = {
  2636. init: function () {
  2637. this.appendDummyInput()
  2638. .appendField(Blockly.Msg.ai_camera_set_auto_gain)
  2639. .appendField(new Blockly.FieldDropdown([
  2640. [Blockly.Msg.ai_camera_enable, "True"],
  2641. [Blockly.Msg.ai_camera_disable, "False"]
  2642. ]), "DEGREE")
  2643. this.setPreviousStatement(true, null);
  2644. this.setNextStatement(true, null);
  2645. this.setColour("#60c1bb");
  2646. this.setTooltip('');
  2647. this.setHelpUrl('');
  2648. }
  2649. };
  2650. Blockly.Python.ai_camera_auto_gain = function (block) {
  2651. var degee = block.getFieldValue('DEGREE');
  2652. var _code = "sensor.set_auto_gain(" + degee + ")\n"
  2653. return _code;
  2654. }
  2655. Blockly.Blocks['ai_camera_auto_exposure'] = {
  2656. init: function () {
  2657. this.appendDummyInput()
  2658. .appendField(Blockly.Msg.ai_camera_set_auto_exposure)
  2659. .appendField(new Blockly.FieldDropdown([
  2660. [Blockly.Msg.ai_camera_enable, "True"],
  2661. [Blockly.Msg.ai_camera_disable, "False"]
  2662. ]), "DEGREE")
  2663. this.setPreviousStatement(true, null);
  2664. this.setNextStatement(true, null);
  2665. this.setColour("#60c1bb");
  2666. this.setTooltip('');
  2667. this.setHelpUrl('');
  2668. }
  2669. };
  2670. Blockly.Python.ai_camera_auto_exposure = function (block) {
  2671. var degee = block.getFieldValue('DEGREE');
  2672. var _code = "sensor.set_auto_exposure(" + degee + ")\n"
  2673. return _code;
  2674. }
  2675. Blockly.Blocks['ai_camera_bcs_operation'] = {
  2676. init: function () {
  2677. this.appendDummyInput()
  2678. .appendField(Blockly.Msg.ai_camera_bcs_set_text)
  2679. .appendField(new Blockly.FieldDropdown([
  2680. [Blockly.Msg.ai_camera_bcs_contrast, "contrast"],
  2681. [Blockly.Msg.ai_camera_bcs_brightness, "brightness"],
  2682. [Blockly.Msg.ai_camera_bcs_saturation, "saturation"]
  2683. ]), "image_property")
  2684. .appendField(Blockly.Msg.ai_camera_bcs_as);
  2685. this.appendValueInput("A").setCheck("Number");
  2686. this.appendDummyInput()
  2687. .appendField(Blockly.Msg.ai_camera_set_range);
  2688. this.setPreviousStatement(true, null);
  2689. this.setNextStatement(true, null);
  2690. this.setInputsInline(!0);
  2691. this.setColour("#60c1bb");
  2692. var thisBlock = this;
  2693. this.setTooltip(function () {
  2694. var mode = thisBlock.getFieldValue('image_property');
  2695. var TOOLTIPS = {
  2696. 'contrast': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_contrast),
  2697. 'brightness': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_brightness),
  2698. 'saturation': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_saturation)
  2699. };
  2700. return TOOLTIPS[mode];
  2701. });
  2702. this.setHelpUrl('');
  2703. }
  2704. };
  2705. Blockly.Python.ai_camera_bcs_operation = function (block) {
  2706. var dropdown_image_property = block.getFieldValue('image_property');
  2707. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2708. var _code = "sensor.set_" + dropdown_image_property + "(" + _x + ")\n"
  2709. return _code;
  2710. }
  2711. Blockly.Blocks['ai_camera_contrast'] = {
  2712. init: function () {
  2713. this.appendDummyInput()
  2714. .appendField(Blockly.Msg.ai_camera_set_contrast_to_value);
  2715. this.appendValueInput("A").setCheck("Number");
  2716. this.appendDummyInput()
  2717. .appendField(Blockly.Msg.ai_camera_set_range);
  2718. this.setPreviousStatement(true, null);
  2719. this.setNextStatement(true, null);
  2720. this.setInputsInline(!0);
  2721. this.setColour("#60c1bb");
  2722. this.setTooltip('');
  2723. this.setHelpUrl('');
  2724. }
  2725. };
  2726. Blockly.Python.ai_camera_contrast = function (block) {
  2727. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2728. var _code = "sensor.set_contrast(" + _x + ")\n"
  2729. return _code;
  2730. }
  2731. Blockly.Blocks['ai_camera_brightness'] = {
  2732. init: function () {
  2733. this.appendDummyInput()
  2734. .appendField(Blockly.Msg.ai_camera_set_brightness_to_value);
  2735. this.appendValueInput("A").setCheck("Number");
  2736. this.appendDummyInput()
  2737. .appendField(Blockly.Msg.ai_camera_set_range);
  2738. this.setPreviousStatement(true, null);
  2739. this.setNextStatement(true, null);
  2740. this.setInputsInline(!0);
  2741. this.setColour("#60c1bb");
  2742. this.setTooltip('');
  2743. this.setHelpUrl('');
  2744. }
  2745. };
  2746. Blockly.Python.ai_camera_brightness = function (block) {
  2747. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2748. var _code = "sensor.set_brightness(" + _x + ")\n"
  2749. return _code;
  2750. }
  2751. Blockly.Blocks['ai_camera_saturation'] = {
  2752. init: function () {
  2753. this.appendDummyInput()
  2754. .appendField(Blockly.Msg.ai_camera_set_saturation_value);
  2755. this.appendValueInput("A").setCheck("Number");
  2756. this.appendDummyInput()
  2757. .appendField(Blockly.Msg.ai_camera_set_range);
  2758. this.setPreviousStatement(true, null);
  2759. this.setNextStatement(true, null);
  2760. this.setInputsInline(!0);
  2761. this.setColour("#60c1bb");
  2762. this.setTooltip('');
  2763. this.setHelpUrl('');
  2764. }
  2765. };
  2766. Blockly.Python.ai_camera_saturation = function (block) {
  2767. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2768. var _code = "sensor.set_saturation(" + _x + ")\n"
  2769. return _code;
  2770. }
  2771. /*
  2772. _ ___ __ ___ _
  2773. / \ |_ _| \ \ / (_)___(_) ___ _ __
  2774. / _ \ | | \ \ / /| / __| |/ _ \| '_ \
  2775. / ___ \ | | \ V / | \__ \ | (_) | | | |
  2776. /_/ \_\___| \_/ |_|___/_|\___/|_| |_|
  2777. */
  2778. Blockly.Blocks.ai_lcd_XY_vision = {
  2779. init: function () {
  2780. var _input = this.appendDummyInput();
  2781. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  2782. this.setColour("#f0983e");
  2783. this.setOutput(!0, "Boolean");
  2784. _input.appendField(Blockly.Msg.X);
  2785. this.appendValueInput("A").setCheck("Number");
  2786. _input = this.appendDummyInput();
  2787. _input.appendField(Blockly.Msg.Y)
  2788. this.appendValueInput("B").setCheck("Number");
  2789. this.setInputsInline(!0);
  2790. }
  2791. };
  2792. Blockly.Python.ai_lcd_XY_vision = function (block) {
  2793. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2794. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  2795. var code = "" + _x + ", " + _y + "";
  2796. return [code, Blockly.Python.ORDER_ATOMIC];
  2797. };
  2798. Blockly.Blocks.ai_lcd_WH_vision = {
  2799. init: function () {
  2800. var _input = this.appendDummyInput();
  2801. this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
  2802. this.setColour("#f0983e");
  2803. this.setOutput(!0, "Boolean");
  2804. _input.appendField(Blockly.Msg.W);
  2805. this.appendValueInput("A").setCheck("Number");
  2806. _input = this.appendDummyInput();
  2807. _input.appendField(Blockly.Msg.H)
  2808. this.appendValueInput("B").setCheck("Number");
  2809. this.setInputsInline(!0);
  2810. }
  2811. };
  2812. Blockly.Python.ai_lcd_WH_vision = function (block) {
  2813. var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
  2814. var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
  2815. var code = "" + _x + ", " + _y + "";
  2816. return [code, Blockly.Python.ORDER_ATOMIC];
  2817. };
  2818. Blockly.Blocks['ai_canvas_area_tuple'] = {
  2819. init: function () {
  2820. this.appendDummyInput()
  2821. .appendField(Blockly.Msg.ai_vision_canvas_area_tuple);
  2822. this.appendValueInput("xy")
  2823. .setCheck(null)
  2824. .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_xy);
  2825. this.appendValueInput("wh")
  2826. .setCheck(null)
  2827. .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_wh);
  2828. this.setInputsInline(false);
  2829. this.setOutput(true, null);
  2830. this.setColour("#f0983e");
  2831. this.setTooltip(Blockly.Msg.ai_vision_canvas_area_tuple_TOOLTIP);
  2832. this.setHelpUrl("");
  2833. }
  2834. };
  2835. Blockly.Python['ai_canvas_area_tuple'] = function (block) {
  2836. var value_coordinate = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2837. var value_size = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2838. // TODO: Assemble Python into code variable.
  2839. var code = value_coordinate + ',' + value_size;
  2840. // TODO: Change ORDER_NONE to the correct strength.
  2841. return [code, Blockly.Python.ORDER_NONE];
  2842. };
  2843. Blockly.Blocks['ai_lane_tracking_run'] = {
  2844. init: function () {
  2845. this.appendDummyInput()
  2846. .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2847. this.appendDummyInput()
  2848. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2849. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2850. .appendField(Blockly.Msg.ai_vision_lane_tracking_run);
  2851. this.appendValueInput("rgb_value")
  2852. .setCheck(null)
  2853. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2854. this.setPreviousStatement(true, null);
  2855. this.setNextStatement(true, null);
  2856. this.setColour("#f0983e");
  2857. this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2858. this.setHelpUrl("");
  2859. }
  2860. };
  2861. Blockly.Python['ai_lane_tracking_run'] = function (block) {
  2862. var value_color = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC)
  2863. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2864. var code = '' +
  2865. 'line = ' + variable_name + '.find_line()\n' +
  2866. '' + variable_name + '.draw_line(line["rect"][0], line["rect"][1], line["rect"][2],line["rect"][3], color=' + value_color + ', thickness=1)\n' +
  2867. '' + variable_name + '.draw_line(line["rect"][2], line["rect"][3], line["rect"][4],line["rect"][5], color=' + value_color + ', thickness=1)\n' +
  2868. '' + variable_name + '.draw_line(line["rect"][4], line["rect"][5], line["rect"][6],line["rect"][7], color=' + value_color + ', thickness=1)\n' +
  2869. '' + variable_name + '.draw_line(line["rect"][6], line["rect"][7], line["rect"][0],line["rect"][1], color=' + value_color + ', thickness=1)\n' +
  2870. '' + variable_name + '.draw_circle(line["cx"], line["cy"], 4,color=' + value_color + ', thickness=1)\n';
  2871. return code;
  2872. };
  2873. Blockly.Blocks['ai_vision_find_lines'] = {
  2874. init: function () {
  2875. this.appendDummyInput()
  2876. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_line.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2877. this.appendDummyInput()
  2878. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2879. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2880. .appendField(Blockly.Msg.ai_vision_find_line);
  2881. this.appendValueInput("xy")
  2882. .setCheck(null)
  2883. .appendField(Blockly.Msg.ai_vision_find_line_start_coord);
  2884. this.appendValueInput("wh")
  2885. .setCheck(null)
  2886. .appendField(Blockly.Msg.ai_vision_find_line_size);
  2887. /*this.appendValueInput("threshold")
  2888. .setCheck(null)
  2889. .appendField(Blockly.Msg.ai_vision_find_line_hoffman_threshold);
  2890. this.appendValueInput("theta_margin")
  2891. .setCheck(null)
  2892. .appendField(Blockly.Msg.ai_vision_find_line_merge_theta);
  2893. this.appendValueInput("rho_margin")
  2894. .setCheck(null)
  2895. .appendField(Blockly.Msg.ai_vision_find_line_merge_rho);*/
  2896. this.setOutput(true, null);
  2897. this.setColour("#f0983e");
  2898. this.setTooltip(Blockly.Msg.ai_vision_find_lines_TOOLTIP);
  2899. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  2900. }
  2901. };
  2902. Blockly.Python['ai_vision_find_lines'] = function (block) {
  2903. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2904. //var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
  2905. //var theta_margin = Blockly.Python.valueToCode(block, 'theta_margin', Blockly.Python.ORDER_ATOMIC);
  2906. //var rho_margin = Blockly.Python.valueToCode(block, 'rho_margin', Blockly.Python.ORDER_ATOMIC);
  2907. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2908. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2909. // TODO: Assemble Python into code variable.
  2910. var code = variable_name + '.find_lines(roi=(' + xy + ',' + wh + '), threshold = 1000, theta_margin = 25, rho_margin = 25)';
  2911. // TODO: Change ORDER_NONE to the correct strength.
  2912. return [code, Blockly.Python.ORDER_NONE];
  2913. };
  2914. Blockly.Blocks['ai_vision_find_rects'] = {
  2915. init: function () {
  2916. this.appendDummyInput()
  2917. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_rect.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2918. this.appendDummyInput()
  2919. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2920. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2921. .appendField(Blockly.Msg.ai_vision_find_rect);
  2922. this.appendValueInput("xy")
  2923. .setCheck(null)
  2924. .appendField(Blockly.Msg.ai_vision_find_rect_start_coord);
  2925. this.appendValueInput("wh")
  2926. .setCheck(null)
  2927. .appendField(Blockly.Msg.ai_vision_find_rect_region_size);
  2928. /*this.appendValueInput("threshold")
  2929. .setCheck(null)
  2930. .appendField(Blockly.Msg.ai_vision_find_rect_bounding_threshold);*/
  2931. this.setOutput(true, null);
  2932. this.setColour("#f0983e");
  2933. this.setTooltip(Blockly.Msg.ai_vision_find_rects_TOOLTIP);
  2934. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  2935. }
  2936. };
  2937. Blockly.Python['ai_vision_find_rects'] = function (block) {
  2938. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2939. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2940. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2941. // var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
  2942. // TODO: Assemble Python into code variable.
  2943. var code = variable_name + '.find_rects(roi=(' + xy + ',' + wh + '), threshold = 10000)';
  2944. // TODO: Change ORDER_NONE to the correct strength.
  2945. return [code, Blockly.Python.ORDER_NONE];
  2946. };
  2947. Blockly.Blocks['ai_vision_find_lines'] = {
  2948. init: function () {
  2949. this.appendDummyInput()
  2950. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2951. this.appendDummyInput()
  2952. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2953. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2954. .appendField(Blockly.Msg.ai_vision_find_blobs_color_region);
  2955. this.appendValueInput("color")
  2956. .setCheck(null)
  2957. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2958. this.appendValueInput("xy")
  2959. .setCheck(null)
  2960. .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
  2961. this.appendValueInput("wh")
  2962. .setCheck(null)
  2963. .appendField(Blockly.Msg.ai_vision_find_blobs_size);
  2964. this.setInputsInline(false);
  2965. this.setOutput(true, null);
  2966. this.setColour("#f0983e");
  2967. this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP);
  2968. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  2969. }
  2970. };
  2971. Blockly.Python['ai_vision_find_lines'] = function (block) {
  2972. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  2973. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  2974. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  2975. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  2976. Blockly.Python.definitions_[''] = `
  2977. def v831_find_blob_fun(lane_trackingimg,region1,COLOR):
  2978. IMGBLOB = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
  2979. blobsCANVAS = IMGBLOB.find_blobs(COLOR, merge=True)
  2980. return blobsCANVAS
  2981. `;
  2982. var code = `v831_find_blob_fun(${variable_name},(${value_xy},${value_wh}),${value_color})
  2983. `;
  2984. return [code, Blockly.Python.ORDER_NONE];
  2985. };
  2986. Blockly.Blocks['ai_vision_find_blobs'] = {
  2987. init: function () {
  2988. this.appendDummyInput()
  2989. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  2990. this.appendDummyInput()
  2991. .appendField(Blockly.Msg.ai_vision_from_canvas)
  2992. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  2993. .appendField(Blockly.Msg.ai_vision_find_lines_color_region);
  2994. this.appendValueInput("color")
  2995. .setCheck(null)
  2996. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  2997. this.appendValueInput("xy")
  2998. .setCheck(null)
  2999. .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
  3000. this.appendValueInput("wh")
  3001. .setCheck(null)
  3002. .appendField(Blockly.Msg.ai_vision_find_blobs_size);
  3003. this.setInputsInline(false);
  3004. this.setOutput(true, null);
  3005. this.setColour("#f0983e");
  3006. this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP);
  3007. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3008. }
  3009. };
  3010. Blockly.Python['ai_vision_find_blobs'] = function (block) {
  3011. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3012. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  3013. var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  3014. var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  3015. Blockly.Python.addVariable('lane_trackingline', "lane_trackingline1 = {}", true);
  3016. Blockly.Python.definitions_['ai_vision_find_blobs_color'] = `_ld_color_detection_threshold = ${value_color}
  3017. def v831_lane_tracking_setup_one(lane_trackingimg,region1):
  3018. global lane_trackingline
  3019. lane_trackingcanvas = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
  3020. lane_trackingline = lane_trackingcanvas.find_line()
  3021. lane_trackingcanvas.draw_circle(lane_trackingline["cx"], lane_trackingline["cy"], 2,color=(0,255,0), thickness=1)
  3022. lane_trackingimg.draw_image(lane_trackingcanvas,region1[0],region1[1])
  3023. lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1)
  3024. lane_trackingline["cx"] = lane_trackingline["cx"] + region1[0]
  3025. lane_trackingline["cy"] = lane_trackingline["cy"] + region1[1]
  3026. return lane_trackingline
  3027. `;
  3028. var code = `v831_lane_tracking_setup_one(${variable_name},(${value_xy},${value_wh}))
  3029. `;
  3030. return [code, Blockly.Python.ORDER_NONE];
  3031. };
  3032. //
  3033. Blockly.Blocks['ai_vision_find_blobs_result'] = {
  3034. init: function () {
  3035. this.appendDummyInput()
  3036. .appendField(Blockly.Msg.OLCD_LINE_START)
  3037. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3038. .appendField(Blockly.Msg.ai_vision_find_lines_color_region_result)
  3039. .appendField(new Blockly.FieldDropdown([
  3040. [Blockly.Msg.ai_models_object_model_x_center, "cx"],
  3041. [Blockly.Msg.ai_models_object_model_y_center, "cy"]
  3042. ]), "value");
  3043. // this.setInputsInline(false);
  3044. this.setOutput(true, null);
  3045. this.setColour("#f0983e");
  3046. this.setTooltip(Blockly.Msg.ai_vision_find_lines_color_region_result);
  3047. }
  3048. };
  3049. Blockly.Python['ai_vision_find_blobs_result'] = function (block) {
  3050. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3051. var property = block.getFieldValue('value');
  3052. var code = `${variable_name}.get("${property}")`;
  3053. return [code, Blockly.Python.ORDER_ATOMIC];
  3054. };
  3055. Blockly.Blocks['ai_lane_tracking_setup'] = {
  3056. init: function () {
  3057. this.appendDummyInput()
  3058. .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  3059. this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas)
  3060. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3061. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup);
  3062. this.appendValueInput("color")
  3063. .setCheck(null)
  3064. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold);
  3065. this.appendValueInput("lsize")
  3066. .setCheck(null)
  3067. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_l);
  3068. this.appendValueInput("rsize")
  3069. .setCheck(null)
  3070. .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_r);
  3071. // this.appendValueInput("axis")
  3072. // .setCheck(null)
  3073. // .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_axis);
  3074. this.setPreviousStatement(true, null);
  3075. this.setNextStatement(true, null);
  3076. this.setColour("#f0983e");
  3077. this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_TOOLTIP);
  3078. this.setHelpUrl("");
  3079. }
  3080. };
  3081. Blockly.Python['ai_lane_tracking_setup'] = function (block) {
  3082. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3083. var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);
  3084. var value_lsize = Blockly.Python.valueToCode(block, 'lsize', Blockly.Python.ORDER_ATOMIC);
  3085. var value_rsize = Blockly.Python.valueToCode(block, 'rsize', Blockly.Python.ORDER_ATOMIC);
  3086. var value_axis = Blockly.Python.valueToCode(block, 'axis', Blockly.Python.ORDER_ATOMIC);
  3087. console.log(value_lsize[0])
  3088. Blockly.Python.addVariable('lane_trackingline1', "lane_trackingline1 = {}", true);
  3089. Blockly.Python.addVariable('lane_trackingline2', "lane_trackingline2 = {}", true);
  3090. Blockly.Python.definitions_['ai_lane_tracking_setup'] = `_ld_color_detection_threshold = ${value_color}
  3091. def v831_lane_tracking_setup(lane_trackingimg,region1,region2):
  3092. global lane_trackingline1,lane_trackingline2
  3093. lane_trackingcanvas1 = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3])
  3094. lane_trackingcanvas2 = lane_trackingimg.crop(region2[0],region2[1],region2[2],region2[3])
  3095. lane_trackingline1 = lane_trackingcanvas1.find_line()
  3096. lane_trackingline2 = lane_trackingcanvas2.find_line()
  3097. lane_trackingcanvas1.draw_circle(lane_trackingline1["cx"], lane_trackingline1["cy"], 2,color=(0,255,0), thickness=1)
  3098. lane_trackingcanvas2.draw_circle(lane_trackingline2["cx"], lane_trackingline2["cy"], 2,color=(0,255,0), thickness=1)
  3099. lane_trackingimg.draw_image(lane_trackingcanvas1,region1[0],region1[1])
  3100. lane_trackingimg.draw_image(lane_trackingcanvas2,region2[0],region2[1])
  3101. lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1)
  3102. lane_trackingimg.draw_rectangle(region2[0],region2[1],region2[0]+region2[2],region2[1]+region2[3], color=(255,0,0), thickness=1)
  3103. `
  3104. let code = `v831_lane_tracking_setup(${variable_name},${value_lsize},${value_rsize})
  3105. `
  3106. return code
  3107. }
  3108. Blockly.Blocks['ai_lane_tracking_get'] = {
  3109. init: function () {
  3110. this.appendDummyInput()
  3111. .appendField(Blockly.Msg.ai_vision_lane_tracking_run_get)
  3112. .appendField(new Blockly.FieldDropdown([
  3113. [Blockly.Msg.ai_vision_lane_tracking_run_ld, "left_check"],
  3114. [Blockly.Msg.ai_vision_lane_tracking_run_lv, "left_value"],
  3115. [Blockly.Msg.ai_vision_lane_tracking_run_rd, "right_check"],
  3116. [Blockly.Msg.ai_vision_lane_tracking_run_rv, "right_value"]
  3117. ]), "return");
  3118. this.setOutput(true, null);
  3119. this.setColour("#f0983e");
  3120. this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_run_get_TOOLTIP);
  3121. this.setHelpUrl("");
  3122. }
  3123. };
  3124. Blockly.Python['ai_lane_tracking_get'] = function (block) {
  3125. var dropdown_return = block.getFieldValue('return');
  3126. // TODO: Assemble Python into code variable.
  3127. var code = '_ld_return["' + dropdown_return + '"]';
  3128. // TODO: Change ORDER_NONE to the correct strength.
  3129. return [code, Blockly.Python.ORDER_NONE];
  3130. };
  3131. Blockly.Blocks['ai_vision_color_analyze'] = {
  3132. init: function () {
  3133. this.appendDummyInput()
  3134. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_analyze_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  3135. this.appendDummyInput()
  3136. .appendField(Blockly.Msg.ai_vision_get_canvas)
  3137. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3138. .appendField(Blockly.Msg.ai_vision_color_analyze_get_result);
  3139. this.appendValueInput("xy")
  3140. .setCheck(null)
  3141. .appendField(Blockly.Msg.ai_vision_color_analyze_start_coord);
  3142. this.appendValueInput("wh")
  3143. .setCheck(null)
  3144. .appendField(Blockly.Msg.ai_vision_color_analyze_size);
  3145. this.setOutput(true, null);
  3146. this.setColour("#f0983e");
  3147. this.setTooltip(Blockly.Msg.ai_vision_color_analyze_TOOLTIP);
  3148. this.setHelpUrl("");
  3149. }
  3150. };
  3151. Blockly.Python['ai_vision_color_analyze'] = function (block) {
  3152. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3153. var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  3154. var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  3155. // TODO: Assemble Python into code variable.
  3156. var code = variable_name + '.get_blob_color((' + xy + ', ' + wh + '), 0, 0)';
  3157. // TODO: Change ORDER_NONE to the correct strength.
  3158. return [code, Blockly.Python.ORDER_NONE];
  3159. };
  3160. Blockly.Blocks['ai_vision_get_blobs'] = {
  3161. init: function () {
  3162. this.appendDummyInput()
  3163. .appendField(Blockly.Msg.ai_vision_from)
  3164. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3165. .appendField(Blockly.Msg.ai_vision_get_blobs_result)
  3166. .appendField(new Blockly.FieldDropdown([
  3167. [Blockly.Msg.ai_vision_detection_box_x, "x"],
  3168. [Blockly.Msg.ai_vision_detection_box_y, "y"],
  3169. [Blockly.Msg.ai_models_face_model_ws, "w"],
  3170. [Blockly.Msg.ai_models_face_model_hs, "h"],
  3171. // [Blockly.Msg.ai_vision_detection_box_pixels, "pixels()"],
  3172. [Blockly.Msg.ai_vision_detection_box_cx, "cx"],
  3173. [Blockly.Msg.ai_vision_detection_box_cy, "cy"]
  3174. // [Blockly.Msg.ai_vision_detection_box_degree, "rotation()"],
  3175. // [Blockly.Msg.ai_vision_detection_box_total, "count()"]
  3176. ]), "blob_type");
  3177. this.setInputsInline(false);
  3178. this.setOutput(true, null);
  3179. this.setColour("#f0983e");
  3180. this.setTooltip(Blockly.Msg.ai_vision_get_blobs_TOOLTIP);
  3181. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3182. }
  3183. };
  3184. Blockly.Python['ai_vision_get_blobs'] = function (block) {
  3185. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3186. var type = block.getFieldValue('blob_type');
  3187. // TODO: Assemble Python into code variable.
  3188. var code = `${variable_name}["${type}"]`;
  3189. if (type == "cx") {
  3190. code = `int((${variable_name}["w"] + ${variable_name}["x"] + ${variable_name}["x"])/2)`
  3191. } else if (type == "cy") {
  3192. code = `int((${variable_name}["h"] + ${variable_name}["y"] + ${variable_name}["y"])/2)`
  3193. }
  3194. // TODO: Change ORDER_NONE to the correct strength.
  3195. return [code, Blockly.Python.ORDER_NONE];
  3196. };
  3197. Blockly.Blocks['ai_vision_get_threshold_default'] = {
  3198. init: function () {
  3199. this.appendDummyInput()
  3200. .appendField(Blockly.Msg.ai_vision_detection_color_threshold_set)
  3201. .appendField(new Blockly.FieldDropdown([
  3202. [Blockly.Msg.ai_vision_detection_color_threshold_set_black, "black"],
  3203. [Blockly.Msg.ai_vision_detection_color_threshold_set_white, "white"],
  3204. [Blockly.Msg.ai_vision_detection_color_threshold_set_red, "red"],
  3205. [Blockly.Msg.ai_vision_detection_color_threshold_set_green, "green"],
  3206. [Blockly.Msg.ai_vision_detection_color_threshold_set_blue, "blue"],
  3207. [Blockly.Msg.ai_vision_detection_color_threshold_set_orange, "orange"]
  3208. ]), "color");
  3209. this.setOutput(true, null);
  3210. this.setColour("#f0983e");
  3211. var thisBlock = this;
  3212. this.setTooltip(function () {
  3213. var mode = thisBlock.getFieldValue('color');
  3214. var TOOLTIPS = {
  3215. 'black': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_black),
  3216. 'white': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_white),
  3217. 'red': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_red),
  3218. 'green': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_green),
  3219. 'blue': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_blue),
  3220. 'orange': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_orange)
  3221. };
  3222. return TOOLTIPS[mode];
  3223. });
  3224. this.setHelpUrl("");
  3225. }
  3226. };
  3227. Blockly.Python['ai_vision_get_threshold_default'] = function (block) {
  3228. var dropdown_color = block.getFieldValue('color');
  3229. // TODO: Assemble Python into code variable.
  3230. if (dropdown_color == "black") {
  3231. var code = '[(0,40)]';
  3232. } else if (dropdown_color == "white") {
  3233. var code = '[(64,100)]';
  3234. } else if (dropdown_color == "red") {
  3235. var code = '[(45, 65, 40, 80, 40, 60)]';
  3236. } else if (dropdown_color == "green") {
  3237. var code = '[(45, 65, -50, -30, 0, 40)]';
  3238. } else if (dropdown_color == "blue") {
  3239. var code = '[(45, 65, -20, 30, -60, -20)]';
  3240. } else if (dropdown_color == "orange") {
  3241. var code = '[(77, 55, 19, 61, 14, 108)]';
  3242. }
  3243. // TODO: Change ORDER_NONE to the correct strength.
  3244. return [code, Blockly.Python.ORDER_NONE];
  3245. };
  3246. Blockly.Blocks['ai_vision_find_qrcode'] = {
  3247. init: function () {
  3248. this.appendDummyInput()
  3249. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_qrcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3250. this.appendDummyInput()
  3251. .appendField(Blockly.Msg.ai_vision_get_canvas)
  3252. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3253. .appendField(Blockly.Msg.ai_vision_qrcode_detected_result);
  3254. this.setOutput(true, null);
  3255. this.setColour("#f0983e");
  3256. this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP);
  3257. this.setHelpUrl("");
  3258. }
  3259. };
  3260. Blockly.Python['ai_vision_find_qrcode'] = function (block) {
  3261. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3262. // TODO: Assemble Python into code variable.
  3263. var code = variable_name + '.find_qrcodes()';
  3264. // TODO: Change ORDER_NONE to the correct strength.
  3265. return [code, Blockly.Python.ORDER_NONE];
  3266. };
  3267. Blockly.Blocks['ai_vision_qrcode_get_info'] = {
  3268. init: function () {
  3269. this.appendDummyInput()
  3270. .appendField(Blockly.Msg.ai_vision_from)
  3271. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3272. .appendField(Blockly.Msg.ai_vision_qrcode_get_result)
  3273. .appendField(new Blockly.FieldDropdown([
  3274. [Blockly.Msg.ai_vision_pattern_detection_content, "payload"],
  3275. // [Blockly.Msg.ai_vision_pattern_detection_type, "data_type"],
  3276. [Blockly.Msg.ai_vision_pattern_detection_x, "x"],
  3277. [Blockly.Msg.ai_vision_pattern_detection_y, "y"],
  3278. [Blockly.Msg.ai_vision_pattern_detection_X_Destination, "w"],
  3279. [Blockly.Msg.ai_vision_pattern_detection_Y_Destination, "h"],
  3280. [Blockly.Msg.ai_vision_pattern_detection_w, "w1"],
  3281. [Blockly.Msg.ai_vision_pattern_detection_h, "h2"]
  3282. ]), "get_info");
  3283. this.setInputsInline(false);
  3284. this.setOutput(true, null);
  3285. this.setColour("#f0983e");
  3286. var thisBlock = this;
  3287. this.setTooltip(function () {
  3288. var mode = thisBlock.getFieldValue('get_info');
  3289. var TOOLTIPS = {
  3290. 'payload': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3291. 'data_type': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type),
  3292. 'x': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3293. 'y': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3294. 'w': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_X_Destination),
  3295. 'h': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_Y_Destination),
  3296. 'w1': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3297. 'h1': Blockly.Msg.ai_vision_qrcode_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3298. };
  3299. return TOOLTIPS[mode];
  3300. });
  3301. this.setHelpUrl("");
  3302. }
  3303. };
  3304. Blockly.Python['ai_vision_qrcode_get_info'] = function (block) {
  3305. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3306. var dropdown_name = block.getFieldValue('get_info');
  3307. // TODO: Assemble Python into code variable.
  3308. var code = `${variable_name}["${dropdown_name}"]`;
  3309. if (dropdown_name == "w") {
  3310. code = `${variable_name}["${dropdown_name}"] + ${variable_name}["x"]`
  3311. } else if (dropdown_name == "h") {
  3312. code = `${variable_name}["${dropdown_name}"] + ${variable_name}["y"]`
  3313. } else if (dropdown_name == "w1") {
  3314. code = `${variable_name}["w"]`
  3315. } else if (dropdown_name == "h2") {
  3316. code = `${variable_name}["h"]`
  3317. }
  3318. return [code, Blockly.Python.ORDER_NONE];
  3319. };
  3320. Blockly.Blocks['ai_vision_find_apriltag'] = {
  3321. init: function () {
  3322. this.appendDummyInput()
  3323. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_apriltag_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3324. this.appendDummyInput()
  3325. .appendField(Blockly.Msg.ai_vision_get_canvas)
  3326. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3327. .appendField(Blockly.Msg.ai_vision_apriltag_detected_result);
  3328. this.setOutput(true, null);
  3329. this.setColour("#f0983e");
  3330. this.setTooltip(Blockly.Msg.ai_vision_find_apriltag_TOOLTIP);
  3331. this.setHelpUrl("");
  3332. }
  3333. };
  3334. Blockly.Python['ai_vision_find_apriltag'] = function (block) {
  3335. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3336. // TODO: Assemble Python into code variable.
  3337. var code = variable_name + '.find_apriltags(families = 16,fx = (6/5.76)*320,fy = (6/3.24)*240,cx = 160,cy = 120)';
  3338. // TODO: Change ORDER_NONE to the correct strength.
  3339. return [code, Blockly.Python.ORDER_NONE];
  3340. };
  3341. Blockly.Blocks['ai_vision_apriltag_get_info'] = {
  3342. init: function () {
  3343. this.appendDummyInput()
  3344. .appendField(Blockly.Msg.ai_vision_from)
  3345. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3346. .appendField(Blockly.Msg.ai_vision_apriltag_get_result)
  3347. .appendField(new Blockly.FieldDropdown([
  3348. // [Blockly.Msg.ai_vision_pattern_detection_content, "payload"],
  3349. [Blockly.Msg.ai_vision_pattern_detection_type_id, "id"],
  3350. [Blockly.Msg.ai_vision_pattern_detection_type_family, "family"],
  3351. [Blockly.Msg.ai_vision_pattern_detection_x, "x"],
  3352. [Blockly.Msg.ai_vision_pattern_detection_y, "y"],
  3353. [Blockly.Msg.ai_vision_pattern_detection_w, "w"],
  3354. [Blockly.Msg.ai_vision_pattern_detection_h, "h"],
  3355. [Blockly.Msg.ai_vision_pattern_distance, "distance"]
  3356. ]), "get_info");
  3357. this.setInputsInline(false);
  3358. this.setOutput(true, null);
  3359. this.setColour("#f0983e");
  3360. var thisBlock = this;
  3361. this.setTooltip(function () {
  3362. var mode = thisBlock.getFieldValue('get_info');
  3363. var TOOLTIPS = {
  3364. 'payload': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3365. 'id': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type_id),
  3366. 'family': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type_family),
  3367. 'x': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3368. 'y': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3369. 'w': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3370. 'h': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3371. };
  3372. return TOOLTIPS[mode];
  3373. });
  3374. this.setHelpUrl("");
  3375. }
  3376. };
  3377. Blockly.Python['ai_vision_apriltag_get_info'] = function (block) {
  3378. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3379. var dropdown_name = block.getFieldValue('get_info');
  3380. // TODO: Assemble Python into code variable.
  3381. var code = `${variable_name}["${dropdown_name}"]`;
  3382. if (dropdown_name == "distance") {
  3383. code = `int((${variable_name}['x_translation']*${variable_name}['x_translation']+${variable_name}['y_translation']*${variable_name}['y_translation']+${variable_name}['z_translation']*${variable_name}['z_translation']**0.5)*3.0649-2)`
  3384. }
  3385. // TODO: Change ORDER_NONE to the correct strength.
  3386. return [code, Blockly.Python.ORDER_NONE];
  3387. };
  3388. Blockly.Blocks['ai_vision_find_datamatrices'] = {
  3389. init: function () {
  3390. this.appendDummyInput()
  3391. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_datamatrix_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3392. this.appendDummyInput()
  3393. .appendField(Blockly.Msg.ai_vision_get_canvas)
  3394. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3395. .appendField(Blockly.Msg.ai_vision_datamatrices_detected_result);
  3396. this.setOutput(true, null);
  3397. this.setColour("#f0983e");
  3398. this.setTooltip(Blockly.Msg.ai_vision_find_datamatrices_TOOLTIP);
  3399. this.setHelpUrl("");
  3400. }
  3401. };
  3402. Blockly.Python['ai_vision_find_datamatrices'] = function (block) {
  3403. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3404. // TODO: Assemble Python into code variable.
  3405. var code = variable_name + '.find_datamatrices()';
  3406. // TODO: Change ORDER_NONE to the correct strength.
  3407. return [code, Blockly.Python.ORDER_NONE];
  3408. };
  3409. Blockly.Blocks['ai_vision_datamatrices_get_info'] = {
  3410. init: function () {
  3411. this.appendDummyInput()
  3412. .appendField(Blockly.Msg.ai_vision_from)
  3413. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3414. .appendField(Blockly.Msg.ai_vision_data_matrices_get_result)
  3415. .appendField(new Blockly.FieldDropdown([
  3416. [Blockly.Msg.ai_vision_pattern_detection_content, "payload"],
  3417. [Blockly.Msg.ai_vision_pattern_detection_rows, "rows"],
  3418. [Blockly.Msg.ai_vision_pattern_detection_cols, "columns"],
  3419. [Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count, "capacity"],
  3420. [Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count, "padding"],
  3421. [Blockly.Msg.ai_vision_pattern_detection_x, "x"],
  3422. [Blockly.Msg.ai_vision_pattern_detection_y, "y"],
  3423. [Blockly.Msg.ai_vision_pattern_detection_w, "w"],
  3424. [Blockly.Msg.ai_vision_pattern_detection_h, "h"]
  3425. ]), "get_info");
  3426. this.setInputsInline(false);
  3427. this.setOutput(true, null);
  3428. this.setColour("#f0983e");
  3429. var thisBlock = this;
  3430. this.setTooltip(function () {
  3431. var mode = thisBlock.getFieldValue('get_info');
  3432. var TOOLTIPS = {
  3433. 'payload': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3434. 'rows': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_rows),
  3435. 'columns': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_cols),
  3436. 'capacity': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count),
  3437. 'padding': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count),
  3438. 'x': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3439. 'y': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3440. 'w': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3441. 'h': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3442. };
  3443. return TOOLTIPS[mode];
  3444. });
  3445. this.setHelpUrl("");
  3446. }
  3447. };
  3448. Blockly.Python['ai_vision_datamatrices_get_info'] = function (block) {
  3449. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3450. var dropdown_name = block.getFieldValue('get_info');
  3451. // TODO: Assemble Python into code variable.
  3452. var code = variable_name + '.' + dropdown_name + '()';
  3453. // TODO: Change ORDER_NONE to the correct strength.
  3454. return [code, Blockly.Python.ORDER_NONE];
  3455. };
  3456. Blockly.Blocks['ai_vision_find_barcodes'] = {
  3457. init: function () {
  3458. this.appendDummyInput()
  3459. .appendField(new Blockly.FieldImage("blockly/media/ai_vision_barcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3460. this.appendDummyInput()
  3461. .appendField(Blockly.Msg.ai_vision_get_canvas)
  3462. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  3463. .appendField(Blockly.Msg.ai_vision_barcode_detected_result);
  3464. this.setOutput(true, null);
  3465. this.setColour("#f0983e");
  3466. this.setTooltip(Blockly.Msg.ai_vision_find_barcodes_TOOLTIP);
  3467. this.setHelpUrl("");
  3468. }
  3469. };
  3470. Blockly.Python['ai_vision_find_barcodes'] = function (block) {
  3471. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3472. // TODO: Assemble Python into code variable.
  3473. var code = variable_name + '.find_barcodes()';
  3474. // TODO: Change ORDER_NONE to the correct strength.
  3475. return [code, Blockly.Python.ORDER_NONE];
  3476. };
  3477. Blockly.Blocks['ai_vision_barcodes_get_info'] = {
  3478. init: function () {
  3479. this.appendDummyInput()
  3480. .appendField(Blockly.Msg.ai_vision_from_canvas)
  3481. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3482. .appendField(Blockly.Msg.ai_vision_barcode_matrices_get_result)
  3483. .appendField(new Blockly.FieldDropdown([
  3484. [Blockly.Msg.ai_vision_pattern_detection_content, "payload"],
  3485. [Blockly.Msg.ai_vision_pattern_detection_type, "type"],
  3486. [Blockly.Msg.ai_vision_pattern_detection_x, "x"],
  3487. [Blockly.Msg.ai_vision_pattern_detection_y, "y"],
  3488. [Blockly.Msg.ai_vision_pattern_detection_w, "w"],
  3489. [Blockly.Msg.ai_vision_pattern_detection_h, "h"]
  3490. ]), "get_info");
  3491. this.setInputsInline(false);
  3492. this.setOutput(true, null);
  3493. this.setColour("#f0983e");
  3494. var thisBlock = this;
  3495. this.setTooltip(function () {
  3496. var mode = thisBlock.getFieldValue('get_info');
  3497. var TOOLTIPS = {
  3498. 'payload': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content),
  3499. 'type': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type),
  3500. 'x': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x),
  3501. 'y': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y),
  3502. 'w': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w),
  3503. 'h': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h)
  3504. };
  3505. return TOOLTIPS[mode];
  3506. });
  3507. this.setHelpUrl("");
  3508. }
  3509. };
  3510. Blockly.Python['ai_vision_barcodes_get_info'] = function (block) {
  3511. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3512. var dropdown_name = block.getFieldValue('get_info');
  3513. // TODO: Assemble Python into code variable.
  3514. var code = variable_name + '["' + dropdown_name + '"]';
  3515. if (dropdown_name == "x") {
  3516. code = `${variable_name}["corners"][0][0]`
  3517. } else if (dropdown_name == "y") {
  3518. code = `${variable_name}["corners"][0][1]`
  3519. } else if (dropdown_name == "w") {
  3520. code = `${variable_name}["corners"][2][0] - ${variable_name}["corners"][0][0]`
  3521. } else if (dropdown_name == "h") {
  3522. code = `${variable_name}["corners"][2][1] - ${variable_name}["corners"][0][1]`
  3523. } else {
  3524. code = `${variable_name}["${dropdown_name}"]`
  3525. }
  3526. // TODO: Change ORDER_NONE to the correct strength.
  3527. return [code, Blockly.Python.ORDER_NONE];
  3528. };
  3529. Blockly.Blocks['ai_vision_get_circles'] = {
  3530. init: function () {
  3531. this.appendDummyInput()
  3532. .appendField(Blockly.Msg.ai_vision_from)
  3533. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3534. .appendField(Blockly.Msg.ai_vision_find_circle_detected_result)
  3535. .appendField(new Blockly.FieldDropdown([
  3536. [Blockly.Msg.ai_vision_find_circle_detected_x, "x()"],
  3537. [Blockly.Msg.ai_vision_find_circle_detected_y, "y()"],
  3538. [Blockly.Msg.ai_vision_find_circle_detected_radius, "r()"]
  3539. ]), "blob_type");
  3540. this.setInputsInline(false);
  3541. this.setOutput(true, null);
  3542. this.setColour("#f0983e");
  3543. this.setTooltip(Blockly.Msg.ai_vision_get_circles_TOOLTIP);
  3544. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3545. }
  3546. };
  3547. Blockly.Python['ai_vision_get_circles'] = function (block) {
  3548. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3549. var type = block.getFieldValue('blob_type');
  3550. var code = variable_name + '.' + type;
  3551. return [code, Blockly.Python.ORDER_NONE];
  3552. };
  3553. Blockly.Blocks['ai_vision_get_rects'] = {
  3554. init: function () {
  3555. this.appendDummyInput()
  3556. .appendField(Blockly.Msg.ai_vision_from)
  3557. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3558. .appendField(Blockly.Msg.ai_vision_find_rect_detected_result)
  3559. .appendField(new Blockly.FieldDropdown([
  3560. [Blockly.Msg.ai_vision_find_rect_detected_x, "x()"],
  3561. [Blockly.Msg.ai_vision_find_rect_detected_y, "y()"],
  3562. [Blockly.Msg.ai_vision_find_rect_detected_w, "w()"],
  3563. [Blockly.Msg.ai_vision_find_rect_detected_h, "h()"],
  3564. [Blockly.Msg.ai_vision_find_rect_detected_tuple, "rect()"],
  3565. [Blockly.Msg.ai_vision_find_rect_detected_corners, "corners()"]
  3566. ]), "blob_type");
  3567. this.setInputsInline(false);
  3568. this.setOutput(true, null);
  3569. this.setColour("#f0983e");
  3570. this.setTooltip(Blockly.Msg.ai_vision_get_rects_TOOLTIP);
  3571. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3572. }
  3573. };
  3574. Blockly.Python['ai_vision_get_rects'] = function (block) {
  3575. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3576. var type = block.getFieldValue('blob_type');
  3577. // TODO: Assemble Python into code variable.
  3578. var code = variable_name + '.' + type;
  3579. // TODO: Change ORDER_NONE to the correct strength.
  3580. return [code, Blockly.Python.ORDER_NONE];
  3581. };
  3582. Blockly.Blocks['ai_vision_get_lines'] = {
  3583. init: function () {
  3584. this.appendDummyInput()
  3585. .appendField(Blockly.Msg.ai_vision_from)
  3586. .appendField(new Blockly.FieldVariable("i"), "varitem")
  3587. .appendField(Blockly.Msg.ai_vision_find_line_detected_result)
  3588. .appendField(new Blockly.FieldDropdown([
  3589. [Blockly.Msg.ai_vision_find_line_detected_start_x, "x1()"],
  3590. [Blockly.Msg.ai_vision_find_line_detected_start_y, "y1()"],
  3591. [Blockly.Msg.ai_vision_find_line_detected_end_x, "x2()"],
  3592. [Blockly.Msg.ai_vision_find_line_detected_end_y, "y2()"],
  3593. [Blockly.Msg.ai_vision_find_line_detected_length, "length()"],
  3594. [Blockly.Msg.ai_vision_find_line_detected_angle, "theta()"]
  3595. ]), "blob_type");
  3596. this.setInputsInline(false);
  3597. this.setOutput(true, null);
  3598. this.setColour("#f0983e");
  3599. this.setTooltip(Blockly.Msg.ai_vision_get_lines_TOOLTIP);
  3600. this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  3601. }
  3602. };
  3603. Blockly.Python['ai_vision_get_lines'] = function (block) {
  3604. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  3605. var type = block.getFieldValue('blob_type');
  3606. // TODO: Assemble Python into code variable.
  3607. var code = variable_name + '.' + type;
  3608. // TODO: Change ORDER_NONE to the correct strength.
  3609. return [code, Blockly.Python.ORDER_NONE];
  3610. };
  3611. /*
  3612. _ ___ __ __ _ _
  3613. / \ |_ _| | \/ (_) ___ _ __ ___ _ __ | |__ ___ _ __ ___
  3614. / _ \ | | | |\/| | |/ __| '__/ _ \| '_ \| '_ \ / _ \| '_ \ / _ \
  3615. / ___ \ | | | | | | | (__| | | (_) | |_) | | | | (_) | | | | __/
  3616. /_/ \_\___| |_| |_|_|\___|_| \___/| .__/|_| |_|\___/|_| |_|\___|
  3617. |_|
  3618. */
  3619. Blockly.Blocks['ai_mphone_init'] = {
  3620. init: function () {
  3621. this.appendDummyInput()
  3622. .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3623. this.appendDummyInput()
  3624. .appendField(Blockly.Msg.ai_microphone_init);
  3625. this.setPreviousStatement(true);
  3626. this.setNextStatement(true);
  3627. this.setColour("#5fcd8e");
  3628. this.setTooltip(Blockly.Msg.ai_mphone_init_TOOLTIP);
  3629. this.setHelpUrl("");
  3630. }
  3631. };
  3632. Blockly.Python.ai_mphone_init = function (block) {
  3633. Blockly.Python.definitions_.import_all_mphone = "" +
  3634. "from Maix import GPIO, I2S, FFT\n" +
  3635. "from board import board_info\n" +
  3636. "from fpioa_manager import fm\n" +
  3637. "\n" +
  3638. "sample_rate = 38640\n" +
  3639. "sample_points = 1024\n" +
  3640. "fft_points = 512\n" +
  3641. "hist_x_num = 50\n" +
  3642. "\n" +
  3643. "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" +
  3644. "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" +
  3645. "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" +
  3646. "\n" +
  3647. "_recorder_rx = I2S(I2S.DEVICE_0)\n" +
  3648. "_recorder_rx.channel_config(_recorder_rx.CHANNEL_0, _recorder_rx.RECEIVER, align_mode = I2S.STANDARD_MODE)\n" +
  3649. "_recorder_rx.set_sample_rate(sample_rate)\n" +
  3650. "def _microphone_read_average(lst): \n" +
  3651. " return int((sum(lst)/len(lst))*100)\n" +
  3652. "";
  3653. // Blockly.Python.addVariable('sample_rate', "sample_rate = 38640", true);
  3654. // Blockly.Python.addVariable('sample_points', "sample_points = 1024", true);
  3655. // Blockly.Python.addVariable('fft_points', "fft_points = 512", true);
  3656. // Blockly.Python.addVariable('hist_x_num', "hist_x_num = 50", true);
  3657. // Blockly.Python.addVariable('_recorder_rx', "_recorder_rx = None", true);
  3658. // Blockly.Python.addVariable('fft_res', "fft_res = None", true);
  3659. // Blockly.Python.addVariable('fft_amp', "fft_amp = None", true);
  3660. Blockly.Python.addVariable('read_all_channel', "read_all_channel = [0, 0, 0, 0, 0, 0, 0, 0]", true);
  3661. // Blockly.Python.addVariable('_recorder_rx', "", true);
  3662. var _code = "" +
  3663. "";
  3664. return _code;
  3665. }
  3666. Blockly.Blocks['ai_mphone_Record_audio_init'] = {
  3667. init: function () {
  3668. this.appendDummyInput()
  3669. .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3670. this.appendDummyInput()
  3671. .appendField(Blockly.Msg.ai_mphone_Record_audio_init);
  3672. this.setPreviousStatement(true);
  3673. this.setNextStatement(true);
  3674. this.setColour("#5fcd8e");
  3675. this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_init_TOOLTIP);
  3676. this.setHelpUrl("");
  3677. }
  3678. };
  3679. Blockly.Python.ai_mphone_Record_audio_init = function (block) {
  3680. Blockly.Python.definitions_.import_ai_mphone_Record_audio_init = "" +
  3681. "from Maix import GPIO, I2S\n" +
  3682. "from fpioa_manager import fm\n" +
  3683. 'import audio\n' +
  3684. "\n" +
  3685. '# user setting\n' +
  3686. "sample_rate = 16000\n" +
  3687. "# default seting\n" +
  3688. "sample_points = 2048\n" +
  3689. "wav_ch = 2\n" +
  3690. "\n" +
  3691. 'fm.register(8, fm.fpioa.GPIO0, force=True)\n' +
  3692. 'wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT)\n' +
  3693. 'wifi_en.value(0)\n' +
  3694. "\n" +
  3695. "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" +
  3696. "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" +
  3697. "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" +
  3698. "\n" +
  3699. "rx = I2S(I2S.DEVICE_0)\n" +
  3700. "rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode=I2S.STANDARD_MODE)\n" +
  3701. "rx.set_sample_rate(sample_rate)\n" +
  3702. "print(rx)\n" +
  3703. "";
  3704. var _code = "" +
  3705. "";
  3706. return _code;
  3707. }
  3708. Blockly.Blocks['ai_mphone_record_init'] = {
  3709. init: function () {
  3710. this.appendDummyInput()
  3711. .appendField(Blockly.Msg.ai_microphone_init);
  3712. this.setPreviousStatement(true);
  3713. this.setNextStatement(true, null);
  3714. this.setColour("#5fcd8e");
  3715. this.setTooltip(Blockly.Msg.ai_microphone_init);
  3716. this.setHelpUrl("");
  3717. }
  3718. }
  3719. Blockly.Python['ai_mphone_record_init'] = function (block) {
  3720. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3721. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3722. Blockly.Python.definitions_['v831_import_os'] = `import os`
  3723. let code = ''
  3724. return code;
  3725. }
  3726. Blockly.Blocks['ai_mphone_record_setting'] = {
  3727. init: function () {
  3728. this.appendValueInput("path")
  3729. .setCheck(null)
  3730. .appendField(Blockly.Msg.ai_mphone_Record_audio_start_path);
  3731. this.appendValueInput("record_time").setCheck(null)
  3732. .appendField(Blockly.Msg.ai_mphone_Record_audio_start_time)
  3733. this.setPreviousStatement(true);
  3734. this.setNextStatement(true, null);
  3735. this.setColour("#5fcd8e");
  3736. this.setTooltip(Blockly.Msg.ai_microphone_init);
  3737. this.setHelpUrl("");
  3738. }
  3739. }
  3740. Blockly.Python['ai_mphone_record_setting'] = function (block) {
  3741. var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  3742. var record_time = Blockly.Python.valueToCode(block, 'record_time', Blockly.Python.ORDER_ATOMIC);
  3743. let code = `if(os.path.exists(${value_path})):
  3744. os.system("rm ${value_path.slice(1, value_path.length - 1)}")
  3745. CHUNK = 1024
  3746. FORMAT = pyaudio.paInt16
  3747. CHANNELS = 1
  3748. RATE = 16000
  3749. RECORD_SECONDS = ${Number(record_time) + 1}
  3750. WAVE_OUTPUT_FILENAME = ${value_path}
  3751. p = pyaudio.PyAudio()
  3752. stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
  3753. `
  3754. return code;
  3755. }
  3756. Blockly.Blocks['ai_mphone_Record_audio_start'] = {
  3757. init: function () {
  3758. this.appendDummyInput()
  3759. .appendField(Blockly.Msg.ai_mphone_Record_audio_start);
  3760. this.setPreviousStatement(true);
  3761. this.setNextStatement(true, null);
  3762. this.setColour("#5fcd8e");
  3763. this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start_TOOLTIP);
  3764. this.setHelpUrl("");
  3765. }
  3766. };
  3767. Blockly.Python['ai_mphone_Record_audio_start'] = function (block) {
  3768. var code = `
  3769. print("* recording")
  3770. frames = []
  3771. for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
  3772. data = stream.read(CHUNK,exception_on_overflow = False)
  3773. frames.append(data)
  3774. print("* done recording")
  3775. stream.stop_stream()
  3776. stream.close()
  3777. p.terminate()
  3778. wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
  3779. wf.setnchannels(CHANNELS)
  3780. wf.setsampwidth(p.get_sample_size(FORMAT))
  3781. wf.setframerate(RATE)
  3782. wf.writeframes(b"".join(frames))
  3783. wf.close()
  3784. `;
  3785. return code;
  3786. };
  3787. Blockly.Blocks['ai_mphone_Record_audio_sound_loudness_analysis'] = {
  3788. init: function () {
  3789. this.appendDummyInput()
  3790. .appendField("获取声音响度值");
  3791. // this.setPreviousStatement(true);
  3792. // this.setNextStatement(true, null);
  3793. this.setOutput(true, null);
  3794. this.setColour("#5fcd8e");
  3795. this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start_TOOLTIP);
  3796. this.setHelpUrl("");
  3797. }
  3798. };
  3799. Blockly.Python['ai_mphone_Record_audio_sound_loudness_analysis'] = function (block) {
  3800. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
  3801. Blockly.Python.definitions_['v831_sound_loudness_analysis_init'] = `CHUNK = 1024
  3802. FORMAT = pyaudio.paInt16
  3803. CHANNELS = 1
  3804. RATE = 44100
  3805. p = pyaudio.PyAudio()
  3806. stream = p.open(format=FORMAT,
  3807. channels=CHANNELS,
  3808. rate=RATE,
  3809. input=True,
  3810. frames_per_buffer=CHUNK)
  3811. `
  3812. Blockly.Python.addFunction("get_sound_loudness", `def get_sound_loudness():
  3813. global CHUNK,stream
  3814. stream.start_stream()
  3815. str_data = stream.read(CHUNK) # 从麦克风获取一帧音频数据
  3816. stream.stop_stream()
  3817. # 将音频数据转换为NumPy数组
  3818. arr = np.frombuffer(str_data, dtype=np.int16)
  3819. # 计算音频数据的绝对值之和,即为声音强度
  3820. # 1024个16位的wav采样点(-32768~32767)的绝对值之和,需要将其映射到0~1023
  3821. intensity = int(np.abs(arr).sum()/32768)
  3822. return intensity
  3823. `)
  3824. var code = `get_sound_loudness()`;
  3825. return [code, Blockly.Python.ORDER_NONE];
  3826. };
  3827. Blockly.Blocks['mphone_audio_spectrum_init'] = {
  3828. init: function () {
  3829. this.appendDummyInput()
  3830. .appendField(new Blockly.FieldImage("blockly/media/ai_audio_spectrum.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  3831. this.appendDummyInput()
  3832. .appendField(Blockly.Msg.ai_microphone_start_spectrum_analyze);
  3833. this.setPreviousStatement(true, null);
  3834. this.setNextStatement(true, null);
  3835. this.setColour("#5fcd8e");
  3836. this.setTooltip(Blockly.Msg.mphone_audio_spectrum_init_TOOLTIP);
  3837. this.setHelpUrl("");
  3838. }
  3839. };
  3840. Blockly.Python['mphone_audio_spectrum_init'] = function (block) {
  3841. // TODO: Assemble Python into code variable.
  3842. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
  3843. Blockly.Python.definitions_['v831_sound_frequency_analysis_init'] = `CHUNK = 1024
  3844. FORMAT = pyaudio.paInt16
  3845. CHANNELS = 2
  3846. RATE = 44100
  3847. p = pyaudio.PyAudio()
  3848. stream = p.open(format=FORMAT,
  3849. channels=CHANNELS,
  3850. rate=RATE,
  3851. input=True,
  3852. frames_per_buffer=CHUNK)
  3853. `
  3854. Blockly.Python.addFunction("get_frequency_analysis", `def get_frequency_analysis():
  3855. global CHUNK,stream
  3856. stream.start_stream()
  3857. str_data = stream.read(CHUNK) # 从麦克风获取一帧音频数据
  3858. stream.stop_stream()
  3859. # 将音频数据转换为NumPy数组
  3860. arr = np.frombuffer(str_data, dtype=np.int16)
  3861. arr.shape = -1,2
  3862. # 将数组转置
  3863. arr = arr.T
  3864. f_signal = np.fft.fft(arr[0])
  3865. fft_data = f_signal[:512]
  3866. fft_data = np.split(fft_data, 8)
  3867. avg_data = np.abs(fft_data).mean(axis=1)
  3868. return avg_data
  3869. `)
  3870. var code = `FEEQUENCYANALYSISVALUE = get_frequency_analysis().tolist()\n`;
  3871. return code;
  3872. };
  3873. Blockly.Blocks['ai_mphone_read_sound_sensitivity'] = {
  3874. init: function () {
  3875. this.appendDummyInput()
  3876. .appendField(Blockly.Msg.ai_microphone_get_spectrum_analyze_result)
  3877. .appendField(new Blockly.FieldDropdown([
  3878. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_1, "0"],
  3879. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_2, "1"],
  3880. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_3, "2"],
  3881. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_4, "3"],
  3882. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_5, "4"],
  3883. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_6, "5"],
  3884. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_7, "6"],
  3885. [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_8, "7"]
  3886. ]), "level");
  3887. this.setOutput(true, null);
  3888. this.setColour("#5fcd8e");
  3889. this.setTooltip(Blockly.Msg.ai_mphone_read_sound_sensitivity_TOOLTIP);
  3890. this.setHelpUrl("");
  3891. }
  3892. };
  3893. Blockly.Python['ai_mphone_read_sound_sensitivity'] = function (block) {
  3894. var dropdown_level = block.getFieldValue('level');
  3895. // TODO: Assemble Python into code variable.
  3896. var code = `int(FEEQUENCYANALYSISVALUE[${dropdown_level}]/500)`;
  3897. // TODO: Change ORDER_NONE to the correct strength.
  3898. return [code, Blockly.Python.ORDER_NONE];
  3899. };
  3900. Blockly.Blocks['ai_audio_start_recording'] = {
  3901. init: function () {
  3902. this.appendDummyInput()
  3903. .appendField(Blockly.Msg.ai_audio_play_music_file);
  3904. this.appendValueInput("path")
  3905. .setCheck(null)
  3906. .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  3907. this.setPreviousStatement(true, null);
  3908. this.setNextStatement(true, null);
  3909. this.setColour("#5fcd8e");
  3910. this.setTooltip(Blockly.Msg.ai_audio_stop_recording_TOOLTIP);
  3911. this.setHelpUrl("");
  3912. }
  3913. };
  3914. Blockly.Python['ai_audio_start_recording'] = function (block) {
  3915. // TODO: Assemble Python into code variable.
  3916. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3917. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3918. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  3919. sys.path.append("/root/")`
  3920. var code = `
  3921. CHUNK = 1024
  3922. wf = wave.open(r"test.wav", "rb")#(sys.argv[1], "rb"
  3923. p = pyaudio.PyAudio()
  3924. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
  3925. channels=wf.getnchannels(),
  3926. rate=wf.getframerate(),
  3927. output=True)
  3928. data = wf.readframes(CHUNK)
  3929. while len(data) > 0:
  3930. stream.write(data)
  3931. data = wf.readframes(CHUNK)
  3932. stream.stop_stream()
  3933. stream.close()
  3934. p.terminate()
  3935. `;
  3936. return code;
  3937. };
  3938. /*
  3939. _ ___ _ _ _
  3940. / \ |_ _| / \ _ _ __| (_) ___
  3941. / _ \ | | / _ \| | | |/ _` | |/ _ \
  3942. / ___ \ | | / ___ \ |_| | (_| | | (_) |
  3943. /_/ \_\___| /_/ \_\__,_|\__,_|_|\___/
  3944. */
  3945. Blockly.Blocks['ai_audio_play_init'] = {
  3946. init: function () {
  3947. this.appendDummyInput()
  3948. .appendField(Blockly.Msg.AUDIO_S);
  3949. this.setPreviousStatement(true, null);
  3950. this.setNextStatement(true, null);
  3951. this.setColour("#603ea0");
  3952. this.setTooltip("");
  3953. this.setHelpUrl("");
  3954. }
  3955. };
  3956. Blockly.Python['ai_audio_play_init'] = function (block) {
  3957. Blockly.Python.definitions_['v831_import_os'] = `import os`
  3958. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  3959. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  3960. Blockly.Python.definitions_['v831_import_time'] = `import time`
  3961. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  3962. sys.path.append("/root/")`
  3963. Blockly.Python.addVariable("VOICESTATE", "VOICESTATE = 0", true)
  3964. Blockly.Python.addVariable("VOICEDATA", "", true)
  3965. Blockly.Python.addVariable("VOICESTREAM", 'VOICESTREAM = ""', true)
  3966. Blockly.Python.addVariable("VOICEPYAUDIO", "VOICEPYAUDIO = pyaudio.PyAudio()", true)
  3967. Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true)
  3968. Blockly.Python.addVariable("VOICEPPATH", "", true)
  3969. Blockly.Python.addVariable("VOICEPLAYSTATE", 'VOICEPLAYSTATE = True', true)
  3970. Blockly.Python.addVariable("VOICEWF", 'VOICEWF = ""', true)
  3971. var _code = ``;
  3972. return _code;
  3973. };
  3974. Blockly.Blocks['ai_audio_play_volume'] = {
  3975. init: function () {
  3976. this.appendDummyInput()
  3977. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  3978. .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol")
  3979. .appendField("(0~100)");
  3980. this.setPreviousStatement(true, null);
  3981. this.setNextStatement(true, null);
  3982. this.setColour("#603ea0");
  3983. this.setTooltip("");
  3984. this.setHelpUrl("");
  3985. }
  3986. };
  3987. Blockly.Python['ai_audio_play_volume'] = function (block) {
  3988. var number_play_vol = block.getFieldValue('play_vol');
  3989. Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
  3990. valueScaled = float(value - 0) / float(100)
  3991. return int(valueScaled * 31)
  3992. `
  3993. var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol}))
  3994. time.sleep(0.01)
  3995. SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
  3996. `;
  3997. return _code;
  3998. };
  3999. Blockly.Blocks['ai_audio_play_song'] = {
  4000. init: function () {
  4001. this.appendValueInput("path")
  4002. .setCheck(null)
  4003. .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  4004. this.setPreviousStatement(true, null);
  4005. this.setNextStatement(true, null);
  4006. this.setColour("#603ea0");
  4007. this.setTooltip("");
  4008. this.setHelpUrl("");
  4009. }
  4010. };
  4011. Blockly.Python['ai_audio_play_song'] = function (block) {
  4012. var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4013. // Blockly.Python.addVariable("VOICEPPATH","",false)
  4014. var _code = `VOICEPLAYSTATE = True
  4015. VOICEPPATH = ${value_name}
  4016. `;
  4017. return _code;
  4018. };
  4019. Blockly.Blocks['ai_audio_play_start'] = {
  4020. init: function () {
  4021. this.appendDummyInput()
  4022. .appendField(Blockly.Msg.ai_audio_start_play);
  4023. this.setPreviousStatement(true, null);
  4024. this.setNextStatement(true, null);
  4025. this.setColour("#603ea0");
  4026. this.setTooltip(Blockly.Msg.ai_audio_start_play);
  4027. this.setHelpUrl("");
  4028. }
  4029. }
  4030. Blockly.Python['ai_audio_play_start'] = function (block) {
  4031. Blockly.Python.definitions_["VoicePlayState"] = `def VoicePlayState():
  4032. global VOICESTATE,VOICEDATA,CHUNK,VOICESTREAM,VOICEPYAUDIO,VOICEWF,VOICEPPATH
  4033. if VOICESTATE == 0:
  4034. VOICEWF = wave.open(VOICEPPATH, "rb")#(sys.argv[1], "rb"
  4035. VOICEPYAUDIO = pyaudio.PyAudio()
  4036. VOICESTREAM = VOICEPYAUDIO.open(format=VOICEPYAUDIO.get_format_from_width(VOICEWF.getsampwidth()),channels=VOICEWF.getnchannels(),rate=VOICEWF.getframerate(),output=True)
  4037. VOICEDATA = VOICEWF.readframes(CHUNK)
  4038. VOICESTATE = 1
  4039. return True
  4040. else:
  4041. if len(VOICEDATA) > 0:
  4042. try:
  4043. VOICESTREAM.write(VOICEDATA)
  4044. VOICEDATA = VOICEWF.readframes(CHUNK)
  4045. return True
  4046. except:
  4047. VOICESTATE = 0
  4048. else:
  4049. VOICESTREAM.stop_stream()
  4050. VOICESTREAM.close()
  4051. VOICEPYAUDIO.terminate()
  4052. VOICESTATE = 0
  4053. return False
  4054. `
  4055. let code = `VOICEPLAYSTATE = VoicePlayState()
  4056. `
  4057. return code;
  4058. }
  4059. Blockly.Blocks['ai_audio_play_finish'] = {
  4060. init: function () {
  4061. this.appendDummyInput()
  4062. .appendField(Blockly.Msg.ai_audio_end_play);
  4063. this.setPreviousStatement(true, null);
  4064. this.setNextStatement(true, null);
  4065. this.setColour("#603ea0");
  4066. this.setTooltip("");
  4067. this.setHelpUrl("");
  4068. }
  4069. };
  4070. Blockly.Python['ai_audio_play_finish'] = function (block) {
  4071. // TODO: Assemble Python into code variable.
  4072. var code = `try:
  4073. VOICESTREAM.stop_stream()
  4074. VOICESTREAM.close()
  4075. VOICEPYAUDIO.terminate()
  4076. VOICESTATE = 0
  4077. except:
  4078. pass
  4079. `;
  4080. return code;
  4081. };
  4082. Blockly.Blocks['ai_audio_get_play_status'] = {
  4083. init: function () {
  4084. this.appendDummyInput()
  4085. .appendField(Blockly.Msg.ai_audio_get_play_status);
  4086. this.setOutput(true, null);
  4087. this.setColour("#603ea0");
  4088. this.setTooltip(Blockly.Msg.ai_audio_play_state_speaker_TOOLTIP);
  4089. this.setHelpUrl("");
  4090. }
  4091. };
  4092. Blockly.Python['ai_audio_get_play_status'] = function (block) {
  4093. // TODO: Assemble Python into code variable.
  4094. var code = 'VOICEPLAYSTATE';
  4095. // TODO: Change ORDER_NONE to the correct strength.
  4096. return [code, Blockly.Python.ORDER_NONE];
  4097. };
  4098. // 在线语音识别
  4099. Blockly.Blocks['ai_online_voice_init'] = {
  4100. init: function () {
  4101. this.appendDummyInput()
  4102. .appendField(Blockly.Msg.online_voice_init); //
  4103. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4104. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4105. this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
  4106. this.setPreviousStatement(true, null);
  4107. this.setNextStatement(true, null);
  4108. this.setColour("#0000ff");
  4109. this.setTooltip(Blockly.Msg.online_voice_init);
  4110. this.setHelpUrl("");
  4111. }
  4112. };
  4113. Blockly.Python['ai_online_voice_init'] = function (block) {
  4114. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4115. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4116. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4117. // TODO: Assemble Python into code variable.
  4118. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4119. Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
  4120. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4121. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4122. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4123. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4124. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4125. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4126. Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
  4127. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4128. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4129. Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
  4130. Blockly.Python.definitions_.ai_online_voice_init = `
  4131. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  4132. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  4133. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  4134. class Ws_Param_voice(object):
  4135. # 初始化
  4136. def __init__(self, APPID, APIKey, APISecret, AudioFile):
  4137. self.APPID_voice = APPID
  4138. self.APIKey_voice = APIKey
  4139. self.APISecret_voice = APISecret
  4140. self.AudioFile_voice = AudioFile
  4141. # 公共参数(common)
  4142. self.CommonArgs = {"app_id": self.APPID_voice}
  4143. # 业务参数(business),更多个性化参数可在官网查看
  4144. self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000}
  4145. # 生成url
  4146. def create_url_voice(self):
  4147. url = "wss://ws-api.xfyun.cn/v2/iat"
  4148. # 生成RFC1123格式的时间戳
  4149. now = datetime.now()
  4150. date = format_date_time(mktime(now.timetuple()))
  4151. # 拼接字符串
  4152. signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
  4153. signature_origin += "date: " + date + "\\n"
  4154. signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
  4155. # 进行hmac-sha256进行加密
  4156. signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"),
  4157. digestmod=hashlib.sha256).digest()
  4158. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4159. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha)
  4160. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4161. # 将请求的鉴权参数组合为字典
  4162. v = {
  4163. "authorization": authorization,
  4164. "date": date,
  4165. "host": "ws-api.xfyun.cn"
  4166. }
  4167. # 拼接鉴权参数,生成url
  4168. url = url + "?" + urlencode(v)
  4169. # print("date: ",date)
  4170. # print("v: ",v)
  4171. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  4172. # print('websocket url :', url)
  4173. return url
  4174. # 收到websocket消息的处理
  4175. def on_message_voice(ws, message):
  4176. global asr_result,txt_result
  4177. try:
  4178. code = json.loads(message)["code"]
  4179. sid = json.loads(message)["sid"]
  4180. if code != 0:
  4181. errMsg = json.loads(message)["message"]
  4182. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  4183. else:
  4184. data = json.loads(message)["data"]["result"]["ws"]
  4185. # print(json.loads(message))
  4186. result = ""
  4187. for i in data:
  4188. for w in i["cw"]:
  4189. result += w["w"]
  4190. print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False)))
  4191. print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False)))
  4192. asr_result.append(eval(json.dumps(data, ensure_ascii=False)))
  4193. txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1]))
  4194. except Exception as e:
  4195. print("receive msg,but parse exception:", e)
  4196. # 收到websocket错误的处理
  4197. def on_error_voice(ws, error):
  4198. print("### error:", error)
  4199. # 收到websocket关闭的处理
  4200. def on_close_voice(ws):
  4201. print("### closed ###")
  4202. # 收到websocket连接建立的处理
  4203. def on_open_voice(ws):
  4204. def run_voice(*args):
  4205. global wsParam_voice
  4206. frameSize = 8000 # 每一帧的音频大小
  4207. intervel = 0.04 # 发送音频间隔(单位:s)
  4208. status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧
  4209. with open(wsParam_voice.AudioFile_voice, "rb") as fp:
  4210. while True:
  4211. buf = fp.read(frameSize)
  4212. # 文件结束
  4213. if not buf:
  4214. status = STATUS_LAST_FRAME
  4215. # 第一帧处理
  4216. # 发送第一帧音频,带business 参数
  4217. # appid 必须带上,只需第一帧发送
  4218. if status == STATUS_FIRST_FRAME:
  4219. d = {"common": wsParam_voice.CommonArgs,
  4220. "business": wsParam_voice.BusinessArgs,
  4221. "data": {"status": 0, "format": "audio/L16;rate=16000",
  4222. "audio": str(base64.b64encode(buf), "utf-8"),
  4223. "encoding": "raw"}}
  4224. d = json.dumps(d)
  4225. ws.send(d)
  4226. status = STATUS_CONTINUE_FRAME
  4227. # 中间帧处理
  4228. elif status == STATUS_CONTINUE_FRAME:
  4229. d = {"data": {"status": 1, "format": "audio/L16;rate=16000",
  4230. "audio": str(base64.b64encode(buf), "utf-8"),
  4231. "encoding": "raw"}}
  4232. ws.send(json.dumps(d))
  4233. # 最后一帧处理
  4234. elif status == STATUS_LAST_FRAME:
  4235. d = {"data": {"status": 2, "format": "audio/L16;rate=16000",
  4236. "audio": str(base64.b64encode(buf), "utf-8"),
  4237. "encoding": "raw"}}
  4238. ws.send(json.dumps(d))
  4239. time.sleep(1)
  4240. break
  4241. # 模拟音频采样间隔
  4242. time.sleep(intervel)
  4243. ws.close()
  4244. thread.start_new_thread(run_voice, ())
  4245. asr_result=[]
  4246. txt_result=[]
  4247. APPId_voice = ${APPId}
  4248. APISecret_voice = ${APISecret}
  4249. APIKey_voice = ${APIKey}
  4250. `
  4251. var code = '';
  4252. return code;
  4253. };
  4254. // 在线语音识别加载
  4255. Blockly.Blocks['ai_online_voice_loading'] = {
  4256. init: function () {
  4257. this.appendDummyInput()
  4258. .appendField(Blockly.Msg.online_voice_loading); //
  4259. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_voice_init_path);
  4260. this.setPreviousStatement(true, null);
  4261. this.setNextStatement(true, null);
  4262. this.setColour("#0000ff");
  4263. this.setTooltip(Blockly.Msg.online_voice_loading);
  4264. this.setHelpUrl("");
  4265. }
  4266. };
  4267. Blockly.Python['ai_online_voice_loading'] = function (block) {
  4268. var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4269. Blockly.Python.definitions_['get_online_voice_data'] = `asr_string=""
  4270. def getVoiceData():
  4271. global wsParam_voice,asr_string,txt_result,asr_result
  4272. # 测试时候在此处正确填写相关信息即可运行
  4273. asr_string = ""
  4274. txt_result = []
  4275. asr_result = []
  4276. time1 = datetime.now()
  4277. wsParam_voice = Ws_Param_voice(APPID=APPId_voice, APISecret=APISecret_voice,
  4278. APIKey=APIKey_voice,
  4279. AudioFile=${AudioFile})
  4280. websocket.enableTrace(False)
  4281. wsUrl = wsParam_voice.create_url_voice()
  4282. ws = websocket.WebSocketApp(wsUrl, on_message=on_message_voice, on_error=on_error_voice)
  4283. ws.on_open = on_open_voice
  4284. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  4285. time2 = datetime.now()
  4286. for i in range(len(asr_result)):
  4287. for j in range(len(asr_result[i])):
  4288. txt_result.append(asr_result[i][j]["cw"][0]["w"])
  4289. print("txt_result:", txt_result)
  4290. for i in range(len(txt_result)):
  4291. asr_string=asr_string+txt_result[i]
  4292. print("asr_string:", asr_string)
  4293. return asr_string
  4294. `
  4295. let code = `VoiceResult = getVoiceData()
  4296. `;
  4297. return code;
  4298. };
  4299. Blockly.Blocks['ai_online_voice_result'] = {
  4300. init: function () {
  4301. this.appendDummyInput()
  4302. .appendField(Blockly.Msg.online_voice_result); //
  4303. this.setOutput(true, null);
  4304. this.setColour("#0000ff");
  4305. this.setTooltip(Blockly.Msg.online_voice_result);
  4306. this.setHelpUrl("");
  4307. }
  4308. };
  4309. Blockly.Python['ai_online_voice_result'] = function (block) {
  4310. let code = `VoiceResult`;
  4311. return [code, Blockly.Python.ORDER_ATOMIC];
  4312. };
  4313. // 在线人脸识别
  4314. Blockly.Blocks['ai_online_ident_init'] = {
  4315. init: function () {
  4316. this.appendDummyInput()
  4317. .appendField(Blockly.Msg.online_face_init); //
  4318. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4319. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4320. this.appendValueInput("C").setCheck(null).appendField('API Key');
  4321. this.setPreviousStatement(true, null);
  4322. this.setNextStatement(true, null);
  4323. this.setColour("#0000ff");
  4324. this.setTooltip(Blockly.Msg.online_face_init);
  4325. this.setHelpUrl("");
  4326. }
  4327. };
  4328. Blockly.Python['ai_online_ident_init'] = function (block) {
  4329. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4330. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4331. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4332. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4333. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4334. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4335. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4336. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4337. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4338. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4339. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4340. Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
  4341. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4342. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4343. Blockly.Python.definitions_.ai_online_ident_init = `
  4344. class AssembleHeaderException(Exception):
  4345. def __init__(self, msg):
  4346. self.message = msg
  4347. class Url:
  4348. def __init__(this, host, path, schema):
  4349. this.host = host
  4350. this.path = path
  4351. this.schema = schema
  4352. pass
  4353. # 进行sha256加密和base64编码
  4354. def sha256base64(data):
  4355. sha256 = hashlib.sha256()
  4356. sha256.update(data)
  4357. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  4358. return digest
  4359. def parse_url_face(requset_url):
  4360. stidx = requset_url.index("://")
  4361. host = requset_url[stidx + 3:]
  4362. schema = requset_url[:stidx + 3]
  4363. edidx = host.index("/")
  4364. if edidx <= 0:
  4365. raise AssembleHeaderException("invalid request url:" + requset_url)
  4366. path = host[edidx:]
  4367. host = host[:edidx]
  4368. u = Url(host, path, schema)
  4369. return u
  4370. def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""):
  4371. u = parse_url_face(requset_url)
  4372. host = u.host
  4373. path = u.path
  4374. now = datetime.now()
  4375. date = format_date_time(mktime(now.timetuple()))
  4376. print(date)
  4377. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  4378. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  4379. print(signature_origin)
  4380. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  4381. digestmod=hashlib.sha256).digest()
  4382. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4383. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  4384. api_key, "hmac-sha256", "host date request-line", signature_sha)
  4385. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4386. print(authorization_origin)
  4387. values = {
  4388. "host": host,
  4389. "date": date,
  4390. "authorization": authorization
  4391. }
  4392. return requset_url + "?" + urlencode(values)
  4393. def gen_body_face(appid, img_path, server_id):
  4394. with open(img_path, "rb") as f:
  4395. img_data = f.read()
  4396. body = {
  4397. "header": {
  4398. "app_id": appid,
  4399. "status": 3
  4400. },
  4401. "parameter": {
  4402. server_id: {
  4403. "service_kind": "face_detect",
  4404. #"detect_points": "1", #检测特征点
  4405. #"detect_property": "1", #检测人脸属性
  4406. "face_detect_result": {
  4407. "encoding": "utf8",
  4408. "compress": "raw",
  4409. "format": "json"
  4410. }
  4411. }
  4412. },
  4413. "payload": {
  4414. "input1": {
  4415. "encoding": "jpg",
  4416. "status": 3,
  4417. "image": str(base64.b64encode(img_data), "utf-8")
  4418. }
  4419. }
  4420. }
  4421. return json.dumps(body)
  4422. APPId_face = ${APPId}
  4423. APISecret_face = ${APISecret}
  4424. APIKey_face = ${APIKey}
  4425. `;
  4426. let code = ''
  4427. return code;
  4428. };
  4429. // 在线人脸识别加载
  4430. Blockly.Blocks['ai_online_ident_loading'] = {
  4431. init: function () {
  4432. this.appendDummyInput()
  4433. .appendField(Blockly.Msg.online_face_loading); //
  4434. this.appendValueInput("path")
  4435. .setCheck(null)
  4436. .appendField(Blockly.Msg.online_face_init_path); //
  4437. this.setPreviousStatement(true, null);
  4438. this.setNextStatement(true, null);
  4439. this.setColour("#0000ff");
  4440. this.setTooltip(Blockly.Msg.online_face_loading);
  4441. this.setHelpUrl("");
  4442. }
  4443. };
  4444. Blockly.Python['ai_online_ident_loading'] = function (block) {
  4445. var path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4446. Blockly.Python.definitions_.online_ident = `
  4447. ONLINE_IDENT_DATA = ""
  4448. def run_face(appid, apikey, apisecret, img_path, server_id="s67c9c78c"):
  4449. url = "http://api.xf-yun.com/v1/private/{}".format(server_id)
  4450. request_url = assemble_ws_auth_url_face(url, "POST", apikey, apisecret)
  4451. headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid}
  4452. print(request_url)
  4453. response = requests.post(request_url, data=gen_body_face(appid, img_path, server_id), headers=headers)
  4454. resp_data = json.loads(response.content.decode("utf-8"))
  4455. print(resp_data)
  4456. picRes=base64.b64decode(resp_data["payload"]["face_detect_result"]["text"]).decode()
  4457. print(picRes)
  4458. with open("/root/pic0.txt","w") as f:
  4459. f.write(picRes)
  4460. return eval(picRes)
  4461. `
  4462. let code = `
  4463. if __name__ == "__main__":
  4464. img_path_face = ${path}
  4465. ONLINE_IDENT_DATA = run_face(appid=APPId_face,apisecret=APISecret_face,apikey=APIKey_face,img_path=img_path_face,)
  4466. `;
  4467. return code;
  4468. };
  4469. // 在线人脸识别结果
  4470. Blockly.Blocks['ai_online_ident_result'] = {
  4471. init: function () {
  4472. this.appendDummyInput()
  4473. .appendField(Blockly.Msg.online_face_result); //
  4474. this.setOutput(true, null);
  4475. this.setColour("#0000ff");
  4476. this.setTooltip(Blockly.Msg.online_face_result);
  4477. this.setHelpUrl("");
  4478. }
  4479. };
  4480. Blockly.Python['ai_online_ident_result'] = function (block) {
  4481. let code = `ONLINE_IDENT_DATA["face_num"]`;
  4482. return [code, Blockly.Python.ORDER_ATOMIC];
  4483. };
  4484. Blockly.Blocks['ai_online_ident_result_people'] = {
  4485. init: function () {
  4486. this.appendDummyInput()
  4487. .appendField(Blockly.Msg.serialcomm_write_item_first)
  4488. .appendField(new Blockly.FieldVariable("i"), "varitem")
  4489. .appendField(Blockly.Msg.face_information)
  4490. .appendField(new Blockly.FieldDropdown([
  4491. [Blockly.Msg.ai_models_object_model_x, "x"],
  4492. [Blockly.Msg.ai_models_object_model_y, "y"],
  4493. [Blockly.Msg.ai_models_object_model_w, "w"],
  4494. [Blockly.Msg.ai_models_object_model_h, "h"],
  4495. // ['人脸属性信息', "property"],
  4496. [Blockly.Msg.ai_models_object_model_confidence, "score"]
  4497. ]), "TYPE");
  4498. this.setOutput(true, null);
  4499. this.setColour("#0000ff");
  4500. this.setTooltip('');
  4501. this.setHelpUrl("");
  4502. }
  4503. }
  4504. Blockly.Python['ai_online_ident_result_people'] = function (block) {
  4505. var type = block.getFieldValue('TYPE');
  4506. var i = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  4507. let code = '';
  4508. if (type == "w") {
  4509. code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('x')`
  4510. } else if (type == "h") {
  4511. code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('y')`
  4512. } else {
  4513. code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}')`
  4514. }
  4515. return [code, Blockly.Python.ORDER_ATOMIC];
  4516. };
  4517. Blockly.Blocks['ai_audio_init'] = {
  4518. init: function () {
  4519. this.appendDummyInput()
  4520. .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  4521. this.appendDummyInput()
  4522. .appendField(Blockly.Msg.Text_to_speech_initialization); //
  4523. this.appendValueInput("A")
  4524. .setCheck(null)
  4525. .appendField('APP ID');
  4526. this.appendValueInput("B")
  4527. .setCheck(null)
  4528. .appendField('API Secret');
  4529. this.appendValueInput("C")
  4530. .setCheck(null)
  4531. .appendField('API Key');
  4532. this.setPreviousStatement(true, null);
  4533. this.setNextStatement(true, null);
  4534. this.setColour("#0000ff");
  4535. this.setTooltip(Blockly.Msg.Text_to_speech_initialization);
  4536. this.setHelpUrl("");
  4537. }
  4538. };
  4539. // 在线文本转语音初始化
  4540. Blockly.Python.ai_audio_init = function (block) {
  4541. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4542. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4543. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4544. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4545. Blockly.Python.definitions_['v831_import_os'] = `import os`
  4546. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4547. Blockly.Python.definitions_['v831_import_wave'] = `import wave`
  4548. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4549. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4550. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4551. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4552. // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime`
  4553. Blockly.Python.definitions_['v831_import_websocket'] = `import websocket`
  4554. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4555. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4556. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4557. Blockly.Python.definitions_['v831_import_ssl'] = `import ssl`
  4558. Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread`
  4559. Blockly.Python.definitions_.ai_audio_init_function = `
  4560. STATUS_FIRST_FRAME = 0 # 第一帧的标识
  4561. STATUS_CONTINUE_FRAME = 1 # 中间帧标识
  4562. STATUS_LAST_FRAME = 2 # 最后一帧的标识
  4563. class Ws_Param_Audio(object):
  4564. # 初始化
  4565. def __init__(self, APPID, APIKey, APISecret, Text):
  4566. self.APPID = APPID
  4567. self.APIKey = APIKey
  4568. self.APISecret = APISecret
  4569. self.Text = Text
  4570. # 公共参数(common)
  4571. self.CommonArgs = {"app_id": self.APPID}
  4572. # 业务参数(business),更多个性化参数可在官网查看
  4573. self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
  4574. self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")}
  4575. #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"”
  4576. #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}
  4577. # 生成url
  4578. def create_url(self):
  4579. url = "wss://tts-api.xfyun.cn/v2/tts"
  4580. # 生成RFC1123格式的时间戳
  4581. now = datetime.now()
  4582. date = format_date_time(mktime(now.timetuple()))
  4583. # 拼接字符串
  4584. signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n"
  4585. signature_origin += "date: " + date + "\\n"
  4586. signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
  4587. # 进行hmac-sha256进行加密
  4588. signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest()
  4589. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4590. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
  4591. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4592. # 将请求的鉴权参数组合为字典
  4593. v = {
  4594. "authorization": authorization,
  4595. "date": date,
  4596. "host": "ws-api.xfyun.cn"
  4597. }
  4598. # 拼接鉴权参数,生成url
  4599. url = url + "?" + urlencode(v)
  4600. # print("date: ",date)
  4601. # print("v: ",v)
  4602. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  4603. # print('websocket url :', url)
  4604. return url
  4605. APPId_Audio = ${APPId}
  4606. APISecret_Audio = ${APISecret}
  4607. APIKey_Audio = ${APIKey}
  4608. `;
  4609. var _code = "";
  4610. return _code;
  4611. }
  4612. Blockly.Blocks['ai_audio_play_state'] = {
  4613. init: function () {
  4614. this.appendDummyInput()
  4615. .appendField(Blockly.Msg.text_conversion_voice); //
  4616. this.appendValueInput("NAME")
  4617. .setCheck(null)
  4618. .appendField(Blockly.Msg.Content_of_text); //
  4619. this.appendValueInput("path")
  4620. .setCheck(null)
  4621. .appendField(Blockly.Msg.Voice_path); //
  4622. this.setPreviousStatement(true, null);
  4623. this.setNextStatement(true, null);
  4624. this.setColour("#0000ff");
  4625. this.setTooltip(Blockly.Msg.text_conversion_voice);
  4626. this.setHelpUrl("");
  4627. }
  4628. };
  4629. Blockly.Python['ai_audio_play_state'] = function (block) {
  4630. // TODO: Assemble Python into code variable.
  4631. let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC)
  4632. let url = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  4633. let path = `${url.slice(1, url.length - 1)}`
  4634. Blockly.Python.definitions_.on_message = `
  4635. def on_message(ws, message):
  4636. try:
  4637. message =json.loads(message)
  4638. code = message["code"]
  4639. sid = message["sid"]
  4640. audio = message["data"]["audio"]
  4641. audio = base64.b64decode(audio)
  4642. status = message["data"]["status"]
  4643. #print(message)
  4644. if status == 2:
  4645. print("ws is closed")
  4646. ws.close()
  4647. if code != 0:
  4648. errMsg = message["message"]
  4649. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  4650. else:
  4651. pcm_path = "${path}"
  4652. with open(pcm_path, "ab") as f:
  4653. f.write(audio)
  4654. print("tts")
  4655. with open(pcm_path, "rb") as pcmfile:
  4656. pcmdata = pcmfile.read()
  4657. with wave.open(pcm_path + ".wav", "wb") as wavfile:
  4658. wavfile.setparams((1, 2, 16000, 0, "NONE", "NONE"))
  4659. wavfile.writeframes(pcmdata)
  4660. except Exception as e:
  4661. print("receive msg,but parse exception:", e)
  4662. # 收到websocket错误的处理
  4663. def on_error(ws, error):
  4664. print("### error:", error)
  4665. # 收到websocket关闭的处理
  4666. def on_close(ws):
  4667. print("### closed ###")
  4668. # 收到websocket连接建立的处理
  4669. def on_open(ws):
  4670. def run(*args):
  4671. global wsParam_Audio
  4672. d = {"common": wsParam_Audio.CommonArgs,"business": wsParam_Audio.BusinessArgs,"data": wsParam_Audio.Data,}
  4673. d = json.dumps(d)
  4674. print("------>开始发送文本数据")
  4675. ws.send(d)
  4676. if os.path.exists(${url}):
  4677. os.remove(${url})
  4678. thread.start_new_thread(run, ())
  4679. `
  4680. Blockly.Python.addVariable('wsParam_Audio', 'wsParam_Audio = ""', true);
  4681. let code = `if __name__ == "__main__":
  4682. #with open('word.txt', 'r',encoding="UTF-8")as f:#txt= f.read()
  4683. txt_Audio=${text}
  4684. if os.path.exists(${url}):
  4685. os.remove(${url})
  4686. # 测试时候在此处正确填写相关信息即可运行
  4687. wsParam_Audio = Ws_Param_Audio(APPID=APPId_Audio, APISecret=APISecret_Audio,APIKey=APIKey_Audio,Text=txt_Audio)
  4688. websocket.enableTrace(False)
  4689. wsUrl = wsParam_Audio.create_url()
  4690. ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close)
  4691. ws.on_open = on_open
  4692. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  4693. `
  4694. // TODO: Change ORDER_NONE to the correct strength.
  4695. return code
  4696. };
  4697. // 在线物体识别
  4698. Blockly.Blocks['ai_online_object_init'] = {
  4699. init: function () {
  4700. this.appendDummyInput()
  4701. .appendField(Blockly.Msg.online_object_init); //
  4702. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4703. // this.appendValueInput("B").setCheck(null).appendField('APISecret');
  4704. this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
  4705. this.setPreviousStatement(true, null);
  4706. this.setNextStatement(true, null);
  4707. this.setColour("#0000ff");
  4708. this.setTooltip(Blockly.Msg.online_object_init);
  4709. this.setHelpUrl("");
  4710. }
  4711. };
  4712. Blockly.Python['ai_online_object_init'] = function (block) {
  4713. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4714. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4715. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4716. // TODO: Assemble Python into code variable.
  4717. Blockly.Python.definitions_['v831_import_time'] = `import time`
  4718. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4719. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4720. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4721. Blockly.Python.definitions_.ai_online_object_init = `
  4722. API_KEY = ${APIKey}
  4723. APPID = ${APPId}
  4724. def objectGetHeader(APPID, image_url, API_KEY):
  4725. with open(image_url, "rb") as f:
  4726. img_data = f.read()
  4727. curTime = str(int(time.time()))
  4728. paramBase64 = base64.b64encode(img_data)
  4729. tmp = str(paramBase64, "utf-8")
  4730. m2 = hashlib.md5()
  4731. m2.update((API_KEY + curTime + tmp).encode("utf-8"))
  4732. checkSum = m2.hexdigest()
  4733. header = {
  4734. 'X-CurTime': curTime,
  4735. 'X-Param': paramBase64,
  4736. 'X-Appid': APPID,
  4737. 'X-CheckSum': checkSum,
  4738. }
  4739. return header
  4740. `
  4741. var code = '';
  4742. return code;
  4743. };
  4744. Blockly.Blocks['ai_online_object_loading'] = {
  4745. init: function () {
  4746. this.appendDummyInput()
  4747. .appendField(Blockly.Msg.online_object_load); //
  4748. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path);
  4749. this.setPreviousStatement(true, null);
  4750. this.setNextStatement(true, null);
  4751. this.setColour("#0000ff");
  4752. this.setTooltip(Blockly.Msg.online_object_load);
  4753. this.setHelpUrl("");
  4754. }
  4755. }
  4756. Blockly.Python.ai_online_object_loading = function (block) {
  4757. var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4758. let code = `ImageUrl = ${AudioFile}
  4759. OBJECTRESULT = requests.post("http://tupapi.xfyun.cn/v1/currency", headers=objectGetHeader(APPID, ImageUrl,API_KEY))
  4760. `
  4761. return code
  4762. }
  4763. Blockly.Blocks['ai_online_object_result'] = {
  4764. init: function () {
  4765. this.appendDummyInput()
  4766. .appendField(Blockly.Msg.online_object_result); //
  4767. this.setOutput(true, null);
  4768. this.setColour("#0000ff");
  4769. this.setTooltip(Blockly.Msg.online_object_result);
  4770. this.setHelpUrl("");
  4771. }
  4772. };
  4773. Blockly.Python['ai_online_object_result'] = function (block) {
  4774. let code = `OBJECTRESULT.content`;
  4775. return [code, Blockly.Python.ORDER_ATOMIC];
  4776. };
  4777. // 在线车牌识别
  4778. Blockly.Blocks['ai_online_card_init'] = {
  4779. init: function () {
  4780. this.appendDummyInput()
  4781. .appendField(Blockly.Msg.online_card_init); //
  4782. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4783. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4784. this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path
  4785. this.setPreviousStatement(true, null);
  4786. this.setNextStatement(true, null);
  4787. this.setColour("#0000ff");
  4788. this.setTooltip(Blockly.Msg.online_card_init);
  4789. this.setHelpUrl("");
  4790. }
  4791. };
  4792. Blockly.Python['ai_online_card_init'] = function (block) {
  4793. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4794. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4795. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4796. // TODO: Assemble Python into code variable.
  4797. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  4798. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  4799. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  4800. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4801. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4802. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4803. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4804. Blockly.Python.definitions_['v831_import_traceback'] = `import traceback`
  4805. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4806. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4807. Blockly.Python.definitions_.ai_online_card_init = `
  4808. APPId_Card = ${APPId}
  4809. APISecret_Card = ${APISecret}
  4810. APIKey_Card = ${APIKey}
  4811. class AssembleHeaderException_Card(Exception):
  4812. def __init__(self, msg):
  4813. self.message = msg
  4814. class Url_Card:
  4815. def __init__(this, host, path, schema):
  4816. this.host = host
  4817. this.path = path
  4818. this.schema = schema
  4819. pass
  4820. # 进行sha256加密和base64编码
  4821. def sha256base64_Card(data):
  4822. sha256 = hashlib.sha256()
  4823. sha256.update(data)
  4824. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  4825. return digest
  4826. def parse_url_Card(requset_url):
  4827. stidx = requset_url.index("://")
  4828. host = requset_url[stidx + 3:]
  4829. schema = requset_url[:stidx + 3]
  4830. edidx = host.index("/")
  4831. if edidx <= 0:
  4832. raise AssembleHeaderException_Card("invalid request url:" + requset_url)
  4833. path = host[edidx:]
  4834. host = host[:edidx]
  4835. u = Url_Card(host, path, schema)
  4836. return u
  4837. def assemble_ws_auth_url_Card(requset_url, method="GET", api_key="", api_secret=""):
  4838. u = parse_url_Card(requset_url)
  4839. host = u.host
  4840. path = u.path
  4841. now = datetime.now()
  4842. date = format_date_time(mktime(now.timetuple()))
  4843. print(date)
  4844. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  4845. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  4846. print(signature_origin)
  4847. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  4848. digestmod=hashlib.sha256).digest()
  4849. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  4850. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  4851. api_key, "hmac-sha256", "host date request-line", signature_sha)
  4852. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  4853. print(authorization_origin)
  4854. values = {
  4855. "host": host,
  4856. "date": date,
  4857. "authorization": authorization
  4858. }
  4859. return requset_url + "?" + urlencode(values)
  4860. def gen_body_Card(appid, img_path, server_id):
  4861. with open(img_path, "rb") as f:
  4862. img_data = f.read()
  4863. body = {
  4864. "header": {
  4865. "app_id": appid,
  4866. "status": 3
  4867. },
  4868. "parameter": {
  4869. server_id: {
  4870. "carLicenseRes": {
  4871. "encoding": "utf8",
  4872. "compress": "raw",
  4873. "format": "json"
  4874. }
  4875. }
  4876. },
  4877. "payload": {
  4878. "carImgBase64Str": {
  4879. "encoding": "jpg",
  4880. "status": 3,
  4881. "image": str(base64.b64encode(img_data), "utf-8")
  4882. }
  4883. }
  4884. }
  4885. return json.dumps(body)
  4886. `
  4887. var code = '';
  4888. return code;
  4889. };
  4890. Blockly.Blocks['ai_online_card_loading'] = {
  4891. init: function () {
  4892. this.appendDummyInput()
  4893. .appendField(Blockly.Msg.online_card_load); //
  4894. this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path);
  4895. this.setPreviousStatement(true, null);
  4896. this.setNextStatement(true, null);
  4897. this.setColour("#0000ff");
  4898. this.setTooltip(Blockly.Msg.online_card_load);
  4899. this.setHelpUrl("");
  4900. }
  4901. }
  4902. Blockly.Python.ai_online_card_loading = function (block) {
  4903. var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  4904. Blockly.Python.definitions_.ai_online_card_load = `def run_Card(appid, apikey, apisecret, img_path, server_id="jd_ocr_car"):
  4905. url = "http://api.xf-yun.com/v1/private/{}".format(server_id)
  4906. request_url = assemble_ws_auth_url_Card(url, "POST", apikey, apisecret)
  4907. headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid}
  4908. #print(request_url)
  4909. response = requests.post(request_url, data=gen_body_Card(appid, img_path, server_id), headers=headers)
  4910. resp_data = json.loads(response.content.decode("utf-8"))
  4911. print(resp_data)
  4912. resultCard = base64.b64decode(resp_data["payload"]["carLicenseRes"]["text"]).decode("utf-8")
  4913. return json.loads(resultCard)
  4914. CARDRESULT = ""
  4915. `
  4916. let code = `if __name__ == "__main__":
  4917. img_path_Card = ${AudioFile}
  4918. CARDRESULT = run_Card(appid=APPId_Card,apisecret=APISecret_Card,apikey=APIKey_Card,img_path=img_path_Card,)
  4919. `
  4920. return code
  4921. }
  4922. Blockly.Blocks['ai_online_card_result'] = {
  4923. init: function () {
  4924. this.appendDummyInput()
  4925. .appendField(Blockly.Msg.online_card_result); //
  4926. this.setOutput(true, null);
  4927. this.setColour("#0000ff");
  4928. this.setTooltip(Blockly.Msg.online_card_result);
  4929. this.setHelpUrl("");
  4930. }
  4931. };
  4932. Blockly.Python['ai_online_card_result'] = function (block) {
  4933. let code = `CARDRESULT`;
  4934. return [code, Blockly.Python.ORDER_ATOMIC];
  4935. };
  4936. // 机器翻译
  4937. Blockly.Blocks['ai_online_machine_translation_init'] = {
  4938. init: function () {
  4939. this.appendDummyInput()
  4940. .appendField(Blockly.Msg.machine_translation_init); //
  4941. this.appendDummyInput()
  4942. .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
  4943. .appendField(new Blockly.FieldDropdown([
  4944. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
  4945. [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
  4946. ]), "from")
  4947. .appendField(Blockly.Msg.machine_translation_to)
  4948. .appendField(new Blockly.FieldDropdown([
  4949. [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"],
  4950. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"],
  4951. ]), "to");
  4952. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  4953. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  4954. this.appendValueInput("C").setCheck(null).appendField('API Key');
  4955. this.setPreviousStatement(true, null);
  4956. this.setNextStatement(true, null);
  4957. this.setColour("#0000ff");
  4958. this.setTooltip(Blockly.Msg.machine_translation_init);
  4959. this.setHelpUrl("");
  4960. }
  4961. };
  4962. Blockly.Python['ai_online_machine_translation_init'] = function (block) {
  4963. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  4964. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  4965. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  4966. let FROM = block.getFieldValue('from')
  4967. let TO = block.getFieldValue('to')
  4968. // TODO: Assemble Python into code variable.
  4969. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  4970. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  4971. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  4972. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  4973. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  4974. Blockly.Python.definitions_['v831_import_json'] = `import json`
  4975. Blockly.Python.definitions_.ai_online_machine_translation_init = `
  4976. APPId_machine = ${APPId}
  4977. APISecret_machine = ${APISecret}
  4978. APIKey_machine = ${APIKey}
  4979. TRANSLATIONTEXT = ""
  4980. class get_result_machine(object):
  4981. def __init__(self,host,TRANSLATIONTEXT):
  4982. # 应用ID(到控制台获取)
  4983. self.APPID_machine = ${APPId}
  4984. # 接口APISercet(到控制台机器翻译服务页面获取)
  4985. self.Secret_machine = ${APISecret}
  4986. # 接口APIKey(到控制台机器翻译服务页面获取)
  4987. self.APIKey_machine= ${APIKey}
  4988. # 以下为POST请求
  4989. self.Host = "itrans.xfyun.cn"
  4990. self.RequestUri = "/v2/its"
  4991. # 设置url
  4992. # print(host)
  4993. self.url="https://"+host+self.RequestUri
  4994. self.HttpMethod = "POST"
  4995. self.Algorithm = "hmac-sha256"
  4996. self.HttpProto = "HTTP/1.1"
  4997. # 设置当前时间
  4998. curTime_utc = datetime.utcnow()
  4999. self.Date = self.httpdate_machine(curTime_utc)
  5000. # 设置业务参数
  5001. # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html
  5002. self.Text=TRANSLATIONTEXT
  5003. self.BusinessArgs={
  5004. "from": "${FROM}",
  5005. "to": "${TO}",
  5006. }
  5007. def hashlib_256_machine(self, res):
  5008. m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
  5009. result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
  5010. return result
  5011. def httpdate_machine(self, dt):
  5012. """
  5013. Return a string representation of a date according to RFC 1123
  5014. (HTTP/1.1).
  5015. The supplied date must be in UTC.
  5016. """
  5017. weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
  5018. month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  5019. "Oct", "Nov", "Dec"][dt.month - 1]
  5020. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
  5021. dt.year, dt.hour, dt.minute, dt.second)
  5022. def generateSignature_machine(self, digest):
  5023. signatureStr = "host: " + self.Host + "\\n"
  5024. signatureStr += "date: " + self.Date + "\\n"
  5025. signatureStr += self.HttpMethod + " " + self.RequestUri \\
  5026. + " " + self.HttpProto + "\\n"
  5027. signatureStr += "digest: " + digest
  5028. signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")),
  5029. bytes(signatureStr.encode(encoding="utf-8")),
  5030. digestmod=hashlib.sha256).digest()
  5031. result = base64.b64encode(signature)
  5032. return result.decode(encoding="utf-8")
  5033. def init_header_machine(self, data):
  5034. digest = self.hashlib_256_machine(data)
  5035. #print(digest)
  5036. sign = self.generateSignature_machine(digest)
  5037. authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
  5038. #print(authHeader)
  5039. headers = {
  5040. "Content-Type": "application/json",
  5041. "Accept": "application/json",
  5042. "Method": "POST",
  5043. "Host": self.Host,
  5044. "Date": self.Date,
  5045. "Digest": digest,
  5046. "Authorization": authHeader
  5047. }
  5048. return headers
  5049. def get_body_machine(self):
  5050. content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8")
  5051. postdata = {
  5052. "common": {"app_id": self.APPID_machine},
  5053. "business": self.BusinessArgs,
  5054. "data": {
  5055. "text": content,
  5056. }
  5057. }
  5058. body = json.dumps(postdata)
  5059. #print(body)
  5060. return body
  5061. def call_url_machine(self):
  5062. if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "":
  5063. print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
  5064. else:
  5065. code = 0
  5066. body=self.get_body_machine()
  5067. headers=self.init_header_machine(body)
  5068. #print(self.url)
  5069. response = requests.post(self.url, data=body, headers=headers,timeout=8)
  5070. status_code = response.status_code
  5071. #print(response.content)
  5072. if status_code!=200:
  5073. # 鉴权失败
  5074. print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
  5075. print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html")
  5076. else:
  5077. # 鉴权成功
  5078. respData = json.loads(response.text)
  5079. #print('result',respData["data"]['result']['trans_result']['dst'])
  5080. # return
  5081. # 以下仅用于调试
  5082. code = str(respData["code"])
  5083. if code=="0":
  5084. return respData["data"]["result"]["trans_result"]["dst"]
  5085. else:
  5086. print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法")
  5087. `
  5088. var code = '';
  5089. return code;
  5090. };
  5091. Blockly.Blocks['ai_online_machine_translation_loading'] = {
  5092. init: function () {
  5093. this.appendDummyInput()
  5094. .appendField(Blockly.Msg.machine_translation_load); //
  5095. this.appendValueInput("NAME")
  5096. .setCheck(null)
  5097. .appendField(Blockly.Msg.Content_of_text); //
  5098. this.setPreviousStatement(true, null);
  5099. this.setNextStatement(true, null);
  5100. this.setColour("#0000ff");
  5101. this.setTooltip(Blockly.Msg.machine_translation_load);
  5102. this.setHelpUrl("");
  5103. }
  5104. }
  5105. Blockly.Python.ai_online_machine_translation_loading = function (block) {
  5106. let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC)
  5107. let code = `TRANSLATIONTEXT = ${text}
  5108. machinehost = "itrans.xfyun.cn"
  5109. #初始化类
  5110. gClass=get_result_machine(host=machinehost,TRANSLATIONTEXT=TRANSLATIONTEXT)
  5111. TRANSLATIONRESULT = gClass.call_url_machine()
  5112. `
  5113. return code
  5114. }
  5115. Blockly.Blocks['ai_online_machine_translation_result'] = {
  5116. init: function () {
  5117. this.appendDummyInput()
  5118. .appendField(Blockly.Msg.machine_translation_result); //
  5119. this.setOutput(true, null);
  5120. this.setColour("#0000ff");
  5121. this.setTooltip(Blockly.Msg.machine_translation_result);
  5122. this.setHelpUrl("");
  5123. }
  5124. };
  5125. Blockly.Python['ai_online_machine_translation_result'] = function (block) {
  5126. let code = `TRANSLATIONRESULT`;
  5127. return [code, Blockly.Python.ORDER_ATOMIC];
  5128. };
  5129. // 手写文字识别
  5130. Blockly.Blocks['ai_online_handwritten_text_init'] = {
  5131. init: function () {
  5132. this.appendDummyInput()
  5133. .appendField(Blockly.Msg.handwritten_text_init); //
  5134. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5135. // this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5136. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5137. this.setPreviousStatement(true, null);
  5138. this.setNextStatement(true, null);
  5139. this.setColour("#0000ff");
  5140. this.setTooltip(Blockly.Msg.handwritten_text_init);
  5141. this.setHelpUrl("");
  5142. }
  5143. };
  5144. Blockly.Python['ai_online_handwritten_text_init'] = function (block) {
  5145. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5146. // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5147. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5148. // TODO: Assemble Python into code variable.
  5149. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5150. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5151. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5152. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5153. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5154. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5155. Blockly.Python.definitions_.ai_online_handwritten_text_init = `
  5156. URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting"
  5157. APPId_handwritten_text = ${APPId}
  5158. APIKey_handwritten_text = ${APIKey}
  5159. def textGetHeader_handwritten_text(language, location):
  5160. curTime = str(int(time.time()))
  5161. param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}"
  5162. paramBase64 = base64.b64encode(param.encode("utf-8"))
  5163. m2 = hashlib.md5()
  5164. str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8")
  5165. m2.update(str1.encode("utf-8"))
  5166. checkSum = m2.hexdigest()
  5167. # 组装http请求头
  5168. header = {
  5169. "X-CurTime": curTime,
  5170. "X-Param": paramBase64,
  5171. "X-Appid": APPId_handwritten_text,
  5172. "X-CheckSum": checkSum,
  5173. "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
  5174. }
  5175. return header
  5176. def getBody_handwritten_text(filepath):
  5177. with open(filepath, "rb") as f:
  5178. imgfile = f.read()
  5179. data = {"image": str(base64.b64encode(imgfile), "utf-8")}
  5180. return data
  5181. `
  5182. var code = '';
  5183. return code;
  5184. };
  5185. Blockly.Blocks['ai_online_handwritten_text_loading'] = {
  5186. init: function () {
  5187. this.appendDummyInput()
  5188. .appendField(Blockly.Msg.handwritten_text_load); //
  5189. // this.appendDummyInput()
  5190. // .appendField('设置识别语种')
  5191. // .appendField(new Blockly.FieldDropdown([
  5192. // ["en", "en"],
  5193. // ["cn|en", "cn|en"],
  5194. // ]), "language");
  5195. this.appendValueInput("path")
  5196. .setCheck(null)
  5197. .appendField(Blockly.Msg.online_face_init_path); //
  5198. this.setPreviousStatement(true, null);
  5199. this.setNextStatement(true, null);
  5200. this.setColour("#0000ff");
  5201. this.setTooltip(Blockly.Msg.handwritten_text_load);
  5202. this.setHelpUrl("");
  5203. }
  5204. }
  5205. Blockly.Python.ai_online_handwritten_text_loading = function (block) {
  5206. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5207. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  5208. let code = `# 语种设置
  5209. textLanguage = "cn|en"
  5210. # 是否返回文本位置信息
  5211. textLocation = "false"
  5212. # 图片上传接口地址
  5213. picFilePath_handwritten_text = ${text}
  5214. HandwrittenTextData = requests.post(URL_handwritten_text, headers=textGetHeader_handwritten_text(textLanguage, textLocation), data=getBody_handwritten_text(picFilePath_handwritten_text))
  5215. `
  5216. return code
  5217. }
  5218. Blockly.Blocks['ai_online_handwritten_text_result'] = {
  5219. init: function () {
  5220. this.appendDummyInput()
  5221. .appendField(Blockly.Msg.handwritten_text_result); //
  5222. this.setOutput(true, null);
  5223. this.setColour("#0000ff");
  5224. this.setTooltip(Blockly.Msg.handwritten_text_result);
  5225. this.setHelpUrl("");
  5226. }
  5227. };
  5228. Blockly.Python['ai_online_handwritten_text_result'] = function (block) {
  5229. Blockly.Python.definitions_.ai_online_handwritten_text_result = `def handwrittenTextDatas_handwritten_text(r):
  5230. my_json_data = r.content.decode("utf8")
  5231. # print(type(my_json))
  5232. loadsData = json.loads(my_json_data)
  5233. # s = json.dumps(data, indent=4, sort_keys=True)
  5234. print("data",my_json_data)
  5235. deal_data = ""
  5236. if loadsData["code"] == "0" :
  5237. t = loadsData["data"]["block"][0]["line"]
  5238. for i in t:
  5239. print(i)
  5240. for j in i["word"]:
  5241. print(j["content"])
  5242. deal_data = deal_data + j["content"] + " "
  5243. #print('deal_data',deal_data)
  5244. return deal_data
  5245. `
  5246. let code = `handwrittenTextDatas_handwritten_text(HandwrittenTextData)`;
  5247. return [code, Blockly.Python.ORDER_ATOMIC];
  5248. };
  5249. // 公式识别
  5250. Blockly.Blocks['ai_online_formula_init'] = {
  5251. init: function () {
  5252. this.appendDummyInput()
  5253. .appendField(Blockly.Msg.formula_init); //
  5254. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5255. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5256. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5257. this.setPreviousStatement(true, null);
  5258. this.setNextStatement(true, null);
  5259. this.setColour("#0000ff");
  5260. this.setTooltip(Blockly.Msg.formula_init);
  5261. this.setHelpUrl("");
  5262. }
  5263. };
  5264. Blockly.Python['ai_online_formula_init'] = function (block) {
  5265. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5266. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5267. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5268. // TODO: Assemble Python into code variable.
  5269. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5270. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5271. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5272. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5273. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5274. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5275. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5276. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5277. Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object):
  5278. def __init__(self,host,path):
  5279. # 应用ID(到控制台获取)
  5280. self.APPID_formula = ${APPId}
  5281. # 接口APISercet(到控制台公式识别服务页面获取)
  5282. self.Secret_formula = ${APISecret}
  5283. # 接口APIKey(到控制台公式识别服务页面获取)
  5284. self.APIKey_formula = ${APIKey}
  5285. # 以下为POST请求
  5286. self.Host_formula = host
  5287. self.RequestUri_formula = "/v2/itr"
  5288. # 设置url
  5289. # print(host)
  5290. self.url_formula="https://"+host+self.RequestUri_formula
  5291. self.HttpMethod_formula = "POST"
  5292. self.Algorithm_formula = "hmac-sha256"
  5293. self.HttpProto_formula = "HTTP/1.1"
  5294. # 设置当前时间
  5295. curTime_utc = datetime.utcnow()
  5296. self.Date_formula = self.httpdate_formula(curTime_utc)
  5297. #设置测试图片文件
  5298. self.AudioPath_formula = path
  5299. self.BusinessArgs_formula={
  5300. "ent": "teach-photo-print",
  5301. "aue": "raw",
  5302. }
  5303. def imgRead_formula(self, path):
  5304. with open(path, "rb") as fo:
  5305. return fo.read()
  5306. def hashlib_256_formula(self, res):
  5307. m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest()
  5308. result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8")
  5309. return result
  5310. def httpdate_formula(self, dt):
  5311. """
  5312. Return a string representation of a date according to RFC 1123
  5313. (HTTP/1.1).
  5314. The supplied date must be in UTC.
  5315. """
  5316. weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
  5317. month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  5318. "Oct", "Nov", "Dec"][dt.month - 1]
  5319. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
  5320. dt.year, dt.hour, dt.minute, dt.second)
  5321. def generateSignature_formula(self, digest):
  5322. signatureStr = "host: " + self.Host_formula + "\\n"
  5323. signatureStr += "date: " + self.Date_formula + "\\n"
  5324. signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\
  5325. + " " + self.HttpProto_formula + "\\n"
  5326. signatureStr += "digest: " + digest
  5327. signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")),
  5328. bytes(signatureStr.encode(encoding="utf-8")),
  5329. digestmod=hashlib.sha256).digest()
  5330. result = base64.b64encode(signature)
  5331. return result.decode(encoding="utf-8")
  5332. def init_header_formula(self, data):
  5333. digest = self.hashlib_256_formula(data)
  5334. #print(digest)
  5335. sign = self.generateSignature_formula(digest)
  5336. authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\""
  5337. #print(authHeader)
  5338. headers = {
  5339. "Content-Type": "application/json",
  5340. "Accept": "application/json",
  5341. "Method": "POST",
  5342. "Host": self.Host_formula,
  5343. "Date": self.Date_formula,
  5344. "Digest": digest,
  5345. "Authorization": authHeader
  5346. }
  5347. return headers
  5348. def get_body_formula(self):
  5349. audioData = self.imgRead_formula(self.AudioPath_formula)
  5350. content = base64.b64encode(audioData).decode(encoding="utf-8")
  5351. postdata = {
  5352. "common": {"app_id": self.APPID_formula},
  5353. "business": self.BusinessArgs_formula,
  5354. "data": {
  5355. "image": content,
  5356. }
  5357. }
  5358. body = json.dumps(postdata)
  5359. #print(body)
  5360. return body
  5361. def call_url_formula(self):
  5362. if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "":
  5363. print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。")
  5364. else:
  5365. code = 0
  5366. body=self.get_body_formula()
  5367. headers=self.init_header_formula(body)
  5368. #print(self.url_formula)
  5369. response = requests.post(self.url_formula, data=body, headers=headers,timeout=8)
  5370. status_code = response.status_code
  5371. #print(response.content)
  5372. if status_code!=200:
  5373. # 鉴权失败
  5374. print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
  5375. print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
  5376. else:
  5377. # 鉴权成功
  5378. respData = json.loads(response.text)
  5379. dataCotent = ""
  5380. try:
  5381. for i in respData["data"]["region"]:
  5382. dataCotent += i["recog"]["content"]
  5383. except:
  5384. dataCotent = "Failure"
  5385. return dataCotent
  5386. FORMULARESULT = ""
  5387. `
  5388. var code = '';
  5389. return code;
  5390. };
  5391. Blockly.Blocks['ai_online_formula_loading'] = {
  5392. init: function () {
  5393. this.appendDummyInput()
  5394. .appendField(Blockly.Msg.formula_load); //
  5395. // this.appendDummyInput()
  5396. // .appendField('设置识别语种')
  5397. // .appendField(new Blockly.FieldDropdown([
  5398. // ["en", "en"],
  5399. // ["cn|en", "cn|en"],
  5400. // ]), "language");
  5401. this.appendValueInput("path")
  5402. .setCheck(null)
  5403. .appendField(Blockly.Msg.online_face_init_path); //
  5404. this.setPreviousStatement(true, null);
  5405. this.setNextStatement(true, null);
  5406. this.setColour("#0000ff");
  5407. this.setTooltip(Blockly.Msg.formula_load);
  5408. this.setHelpUrl("");
  5409. }
  5410. }
  5411. Blockly.Python.ai_online_formula_loading = function (block) {
  5412. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5413. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  5414. let code = `
  5415. if __name__ == "__main__":
  5416. formulaUrlPath_formula = ${text}
  5417. ##示例: host="rest-api.xfyun.cn"域名形式
  5418. host = "rest-api.xfyun.cn"
  5419. #初始化类
  5420. gClass=get_result_formula(host,path=formulaUrlPath_formula)
  5421. FORMULARESULT = gClass.call_url_formula()
  5422. `
  5423. return code
  5424. }
  5425. Blockly.Blocks['ai_online_formula_result'] = {
  5426. init: function () {
  5427. this.appendDummyInput()
  5428. .appendField(Blockly.Msg.formula_result); //
  5429. this.setOutput(true, null);
  5430. this.setColour("#0000ff");
  5431. this.setTooltip(Blockly.Msg.formula_result);
  5432. this.setHelpUrl("");
  5433. }
  5434. };
  5435. Blockly.Python['ai_online_formula_result'] = function (block) {
  5436. let code = `FORMULARESULT`;
  5437. return [code, Blockly.Python.ORDER_ATOMIC];
  5438. };
  5439. // 身份证识别
  5440. Blockly.Blocks['ai_online_ID_card_init'] = {
  5441. init: function () {
  5442. this.appendDummyInput()
  5443. .appendField('身份证识别初始化'); //
  5444. this.appendValueInput("A").setCheck(null).appendField('APP ID');
  5445. this.appendValueInput("B").setCheck(null).appendField('API Secret');
  5446. this.appendValueInput("C").setCheck(null).appendField('API Key');
  5447. this.setPreviousStatement(true, null);
  5448. this.setNextStatement(true, null);
  5449. this.setColour("#0000ff");
  5450. this.setTooltip(Blockly.Msg.handwritten_text_init);
  5451. this.setHelpUrl("");
  5452. }
  5453. };
  5454. Blockly.Python['ai_online_ID_card_init'] = function (block) {
  5455. var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC);
  5456. var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC);
  5457. var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC);
  5458. // TODO: Assemble Python into code variable.
  5459. Blockly.Python.definitions_['v831_import_time'] = `import time`
  5460. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5461. Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib`
  5462. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5463. Blockly.Python.definitions_['v831_import_hmac'] = `import hmac`
  5464. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5465. Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime`
  5466. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime`
  5467. Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse`
  5468. Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time`
  5469. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode`
  5470. Blockly.Python.definitions_.ai_online_formula_init = `class AssembleHeaderException(Exception):
  5471. def __init__(self, msg):
  5472. self.message = msg
  5473. class Url:
  5474. def __init__(this, host, path, schema):
  5475. this.host = host
  5476. this.path = path
  5477. this.schema = schema
  5478. pass
  5479. # calculate sha256 and encode to base64
  5480. def sha256base64(data):
  5481. sha256 = hashlib.sha256()
  5482. sha256.update(data)
  5483. digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8")
  5484. return digest
  5485. def parse_url(requset_url):
  5486. stidx = requset_url.index("://")
  5487. host = requset_url[stidx + 3:]
  5488. schema = requset_url[:stidx + 3]
  5489. edidx = host.index("/")
  5490. if edidx <= 0:
  5491. raise AssembleHeaderException("invalid request url:" + requset_url)
  5492. path = host[edidx:]
  5493. host = host[:edidx]
  5494. u = Url(host, path, schema)
  5495. return u
  5496. # build websocket auth request url
  5497. def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
  5498. u = parse_url(requset_url)
  5499. host = u.host
  5500. path = u.path
  5501. now = datetime.now()
  5502. date = format_date_time(mktime(now.timetuple()))
  5503. #print(date)
  5504. # date = "Thu, 12 Dec 2019 01:57:27 GMT"
  5505. signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path)
  5506. #print(signature_origin)
  5507. signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"),
  5508. digestmod=hashlib.sha256).digest()
  5509. signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8")
  5510. authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (
  5511. api_key, "hmac-sha256", "host date request-line", signature_sha)
  5512. authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8")
  5513. #print(authorization_origin)
  5514. values = {
  5515. "host": host,
  5516. "date": date,
  5517. "authorization": authorization
  5518. }
  5519. return requset_url + "?" + urlencode(values)
  5520. # 控制台获取以下信息
  5521. APPId = ${APPId}
  5522. APISecret = ${APISecret}
  5523. APIKey = ${APIKey}
  5524. `
  5525. var code = '';
  5526. return code;
  5527. };
  5528. Blockly.Blocks['ai_online_ID_card_loading'] = {
  5529. init: function () {
  5530. this.appendDummyInput()
  5531. .appendField('身份证识别加载'); //
  5532. // this.appendDummyInput()
  5533. // .appendField('设置识别语种')
  5534. // .appendField(new Blockly.FieldDropdown([
  5535. // ["en", "en"],
  5536. // ["cn|en", "cn|en"],
  5537. // ]), "language");
  5538. this.appendValueInput("path")
  5539. .setCheck(null)
  5540. .appendField(Blockly.Msg.online_face_init_path); //
  5541. this.setPreviousStatement(true, null);
  5542. this.setNextStatement(true, null);
  5543. this.setColour("#0000ff");
  5544. this.setTooltip(Blockly.Msg.handwritten_text_load);
  5545. this.setHelpUrl("");
  5546. }
  5547. }
  5548. Blockly.Python.ai_online_ID_card_loading = function (block) {
  5549. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5550. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  5551. let code = `with open(${text}, "rb") as f:
  5552. imageBytes = f.read()
  5553. url = 'http://api.xf-yun.com/v1/private/s5ccecfce'
  5554. body = {
  5555. "header": {
  5556. "app_id": APPId,
  5557. "status": 3,
  5558. },
  5559. "parameter": {
  5560. "s5ccecfce": {
  5561. "template_list": "id_card",
  5562. "result": {
  5563. "encoding": "utf8",
  5564. "compress": "raw",
  5565. "format": "json"
  5566. }
  5567. }
  5568. },
  5569. "payload": {
  5570. "s5ccecfce_data_1": {
  5571. "encoding": "jpg",
  5572. "image": str(base64.b64encode(imageBytes), 'UTF-8'),
  5573. "status": 3
  5574. }
  5575. }
  5576. }
  5577. request_Id_card_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
  5578. headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
  5579. #print(request_url)
  5580. Id_card_response = requests.post(request_Id_card_url, data=json.dumps(body), headers=headers)
  5581. IDCardtempResult = json.loads(Id_card_response.content.decode())
  5582. IDCardfinalResult = base64.b64decode(IDCard['payload']['result']['text']).decode()
  5583. IDCardfinalResult = IDCardfinalResult.replace(" ", "").replace("\n", "").replace("\t", "").strip()
  5584. `
  5585. return code
  5586. }
  5587. Blockly.Blocks['ai_online_ID_card_result'] = {
  5588. init: function () {
  5589. this.appendDummyInput()
  5590. .appendField('身份证识别结果'); //
  5591. this.setOutput(true, null);
  5592. this.setColour("#0000ff");
  5593. this.setTooltip(Blockly.Msg.handwritten_text_result);
  5594. this.setHelpUrl("");
  5595. }
  5596. };
  5597. Blockly.Python['ai_online_ID_card_result'] = function (block) {
  5598. let code = `IDCardfinalResult`;
  5599. return [code, Blockly.Python.ORDER_ATOMIC];
  5600. };
  5601. // 情绪识别
  5602. Blockly.Blocks['ai_online_emotion_init'] = {
  5603. init: function () {
  5604. this.appendDummyInput()
  5605. .appendField(Blockly.Msg.emotion_init);
  5606. // this.appendValueInput("path")
  5607. // .setCheck(null).appendField(Blockly.Msg.set_dictionary)
  5608. // .appendField(new Blockly.FieldVariable("emotion_recognize_result"), "varitem");
  5609. // this.appendDummyInput().appendField(Blockly.Msg.dictionary_contain);
  5610. this.setInputsInline(false)
  5611. this.setPreviousStatement(true, null);
  5612. this.setNextStatement(true, null);; //
  5613. this.setColour("#0000ff");
  5614. this.setTooltip(Blockly.Msg.emotion_init);
  5615. this.setHelpUrl("");
  5616. }
  5617. };
  5618. Blockly.Python['ai_online_emotion_init'] = function (block) {
  5619. // let = []
  5620. // let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5621. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  5622. // TODO: Assemble Python into code variable.
  5623. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5624. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5625. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5626. Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true);
  5627. Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path):
  5628. with open(single_image_path, "rb") as fp:
  5629. imgbase64 = base64.b64encode(fp.read())
  5630. return imgbase64.decode()
  5631. url = "https://ai-api.cocorobo.hk/face"
  5632. `
  5633. // ${variable_name} =${text}
  5634. var code = ``;
  5635. return code;
  5636. };
  5637. Blockly.Blocks['ai_online_emotion_loading'] = {
  5638. init: function () {
  5639. this.appendDummyInput()
  5640. .appendField(Blockly.Msg.emotion_load); //
  5641. // this.appendDummyInput()
  5642. // .appendField('设置识别语种')
  5643. // .appendField(new Blockly.FieldDropdown([
  5644. // ["en", "en"],
  5645. // ["cn|en", "cn|en"],
  5646. // ]), "language");
  5647. this.appendValueInput("path")
  5648. .setCheck(null)
  5649. .appendField(Blockly.Msg.online_face_init_path); //
  5650. this.setPreviousStatement(true, null);
  5651. this.setNextStatement(true, null);
  5652. this.setColour("#0000ff");
  5653. this.setTooltip(Blockly.Msg.emotion_load);
  5654. this.setHelpUrl("");
  5655. }
  5656. }
  5657. Blockly.Python.ai_online_emotion_loading = function (block) {
  5658. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5659. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  5660. let code = `imageEmotionURLbase64 = str(get_img_base64str(${text}))
  5661. # print(imageURLbase64)
  5662. data = "{\\"image\\":\\"" + str(imageEmotionURLbase64) + "\\"}"
  5663. try:
  5664. EMOTION_SEND_REQUEST = requests.post(url, data = data , headers = { "Ocp-Apim-Subscription-Key": "6baf787532ef4eec8bc93c88518b8916", "Content-type": "application/json" }, timeout = 10000)
  5665. EMOTION_SEND_REQUEST = json.loads(EMOTION_SEND_REQUEST.content)["data"]["result"]["face_list"][0]
  5666. # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
  5667. except BaseException as e:
  5668. EMOTION_SEND_REQUEST = "no result"
  5669. pass
  5670. `
  5671. return code
  5672. }
  5673. Blockly.Blocks['ai_online_emotion_result'] = {
  5674. init: function () {
  5675. this.appendDummyInput()
  5676. .appendField(Blockly.Msg.emotion_result)
  5677. .appendField(new Blockly.FieldDropdown([
  5678. [Blockly.Msg.emotion_result_age, "age"],
  5679. [Blockly.Msg.emotion_result_emotion, "emotion"],
  5680. [Blockly.Msg.emotion_result_gender, "gender"],
  5681. [Blockly.Msg.emotion_result_expression, "expression"]
  5682. ]), "emotion_type");
  5683. this.setOutput(true, null);
  5684. this.setColour("#0000ff");
  5685. this.setTooltip(Blockly.Msg.emotion_result);
  5686. this.setHelpUrl("");
  5687. }
  5688. };
  5689. Blockly.Python['ai_online_emotion_result'] = function (block) {
  5690. var type = block.getFieldValue('emotion_type');
  5691. let code = ""
  5692. // console.log(type)
  5693. if (type == "age") {
  5694. code = `EMOTION_SEND_REQUEST["age"]`
  5695. } else {
  5696. code = `EMOTION_SEND_REQUEST["${type}"]["type"]`
  5697. }
  5698. return [code, Blockly.Python.ORDER_ATOMIC];
  5699. };
  5700. // 手势识别
  5701. Blockly.Blocks['ai_online_gesture_init'] = {
  5702. init: function () {
  5703. this.appendDummyInput()
  5704. .appendField(Blockly.Msg.gesture_init); //
  5705. this.setPreviousStatement(true, null);
  5706. this.setNextStatement(true, null);
  5707. this.setColour("#0000ff");
  5708. this.setTooltip(Blockly.Msg.gesture_init);
  5709. this.setHelpUrl("");
  5710. }
  5711. };
  5712. Blockly.Python['ai_online_gesture_init'] = function (block) {
  5713. // let = []
  5714. // TODO: Assemble Python into code variable.
  5715. Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image`
  5716. Blockly.Python.definitions_['v831_import_base64'] = `import base64`
  5717. Blockly.Python.definitions_['v831_import_requests'] = `import requests`
  5718. Blockly.Python.definitions_['v831_import_json'] = `import json`
  5719. Blockly.Python.definitions_['emotion_init'] = `
  5720. def getImgData(single_image_path):
  5721. imgGesture = Image.open(single_image_path).convert("RGB")
  5722. imgGesture.save(single_image_path.split(".")[0] + ".png", "png")
  5723. with open(single_image_path.split(".")[0] + ".png", "rb") as fp:
  5724. return fp.read()
  5725. url = "https://ai-api.cocorobo.hk/gesture"
  5726. `
  5727. var code = '';
  5728. return code;
  5729. };
  5730. Blockly.Blocks['ai_online_gesture_loading'] = {
  5731. init: function () {
  5732. this.appendDummyInput()
  5733. .appendField(Blockly.Msg.gesture_load); //
  5734. // this.appendDummyInput()
  5735. // .appendField('设置识别语种')
  5736. // .appendField(new Blockly.FieldDropdown([
  5737. // ["en", "en"],
  5738. // ["cn|en", "cn|en"],
  5739. // ]), "language");
  5740. this.appendValueInput("path")
  5741. .setCheck(null)
  5742. .appendField(Blockly.Msg.online_face_init_path); //
  5743. this.setPreviousStatement(true, null);
  5744. this.setNextStatement(true, null);
  5745. this.setColour("#0000ff");
  5746. this.setTooltip(Blockly.Msg.gesture_load);
  5747. this.setHelpUrl("");
  5748. }
  5749. }
  5750. Blockly.Python.ai_online_gesture_loading = function (block) {
  5751. let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC)
  5752. // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC);
  5753. let code = `try:
  5754. payload={}
  5755. files=[("image",("filename.png", getImgData(${text}),"image/png"))]
  5756. headers = {}
  5757. GESTURE_SEND_REQUEST = requests.post(url, headers=headers, data=payload, files=files, timeout = 10000)
  5758. GESTURE_SEND_REQUEST = json.loads(GESTURE_SEND_REQUEST.content)["data"]["result"][0]["classname"]
  5759. # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content))
  5760. except BaseException as e:
  5761. GESTURE_SEND_REQUEST = "no result"
  5762. pass
  5763. `
  5764. return code
  5765. }
  5766. Blockly.Blocks['ai_online_gesture_result'] = {
  5767. init: function () {
  5768. this.appendDummyInput()
  5769. .appendField(Blockly.Msg.gesture_result);
  5770. this.setOutput(true, null);
  5771. this.setColour("#0000ff");
  5772. this.setTooltip(Blockly.Msg.gesture_result);
  5773. this.setHelpUrl("");
  5774. }
  5775. };
  5776. Blockly.Python['ai_online_gesture_result'] = function (block) {
  5777. let code = `GESTURE_SEND_REQUEST`
  5778. return [code, Blockly.Python.ORDER_ATOMIC];
  5779. };
  5780. Blockly.Blocks['ai_audio_set'] = {
  5781. init: function () {
  5782. this.appendValueInput("Num")
  5783. .setCheck(null)
  5784. .appendField(Blockly.Msg.ai_audio_set_music_vol);
  5785. this.setInputsInline(true);
  5786. this.setPreviousStatement(true, null);
  5787. this.setNextStatement(true, null);
  5788. this.setColour("#603ea0");
  5789. this.setTooltip("");
  5790. this.setHelpUrl("");
  5791. }
  5792. };
  5793. Blockly.Python.ai_audio_set = function (block) {
  5794. var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);
  5795. var _code = "_player.volume(" + _num + ")\n"
  5796. return _code;
  5797. }
  5798. var SPEECH_RECOGNITION_BLOCK_COLOR = "230";
  5799. Blockly.Blocks['speech_recognition_new_setup'] = {
  5800. init: function () {
  5801. this.appendDummyInput()
  5802. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" }));
  5803. this.appendDummyInput()
  5804. .appendField(Blockly.Msg.ai_speech_recognition_setup);
  5805. // this.appendDummyInput()
  5806. // .appendField(Blockly.Msg.ai_speech_recognition_setup_set_sensi)
  5807. // .appendField(new Blockly.FieldDropdown([
  5808. // [Blockly.Msg.ai_speech_recognition_setup_set_sensi_normal, "10000"],
  5809. // [Blockly.Msg.ai_speech_recognition_setup_set_sensi_high, "20000"],
  5810. // [Blockly.Msg.ai_speech_recognition_setup_set_sensi_ehigh, "30000"]
  5811. // ]), "sensitivity");
  5812. this.setPreviousStatement(true, null);
  5813. this.setNextStatement(true, null);
  5814. this.setColour("#ee783a");
  5815. this.setTooltip(Blockly.Msg.speech_recognition_new_setup_TOOLTIP);
  5816. this.setHelpUrl("");
  5817. }
  5818. };
  5819. Blockly.Python['speech_recognition_new_setup'] = function (block) {
  5820. Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
  5821. Blockly.Python.definitions_["v831_import_time"] = `import time`
  5822. Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
  5823. Blockly.Python.addVariable("RecordState", "RecordState = 0", true);
  5824. Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true);
  5825. Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true);
  5826. let code = ""
  5827. return code;
  5828. };
  5829. Blockly.Blocks['speech_recognition_clear'] = {
  5830. init: function () {
  5831. // this.appendDummyInput()
  5832. // .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" }));
  5833. this.appendDummyInput()
  5834. .appendField(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result);
  5835. this.setPreviousStatement(true, null);
  5836. this.setNextStatement(true, null);
  5837. this.setColour("#ee783a");
  5838. this.setTooltip(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result);
  5839. this.setHelpUrl("");
  5840. }
  5841. };
  5842. Blockly.Python['speech_recognition_clear'] = function (block) {
  5843. Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc`
  5844. Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`;
  5845. var code = `mfcc.clear()
  5846. `;
  5847. return code;
  5848. };
  5849. Blockly.Blocks['speech_recognition_record_start_result'] = {
  5850. init: function () {
  5851. this.appendDummyInput()
  5852. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recording_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
  5853. this.appendDummyInput()
  5854. .appendField(Blockly.Msg.ai_speech_recognition_start_recording);
  5855. this.appendDummyInput()
  5856. .appendField(Blockly.Msg.ai_speech_recognition_start_recording_clip_text)
  5857. .appendField(new Blockly.FieldNumber(2, 1, 6, 1), "clip")
  5858. // .appendField(Blockly.Msg.ai_speech_recognition_start_recording_take_note);
  5859. this.appendDummyInput()
  5860. .appendField(Blockly.Msg.image_process_interface)
  5861. .appendField(new Blockly.FieldVariable("recordCanvas"), "varitem");
  5862. this.setPreviousStatement(true, null);
  5863. this.setNextStatement(true, null);
  5864. this.setColour("#ee783a");
  5865. this.setTooltip(Blockly.Msg.ai_speech_recognition_start_recording);
  5866. this.setHelpUrl("");
  5867. }
  5868. };
  5869. Blockly.Python['speech_recognition_record_start_result'] = function (block) {
  5870. var number_take = block.getFieldValue('clip');
  5871. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  5872. Blockly.Python.definitions_["v831_mfcc_clear"] = `mfcc.clear()
  5873. `
  5874. Blockly.Python.addVariable('number_take', `number_take = ${number_take}`, true)
  5875. let idenSuccess = "录制成功";
  5876. let speek = "说第";
  5877. let SpeechFragment = "语音片段";
  5878. if (localStorage.getItem('handPyLanguage') == "zh-hant") {
  5879. idenSuccess = "錄製成功";
  5880. speek = "說第 ";
  5881. SpeechFragment = "語音片段";
  5882. } else if (localStorage.getItem('handPyLanguage') == "en") {
  5883. idenSuccess = "Recorded successfully";
  5884. speek = "Speek ";
  5885. SpeechFragment = "Speech fragment";
  5886. }
  5887. var code = `if RecordState == 0:
  5888. mfcc.recording(recordFrequency)
  5889. recordFrequency = recordFrequency + 1
  5890. time.sleep(1)
  5891. RecordState = 1
  5892. if RecordState == 1:
  5893. recordData = mfcc.state()
  5894. if recordData == mfcc._mfcc_result:
  5895. ${variable_name}.draw_string(0,80,"${idenSuccess}", scale = 2, color = (0,204,204) , thickness = 1)
  5896. time.sleep(1)
  5897. if recordFrequency < number_take:
  5898. RecordState = 0
  5899. else:
  5900. ${variable_name}.draw_string(0,80, "${speek} "+str(recordFrequency)+" ${SpeechFragment}", scale = 2, color = (0,204,204) , thickness = 1)
  5901. `
  5902. return code
  5903. };
  5904. Blockly.Blocks['speech_recognition_new_start_recognition'] = {
  5905. init: function () {
  5906. this.appendDummyInput()
  5907. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
  5908. this.appendDummyInput()
  5909. .appendField(Blockly.Msg.ai_speech_recognition_start_recognizing);
  5910. this.setPreviousStatement(true, null);
  5911. this.setNextStatement(true, null);
  5912. this.setColour("#ee783a");
  5913. this.setTooltip(Blockly.Msg.speech_recognition_new_start_recognition_TOOLTIP);
  5914. this.setHelpUrl("");
  5915. }
  5916. };
  5917. Blockly.Python['speech_recognition_new_start_recognition'] = function (block) {
  5918. var code = `if RecordState == 0:
  5919. mfcc.recognize()
  5920. recordResultData = None
  5921. time.sleep(1)
  5922. RecordState = 1
  5923. `
  5924. return code
  5925. };
  5926. Blockly.Blocks['speech_recognition_new_recognition_get_any_result'] = {
  5927. init: function () {
  5928. this.appendDummyInput()
  5929. .appendField(Blockly.Msg.ai_speech_recognition_any_result_text);
  5930. this.appendStatementInput("NAME")
  5931. .setCheck(null)
  5932. .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  5933. this.setPreviousStatement(true, null);
  5934. this.setNextStatement(true, null);
  5935. this.setColour("#ee783a");
  5936. this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_any_result_TOOLTIP);
  5937. this.setHelpUrl("");
  5938. }
  5939. };
  5940. Blockly.Python['speech_recognition_new_recognition_get_any_result'] = function (block) {
  5941. var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  5942. // TODO: Assemble Python into code variable.
  5943. var code = `if RecordState == 1:
  5944. recordData = mfcc.state()
  5945. if recordData == mfcc._mfcc_result:
  5946. recordResultData = mfcc.result()
  5947. time.sleep(1)
  5948. RecordState = 0
  5949. ${statements_name}
  5950. `;
  5951. return code;
  5952. };
  5953. Blockly.Blocks['speech_recognition_new_recognition_get_result'] = {
  5954. init: function () {
  5955. this.appendDummyInput()
  5956. .appendField(Blockly.Msg.ai_speech_recognition_get_result)
  5957. .appendField(new Blockly.FieldNumber(1, 1, 6, 1), "index")
  5958. .appendField(Blockly.Msg.ai_speech_recognition_get_result_after);
  5959. this.setOutput(true, null);
  5960. this.setColour("#ee783a");
  5961. this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_result_TOOLTIP);
  5962. this.setHelpUrl("");
  5963. }
  5964. };
  5965. Blockly.Python['speech_recognition_new_recognition_get_result'] = function (block) {
  5966. var number_index = block.getFieldValue('index');
  5967. // TODO: Assemble Python into code variable.
  5968. var code = `recordResultData == ${number_index - 1}`;
  5969. // TODO: Change ORDER_NONE to the correct strength.
  5970. return [code, Blockly.Python.ORDER_NONE];
  5971. };
  5972. /*
  5973. _ ___ ____ _
  5974. / \ |_ _| / ___| _ __ ___ __ _| | _____ _ __
  5975. / _ \ | | \___ \| '_ \ / _ \/ _` | |/ / _ \ '__|
  5976. / ___ \ _ | | _ ___) | |_) | __/ (_| | < __/ |
  5977. /_/ \_(_)___(_) |____/| .__/ \___|\__,_|_|\_\___|_|
  5978. |_|
  5979. */
  5980. Blockly.Blocks['ai_audio_init_speaker'] = {
  5981. init: function () {
  5982. this.appendDummyInput()
  5983. .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  5984. this.appendDummyInput()
  5985. .appendField(Blockly.Msg.ai_audio_init);
  5986. this.setColour("#5f7fc1");
  5987. this.setTooltip(Blockly.Msg.ai_audio_init_speaker_TOOLTIP);
  5988. this.setHelpUrl("");
  5989. this.setPreviousStatement(true);
  5990. this.setNextStatement(true);
  5991. }
  5992. };
  5993. Blockly.Python.ai_audio_init_speaker = function (block) {
  5994. Blockly.Python.definitions_.import_Maix = "from Maix import I2S, GPIO";
  5995. Blockly.Python.definitions_.import_fpioa_manager = "from fpioa_manager import *";
  5996. Blockly.Python.definitions_.import_audio = "import audio";
  5997. var _code = "";
  5998. return _code;
  5999. }
  6000. Blockly.Blocks['ai_audio_play_song_speaker'] = {
  6001. init: function () {
  6002. this.appendDummyInput()
  6003. .appendField(Blockly.Msg.ai_audio_play_music_file);
  6004. // this.appendDummyInput()
  6005. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  6006. // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
  6007. this.appendValueInput("volume")
  6008. .setCheck(null)
  6009. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
  6010. this.appendValueInput("path")
  6011. .setCheck(null)
  6012. .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  6013. this.setPreviousStatement(true, null);
  6014. this.setNextStatement(true, null);
  6015. this.setColour("#5f7fc1");
  6016. this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_TOOLTIP);
  6017. this.setHelpUrl("");
  6018. }
  6019. };
  6020. Blockly.Python['ai_audio_play_song_speaker'] = function (block) {
  6021. // var number_play_vol = block.getFieldValue('play_vol');
  6022. var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  6023. var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6024. var _in = "" +
  6025. "_audio_rx = I2S(I2S.DEVICE_1)\n" +
  6026. "\n" +
  6027. "def _speaker_play_song(path, volume):\n" +
  6028. " global _audio_play_state,_player\n" +
  6029. " _player = audio.Audio(path = path)\n" +
  6030. " _player.volume(volume)\n" +
  6031. " try:\n" +
  6032. " _wav_info = _player.play_process(_audio_rx)\n" +
  6033. " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
  6034. " _audio_rx.set_sample_rate(_wav_info[1])\n" +
  6035. " _audio_play_state = 0\n" +
  6036. "\n" +
  6037. " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
  6038. " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
  6039. " fm.register(33,fm.fpioa.I2S1_WS)\n" +
  6040. "\n" +
  6041. " while True:\n" +
  6042. " _audio_play_state = _player.play()\n" +
  6043. " if (_audio_play_state) == True:\n" +
  6044. " print(\"Playing.\")\n" +
  6045. " elif (_audio_play_state) == False:\n" +
  6046. " print(\"Done.\")\n" +
  6047. " break\n" +
  6048. "\n" +
  6049. " except:\n" +
  6050. " pass\n" +
  6051. "\n";
  6052. // Blockly.Python.definitions_.import_audio = _in;
  6053. Blockly.Python.addVariable('_audio_play_state', _in, true);
  6054. // Blockly.Python.addSetup("ai_audio_read", _in);
  6055. var _code = "_speaker_play_song(path=" + value_name + ", volume=" + number_play_vol + ")\n";
  6056. return _code;
  6057. };
  6058. Blockly.Blocks['ai_audio_play_finish_speaker'] = {
  6059. init: function () {
  6060. this.appendDummyInput()
  6061. .appendField(Blockly.Msg.ai_audio_end_play);
  6062. this.setPreviousStatement(true, null);
  6063. this.setNextStatement(true, null);
  6064. this.setColour("#5f7fc1");
  6065. this.setTooltip(Blockly.Msg.ai_audio_play_finish_speaker_TOOLTIP);
  6066. this.setHelpUrl("");
  6067. }
  6068. };
  6069. Blockly.Python['ai_audio_play_finish_speaker'] = function (block) {
  6070. // TODO: Assemble Python into code variable.
  6071. var code = '_player.finish()\n';
  6072. return code;
  6073. };
  6074. Blockly.Blocks['ai_audio_set_speaker'] = {
  6075. init: function () {
  6076. this.appendValueInput("Num")
  6077. .setCheck(null)
  6078. .appendField(Blockly.Msg.ai_audio_set_music_vol);
  6079. this.setInputsInline(true);
  6080. this.setPreviousStatement(true, null);
  6081. this.setNextStatement(true, null);
  6082. this.setColour("#5f7fc1");
  6083. this.setTooltip(Blockly.Msg.ai_audio_set_speaker_TOOLTIP);
  6084. this.setHelpUrl("");
  6085. }
  6086. };
  6087. Blockly.Python.ai_audio_set_speaker = function (block) {
  6088. var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);
  6089. var _code = "_player.volume(" + _num + ")\n"
  6090. return _code;
  6091. }
  6092. Blockly.Blocks['ai_audio_files_list'] = {
  6093. init: function () {
  6094. this.appendDummyInput()
  6095. .appendField(Blockly.Msg.ai_audio_files_list);
  6096. this.appendValueInput("path")
  6097. .setCheck(null)
  6098. .appendField(Blockly.Msg.ai_audio_files_list_set_file_path);
  6099. this.setOutput(true, null);
  6100. this.setColour("#5f7fc1");
  6101. this.setTooltip(Blockly.Msg.ai_audio_files_list_TOOLTIP);
  6102. this.setHelpUrl("");
  6103. }
  6104. };
  6105. Blockly.Python.ai_audio_files_list = function (block) {
  6106. var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6107. Blockly.Python.definitions_['v831_import_os'] = `import os`
  6108. Blockly.Python.definitions_.import_ai_audio_files_list = '' +
  6109. 'def getRawFileList(path):\n' +
  6110. ' files = []\n' +
  6111. ' for f in os.listdir(path):\n' +
  6112. ' if (not f.endswith("~") or not f == "") and f.split(".")[1] == "wav":\n' +
  6113. ' files.append(path + "/" + f)\n' +
  6114. ' return files\n' +
  6115. '\n';
  6116. var code = 'getRawFileList(' + value_name + ')';
  6117. return [code, Blockly.Python.ORDER_NONE];
  6118. };
  6119. Blockly.Blocks['ai_audio_play_song_list_loop_speaker'] = {
  6120. init: function () {
  6121. this.appendDummyInput()
  6122. .appendField(Blockly.Msg.ai_audio_play_music_file_list_loop);
  6123. // this.appendDummyInput()
  6124. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  6125. // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
  6126. this.appendValueInput("volume")
  6127. .setCheck(null)
  6128. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
  6129. // this.appendValueInput("path")
  6130. // .setCheck(null)
  6131. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  6132. this.appendValueInput("my_list")
  6133. .setCheck(null)
  6134. .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list);
  6135. this.appendValueInput("firstIndex")
  6136. .setCheck(null)
  6137. .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index);
  6138. this.setPreviousStatement(true, null);
  6139. this.setNextStatement(true, null);
  6140. this.setColour("#5f7fc1");
  6141. this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_list_loop_TOOLTIP);
  6142. this.setHelpUrl("");
  6143. }
  6144. };
  6145. Blockly.Python['ai_audio_play_song_list_loop_speaker'] = function (block) {
  6146. // var number_play_vol = block.getFieldValue('play_vol');
  6147. var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  6148. // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6149. var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC);
  6150. var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC);
  6151. var _in = "" +
  6152. "_audio_rx = I2S(I2S.DEVICE_1)\n" +
  6153. "direction = 0\n" +
  6154. "firstIndex = " + firstIndex + "\n" +
  6155. "\n" +
  6156. "# 上一首\n" +
  6157. "def previous_song(index,my_list):\n" +
  6158. " global direction\n" +
  6159. " index = index - 1\n" +
  6160. " direction = 1\n" +
  6161. " if index == -1:\n" +
  6162. " index = len(my_list) - 1\n" +
  6163. " return index\n" +
  6164. "\n" +
  6165. "# 切换上一首\n" +
  6166. "def change_previous_song(index):\n" +
  6167. " global _audio_play_state,direction,firstIndex,_player\n" +
  6168. " _player.finish()\n" +
  6169. " _audio_play_state = 0\n" +
  6170. " firstIndex = index\n" +
  6171. " direction = 1\n" +
  6172. "\n" +
  6173. "# 下一首\n" +
  6174. "def next_song(index,my_list):\n" +
  6175. " global direction\n" +
  6176. " index = index + 1\n" +
  6177. " direction = 2\n" +
  6178. " if index == len(my_list):\n" +
  6179. " index = 0\n" +
  6180. " return index\n" +
  6181. "\n" +
  6182. "# 切换下一首\n" +
  6183. "def change_next_song(index):\n" +
  6184. " global _audio_play_state,direction,firstIndex,_player\n" +
  6185. " _player.finish()\n" +
  6186. " _audio_play_state = 0\n" +
  6187. " firstIndex = index\n" +
  6188. " direction = 2\n" +
  6189. "\n" +
  6190. "def _speaker_play_song_list_loop(volume, my_list):\n" +
  6191. " global _audio_play_state,_player,firstIndex,play_again,direction\n" +
  6192. " _player = audio.Audio(path = my_list[firstIndex])\n" +
  6193. " _player.volume(volume)\n" +
  6194. " try:\n" +
  6195. // " firstIndex = index\n" +
  6196. " _wav_info = _player.play_process(_audio_rx)\n" +
  6197. " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
  6198. " _audio_rx.set_sample_rate(_wav_info[1])\n" +
  6199. " _audio_play_state = 0\n" +
  6200. "\n" +
  6201. " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
  6202. " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
  6203. " fm.register(33,fm.fpioa.I2S1_WS)\n" +
  6204. "\n" +
  6205. " button_a_state = False\n" +
  6206. " button_b_state = False\n" +
  6207. " while True:\n" +
  6208. " _audio_play_state = _player.play()\n" +
  6209. " if (_audio_play_state) == True:\n" +
  6210. " #print(\"Playing.\")\n" +
  6211. " if (_gp_side_a.value() == 1) and button_a_state == False:\n" +
  6212. " index = previous_song(firstIndex,my_list)\n" +
  6213. " button_a_state = True\n" +
  6214. " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" +
  6215. " button_a_state = False\n" +
  6216. " change_previous_song(index)\n" +
  6217. " break\n" +
  6218. " if (_gp_side_b.value() == 1) and button_b_state == False:\n" +
  6219. " index = next_song(firstIndex,my_list)\n" +
  6220. " button_b_state = True\n" +
  6221. " elif (_gp_side_b.value() == 0) and button_b_state == True:\n" +
  6222. " button_b_state = False\n" +
  6223. " change_next_song(index)\n" +
  6224. " break\n" +
  6225. "\n" +
  6226. " elif (_audio_play_state) == False:\n" +
  6227. " #print(\"Done.\")\n" +
  6228. " index = firstIndex + 1\n" +
  6229. " if index == len(my_list):\n" +
  6230. " index = 0\n" +
  6231. " firstIndex = index\n" +
  6232. " break\n" +
  6233. "\n" +
  6234. " except:\n" +
  6235. " play_again = True\n" +
  6236. " if direction == 0:\n" +
  6237. " direction = 3\n" +
  6238. " return\n" +
  6239. "\n";
  6240. // Blockly.Python.definitions_.import_audio = _in;
  6241. Blockly.Python.addVariable('_audio_play_list_loop_state', _in, true);
  6242. Blockly.Python.definitions_['import_define_x_ai_button'] = '' +
  6243. 'from fpioa_manager import *\n' +
  6244. 'from Maix import FPIOA, GPIO\n' +
  6245. '\n' +
  6246. '_gp_side_buttons = [9, 10, 11]\n' +
  6247. '\n' +
  6248. 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' +
  6249. 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' +
  6250. 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' +
  6251. '\n' +
  6252. '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' +
  6253. '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' +
  6254. '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' +
  6255. '\n';
  6256. // Blockly.Python.addSetup("ai_audio_read", _in);
  6257. var _code = "_speaker_play_song_list_loop(volume=" + number_play_vol + ", my_list=" + my_list + ")\n";
  6258. return _code;
  6259. };
  6260. Blockly.Blocks['ai_audio_play_song_list_random_speaker'] = {
  6261. init: function () {
  6262. this.appendDummyInput()
  6263. .appendField(Blockly.Msg.ai_audio_play_music_file_list_random);
  6264. // this.appendDummyInput()
  6265. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol)
  6266. // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
  6267. this.appendValueInput("volume")
  6268. .setCheck(null)
  6269. .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
  6270. // this.appendValueInput("path")
  6271. // .setCheck(null)
  6272. // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
  6273. this.appendValueInput("my_list")
  6274. .setCheck(null)
  6275. .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list);
  6276. this.appendValueInput("firstIndex")
  6277. .setCheck(null)
  6278. .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index);
  6279. this.setPreviousStatement(true, null);
  6280. this.setNextStatement(true, null);
  6281. this.setColour("#5f7fc1");
  6282. this.setTooltip(Blockly.Msg.ai_audio_play_music_file_list_random_TOOLTIP);
  6283. this.setHelpUrl("");
  6284. }
  6285. };
  6286. Blockly.Python['ai_audio_play_song_list_random_speaker'] = function (block) {
  6287. // var number_play_vol = block.getFieldValue('play_vol');
  6288. var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  6289. // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6290. var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC);
  6291. var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC);
  6292. Blockly.Python.definitions_['v831_import_time'] = `import time`
  6293. Blockly.Python.definitions_['v831_import_random'] = `import random`
  6294. var _in = "" +
  6295. "random.seed(time.ticks_cpu())\n" +
  6296. "\n" +
  6297. "_audio_rx = I2S(I2S.DEVICE_1)\n" +
  6298. "firstIndex = " + firstIndex + "\n" +
  6299. "\n" +
  6300. "# 随机一首\n" +
  6301. "def random_song(index,my_list):\n" +
  6302. " index = random.randrange(0, len(my_list), 1)\n" +
  6303. " return index\n" +
  6304. "\n" +
  6305. "# 切换歌曲\n" +
  6306. "def change_random_song(index):\n" +
  6307. " global _audio_play_state,firstIndex,_player\n" +
  6308. " _player.finish()\n" +
  6309. " _audio_play_state = 0\n" +
  6310. " firstIndex = index\n" +
  6311. "\n" +
  6312. "def _speaker_play_song_list_random(volume, my_list):\n" +
  6313. " global _audio_play_state,_player,firstIndex,play_again\n" +
  6314. " _player = audio.Audio(path = my_list[firstIndex])\n" +
  6315. " _player.volume(volume)\n" +
  6316. " try:\n" +
  6317. // " firstIndex = index\n" +
  6318. " _wav_info = _player.play_process(_audio_rx)\n" +
  6319. " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" +
  6320. " _audio_rx.set_sample_rate(_wav_info[1])\n" +
  6321. " _audio_play_state = 0\n" +
  6322. "\n" +
  6323. " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" +
  6324. " fm.register(35,fm.fpioa.I2S1_SCLK)\n" +
  6325. " fm.register(33,fm.fpioa.I2S1_WS)\n" +
  6326. "\n" +
  6327. " button_a_state = False\n" +
  6328. " while True:\n" +
  6329. " _audio_play_state = _player.play()\n" +
  6330. " if (_audio_play_state) == True:\n" +
  6331. " #print(\"Playing.\")\n" +
  6332. " if (_gp_side_a.value() == 1) and button_a_state == False:\n" +
  6333. " index = random_song(firstIndex,my_list)\n" +
  6334. " button_a_state = True\n" +
  6335. " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" +
  6336. " button_a_state = False\n" +
  6337. " change_random_song(index)\n" +
  6338. " break\n" +
  6339. "\n" +
  6340. " elif (_audio_play_state) == False:\n" +
  6341. " #print(\"Done.\")\n" +
  6342. " index = random_song(firstIndex,my_list)\n" +
  6343. " firstIndex = index\n" +
  6344. " break\n" +
  6345. "\n" +
  6346. " except:\n" +
  6347. " play_again = True\n" +
  6348. " return\n" +
  6349. "\n";
  6350. // Blockly.Python.definitions_.import_audio = _in;
  6351. Blockly.Python.addVariable('_audio_play_list_random_state', _in, true);
  6352. Blockly.Python.definitions_['import_define_x_ai_button'] = '' +
  6353. 'from fpioa_manager import *\n' +
  6354. 'from Maix import FPIOA, GPIO\n' +
  6355. '\n' +
  6356. '_gp_side_buttons = [9, 10, 11]\n' +
  6357. '\n' +
  6358. 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' +
  6359. 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' +
  6360. 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' +
  6361. '\n' +
  6362. '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' +
  6363. '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' +
  6364. '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' +
  6365. '\n';
  6366. // Blockly.Python.addSetup("ai_audio_read", _in);
  6367. var _code = "_speaker_play_song_list_random(volume=" + number_play_vol + ", my_list=" + my_list + ")\n";
  6368. return _code;
  6369. };
  6370. /*
  6371. _ ___ __ ___ _
  6372. / \ |_ _| \ \ / (_) __| | ___ ___
  6373. / _ \ | | \ \ / /| |/ _` |/ _ \/ _ \
  6374. / ___ \ | | \ V / | | (_| | __/ (_) |
  6375. /_/ \_\___| \_/ |_|\__,_|\___|\___/
  6376. */
  6377. Blockly.Blocks['ai_video_record_setup'] = {
  6378. init: function () {
  6379. this.appendDummyInput()
  6380. .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  6381. this.appendDummyInput()
  6382. .appendField(Blockly.Msg.ai_video_start_recording);
  6383. this.appendValueInput("save_path")
  6384. .setCheck(null)
  6385. .appendField(Blockly.Msg.ai_video_start_recording_file_path);
  6386. this.appendValueInput("w")
  6387. .setCheck(null)
  6388. .appendField(Blockly.Msg.ai_video_start_recording_width);
  6389. this.appendValueInput("h")
  6390. .setCheck(null)
  6391. .appendField(Blockly.Msg.ai_video_start_recording_height);
  6392. this.setPreviousStatement(true, null);
  6393. this.setNextStatement(true, null);
  6394. this.setColour("#60c1bb");
  6395. this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP);
  6396. this.setHelpUrl("");
  6397. }
  6398. };
  6399. Blockly.Python['ai_video_record_setup'] = function (block) {
  6400. var value_save_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  6401. var value_w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
  6402. var value_h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
  6403. Blockly.Python.definitions_.import_video = "import video";
  6404. Blockly.Python.definitions_.import_Maix = "from Maix import GPIO";
  6405. Blockly.Python.addVariable('record_vid', 'record_vid = None', true);
  6406. // TODO: Assemble Python into code variable.
  6407. var code = "_record_vid = video.open(" + value_save_path + ", record=1, width=" + value_w + ", height=" + value_h + ", interval=20000, quality=80)\n";
  6408. return code;
  6409. };
  6410. Blockly.Blocks['ai_video_get'] = {
  6411. init: function () {
  6412. this.appendDummyInput()
  6413. .appendField(Blockly.Msg.ai_video_to_canvas)
  6414. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  6415. .appendField(Blockly.Msg.ai_video_record);
  6416. this.setInputsInline(false);
  6417. this.setPreviousStatement(true, null);
  6418. this.setNextStatement(true, null);
  6419. this.setColour("#60c1bb");
  6420. this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP);
  6421. this.setHelpUrl("");
  6422. }
  6423. };
  6424. Blockly.Python.ai_video_get = function (block) {
  6425. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  6426. var _code = "_record_vid.record(" + variable_name + ")\n"
  6427. return _code;
  6428. }
  6429. Blockly.Blocks['ai_video_stop'] = {
  6430. init: function () {
  6431. this.appendDummyInput()
  6432. .appendField(Blockly.Msg.ai_video_stop_recording);
  6433. this.setPreviousStatement(true);
  6434. this.setNextStatement(true);
  6435. this.setColour("#60c1bb");
  6436. this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP);
  6437. this.setHelpUrl("");
  6438. }
  6439. };
  6440. Blockly.Python.ai_video_stop = function (block) {
  6441. var _code = "_record_vid.record_finish()\n"
  6442. return _code;
  6443. }
  6444. Blockly.Blocks['ai_video_set_init'] = {
  6445. init: function () {
  6446. this.appendDummyInput()
  6447. .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  6448. this.appendDummyInput()
  6449. .appendField(Blockly.Msg.ai_video_set_play_init);
  6450. this.setPreviousStatement(true, null);
  6451. this.setNextStatement(true, null);
  6452. this.setColour("#4d9994");
  6453. this.setTooltip(Blockly.Msg.ai_video_set_play_init);
  6454. this.setHelpUrl("");
  6455. }
  6456. }
  6457. Blockly.Python['ai_video_set_init'] = function (block) {
  6458. Blockly.Python.definitions_['v831_import_os'] = `import os`
  6459. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  6460. Blockly.Python.definitions_['v831_import_av'] = `import av`
  6461. Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display`
  6462. Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera`
  6463. Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image`
  6464. // Blockly.Python.addVariable("VIDEOPLAY",`VIDEOPLAY = False`,true)
  6465. let code = ``
  6466. return code;
  6467. }
  6468. Blockly.Blocks['ai_video_set'] = {
  6469. init: function () {
  6470. // this.appendDummyInput()
  6471. // .appendField(Blockly.Msg.ai_video_play_video);
  6472. this.appendValueInput("path")
  6473. .setCheck(null)
  6474. .appendField(Blockly.Msg.ai_video_play_video_file_path);
  6475. // this.appendDummyInput()
  6476. // .appendField(Blockly.Msg.ai_video_play_video_2);
  6477. this.setPreviousStatement(true, null);
  6478. this.setNextStatement(true, null);
  6479. this.setColour("#4d9994");
  6480. this.setTooltip(Blockly.Msg.ai_video_play_video);
  6481. this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  6482. }
  6483. };
  6484. Blockly.Python['ai_video_set'] = function (block) {
  6485. // Blockly.Python.definitions_.import_Maix = "from maix import display, camera, image";
  6486. var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6487. var code = `pathToVideo = ${value_path}
  6488. containerVideo = av.open(pathToVideo)
  6489. streamVideo = containerVideo.streams.video[0]
  6490. `
  6491. return code;
  6492. };
  6493. Blockly.Blocks['ai_video_set_stats'] = {
  6494. init: function () {
  6495. this.appendDummyInput()
  6496. .appendField(Blockly.Msg.ai_video_set_play_stats);
  6497. // this.appendDummyInput()
  6498. // .appendField(Blockly.Msg.ai_video_play_video_2);
  6499. this.setOutput(true, null)
  6500. this.setColour("#4d9994");
  6501. this.setTooltip(Blockly.Msg.ai_video_set_play_stats);
  6502. this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  6503. }
  6504. };
  6505. Blockly.Python['ai_video_set_stats'] = function (block) {
  6506. var code = `containerVideo.decode(video=0)`
  6507. return [code, Blockly.Python.ORDER_NONE];
  6508. };
  6509. Blockly.Blocks['ai_video_set_play'] = {
  6510. init: function () {
  6511. this.appendDummyInput().appendField(Blockly.Msg.ai_models_from)
  6512. .appendField(new Blockly.FieldVariable("i"), "varitem")
  6513. .appendField(Blockly.Msg.ai_video_set_play);
  6514. this.setPreviousStatement(true, null);
  6515. this.setNextStatement(true, null);
  6516. this.setColour("#4d9994");
  6517. this.setTooltip(Blockly.Msg.ai_video_set_play);
  6518. this.setHelpUrl("");
  6519. }
  6520. }
  6521. Blockly.Python['ai_video_set_play'] = function (block) {
  6522. var value = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  6523. let code = `if "Video" in repr(${value}):
  6524. VideoImg = image.load(bytes(${value}.to_rgb().planes[0]), (streamVideo.width, streamVideo.height))
  6525. display.show(VideoImg)
  6526. `
  6527. return code;
  6528. }
  6529. Blockly.Blocks['ai_video_stop_play'] = {
  6530. init: function () {
  6531. this.appendDummyInput()
  6532. .appendField(Blockly.Msg.ai_video_stop_video_playing);
  6533. this.setPreviousStatement(true, null);
  6534. this.setNextStatement(true, null);
  6535. this.setColour("#4d9994");
  6536. this.setTooltip(Blockly.Msg.ai_video_stop_play_TOOLTIP);
  6537. this.setHelpUrl("");
  6538. }
  6539. };
  6540. Blockly.Python['ai_video_stop_play'] = function (block) {
  6541. // TODO: Assemble Python into code variable.
  6542. var code = `break
  6543. `;
  6544. return code;
  6545. };
  6546. Blockly.Blocks['ai_video_record_init'] = {
  6547. init: function () {
  6548. this.appendDummyInput()
  6549. .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  6550. this.appendDummyInput()
  6551. .appendField(Blockly.Msg.ai_video_start_recording);
  6552. this.appendValueInput("save_path")
  6553. .setCheck(null)
  6554. .appendField(Blockly.Msg.ai_video_start_recording_file_path);
  6555. this.appendValueInput("w")
  6556. .setCheck(null)
  6557. .appendField(Blockly.Msg.ai_video_start_recording_width);
  6558. this.appendValueInput("h")
  6559. .setCheck(null)
  6560. .appendField(Blockly.Msg.ai_video_start_recording_height);
  6561. this.setPreviousStatement(true, null);
  6562. this.setNextStatement(true, null);
  6563. this.setColour("#4d9994");
  6564. this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP);
  6565. // this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  6566. }
  6567. };
  6568. Blockly.Python['ai_video_record_init'] = function (block) {
  6569. Blockly.Python.definitions_['v831_import_os'] = `import os`
  6570. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  6571. Blockly.Python.definitions_['v831_import_av'] = `import av`
  6572. Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display`
  6573. Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera`
  6574. Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image`
  6575. var value_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  6576. var w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
  6577. var h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
  6578. var code = `path_to_video = ${value_path}
  6579. fps = 10
  6580. container = av.open(path_to_video, mode='w')
  6581. stream = container.add_stream('h264', rate=fps) # h264 or mpeg4
  6582. stream.width = ${w}
  6583. stream.height = ${h}
  6584. stream.pix_fmt = 'yuv420p'
  6585. `
  6586. return code;
  6587. };
  6588. Blockly.Blocks['ai_video_record_get'] = {
  6589. init: function () {
  6590. this.appendDummyInput()
  6591. .appendField(Blockly.Msg.ai_video_to_canvas)
  6592. .appendField(new Blockly.FieldVariable("canvas"), "varitem")
  6593. .appendField(Blockly.Msg.ai_video_record);
  6594. this.setInputsInline(false);
  6595. this.setPreviousStatement(true, null);
  6596. this.setNextStatement(true, null);
  6597. this.setColour("#4d9994");
  6598. this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP);
  6599. this.setHelpUrl("");
  6600. }
  6601. };
  6602. Blockly.Python.ai_video_record_get = function (block) {
  6603. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  6604. var _code = `frame = av.VideoFrame(${variable_name}.width, ${variable_name}.height, 'rgb24')
  6605. frame.planes[0].update(${variable_name}.tobytes())
  6606. for packet in stream.encode(frame):
  6607. container.mux(packet)
  6608. `
  6609. return _code;
  6610. }
  6611. Blockly.Blocks['ai_video_record_stop'] = {
  6612. init: function () {
  6613. this.appendDummyInput()
  6614. .appendField(Blockly.Msg.ai_video_stop_recording);
  6615. this.setPreviousStatement(true);
  6616. this.setNextStatement(true);
  6617. this.setColour("#4d9994");
  6618. this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP);
  6619. this.setHelpUrl("");
  6620. }
  6621. };
  6622. Blockly.Python.ai_video_record_stop = function (block) {
  6623. var _code = `
  6624. #Flush stream
  6625. for packet in stream.encode():
  6626. container.mux(packet)
  6627. #Close the file
  6628. container.close()
  6629. `
  6630. return _code;
  6631. }
  6632. // 视频录制
  6633. Blockly.Blocks['ai_video_record'] = {
  6634. init: function () {
  6635. this.appendDummyInput()
  6636. .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  6637. this.appendDummyInput()
  6638. .appendField(Blockly.Msg.ai_video_recording_and_save);
  6639. this.appendValueInput("path")
  6640. .setCheck(null)
  6641. .appendField(Blockly.Msg.VIDEO_SET_P);
  6642. this.appendDummyInput()
  6643. .appendField(Blockly.Msg.ai_video_play_video_2);
  6644. this.setPreviousStatement(true, null);
  6645. this.setNextStatement(true, null);
  6646. this.setColour("#4d9994");
  6647. this.setTooltip(Blockly.Msg.ai_video_set_TOOLTIP);
  6648. this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi");
  6649. }
  6650. };
  6651. Blockly.Python['ai_video_record'] = function (block) {
  6652. var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  6653. Blockly.Python.definitions_['v831_import_time'] = `import time`
  6654. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio`
  6655. Blockly.Python.definitions_['v831_import_av'] = `import av`
  6656. Blockly.Python.definitions_['v831_import_os'] = `import os`
  6657. Blockly.Python.definitions_['v831_import_from_maix_display'] = `import display`
  6658. Blockly.Python.definitions_['v831_import_from_maix_camera'] = `import camera`
  6659. Blockly.Python.definitions_['v831_import_from_maix_image'] = `import image`
  6660. var code = `path_to_video = ${value_path};
  6661. duration, fps = 4, 10
  6662. total_frames = duration * fps
  6663. container = av.open(path_to_video, mode='w')
  6664. stream = container.add_stream('h264', rate=fps) # h264 or mpeg4
  6665. stream.width = 320
  6666. stream.height = 240
  6667. stream.pix_fmt = 'yuv420p'
  6668. for frame_i in range(total_frames):
  6669. img = image.new(size=(stream.width, stream.height), mode='RGB')
  6670. img.draw_string(0, 0, str(time.time()), 2)
  6671. frame = av.VideoFrame(img.width, img.height, 'rgb24')
  6672. frame.planes[0].update(img.tobytes())
  6673. for packet in stream.encode(frame):
  6674. container.mux(packet)
  6675. #Flush stream
  6676. for packet in stream.encode():
  6677. container.mux(packet)
  6678. #Close the file
  6679. container.close()
  6680. #Play the video
  6681. container = av.open(path_to_video)
  6682. stream = container.streams.video[0]
  6683. for frame in container.decode(video=0):
  6684. if 'Video' in repr(frame):
  6685. img = image.load(bytes(frame.to_rgb().planes[0]), (stream.width, stream.height))
  6686. display.show(img)`
  6687. return code;
  6688. };
  6689. Blockly.Blocks['ai_video_status'] = {
  6690. init: function () {
  6691. this.appendDummyInput()
  6692. .appendField(Blockly.Msg.ai_video_get_video_playing_status);
  6693. this.setOutput(true, null);
  6694. this.setColour("#4d9994");
  6695. this.setTooltip(Blockly.Msg.ai_video_status_TOOLTIP);
  6696. this.setHelpUrl("");
  6697. }
  6698. };
  6699. Blockly.Python.ai_video_status = function (block) {
  6700. var code = "_video_play.play()";
  6701. return [code, Blockly.Python.ORDER_NONE];
  6702. }
  6703. /*
  6704. _ ___ __ __ _ _
  6705. / \ |_ _| | \/ | ___ __| | ___| |___
  6706. / _ \ | | | |\/| |/ _ \ / _` |/ _ \ / __|
  6707. / ___ \ | | | | | | (_) | (_| | __/ \__ \
  6708. /_/ \_\___| |_| |_|\___/ \__,_|\___|_|___/
  6709. */
  6710. Blockly.Blocks['ai_model_allinit'] = {
  6711. init: function () {
  6712. // let types = getLocalStorage("isQiehuan");
  6713. // if (!types) {
  6714. // saveLocalStorage("isQiehuan", 0);
  6715. // }
  6716. this.appendDummyInput()
  6717. .appendField(Blockly.Msg.ai_models_init_title)
  6718. .appendField(new Blockly.FieldDropdown([
  6719. [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"],
  6720. [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"],
  6721. [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]
  6722. ]), "DEGREE");
  6723. this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
  6724. [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
  6725. [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
  6726. [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
  6727. ]), "interface")
  6728. // this.appendDummyInput()
  6729. // .appendField(Blockly.Msg.ai_camera_camera_fit_set1)
  6730. // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem");
  6731. // this.appendDummyInput()
  6732. // .appendField(Blockly.Msg.ai_models_init_source)
  6733. // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  6734. this.setPreviousStatement(true, null);
  6735. this.setNextStatement(true, null);
  6736. this.setColour("#ee783a");
  6737. var thisBlock = this;
  6738. this.setTooltip(function () {
  6739. var mode = thisBlock.getFieldValue('DEGREE');
  6740. var TOOLTIPS = {
  6741. 'Single Digit Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model),
  6742. 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model),
  6743. 'Human Face Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  6744. };
  6745. return TOOLTIPS[mode];
  6746. });
  6747. this.setHelpUrl('');
  6748. }
  6749. };
  6750. Blockly.Python.ai_model_allinit = function (block) {
  6751. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  6752. var degee = block.getFieldValue('DEGREE');
  6753. var _code = "";
  6754. if (degee == "Single Digit Recognition") {
  6755. Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true);
  6756. } else if (degee == "Common Object Recognition") {
  6757. var language = localStorage.getItem("handPyLanguage");
  6758. Blockly.Python.addVariable('task_objectrecognition', 'task_objectrecognition = None', true);
  6759. if (language == "en") {
  6760. _code = '' +
  6761. 'classes_objectrecognition = [\'aeroplane\', \'bicycle\', \'bird\', \'boat\', \'bottle\', \'bus\', \'car\', \'cat\', \'chair\', \'cow\', \'diningtable\', \'dog\', \'horse\', \'motorbike\', \'person\', \'pottedplant\', \'sheep\', \'sofa\', \'train\', \'tvmonitor\']\n' +
  6762. 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
  6763. 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
  6764. 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
  6765. '';
  6766. }
  6767. else if (language == "zh-hans") {
  6768. _code = '' +
  6769. 'classes_objectrecognition = [\'飞机\', \'自行车\', \'鸟\', \'船\', \'瓶子\', \'公共汽车\', \'汽车\', \'猫\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'马\', \'摩托车\', \'人\', \'盆栽\', \'羊\', \'沙发\', \'火车\', \'电视监视器\']\n' +
  6770. 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
  6771. 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
  6772. 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
  6773. '';
  6774. }
  6775. else {
  6776. _code = '' +
  6777. 'classes_objectrecognition = [\'飛機\', \'自行車\', \'鳥\', \'船\', \'瓶子\', \'公共汽車\', \'汽車\', \'貓\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'馬\', \'摩托車\', \'人\', \'盆栽\', \'羊\', \'沙發\', \'火車\', \'電視監視器\']\n' +
  6778. 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' +
  6779. 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' +
  6780. 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' +
  6781. '';
  6782. }
  6783. } else {
  6784. Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true);
  6785. _code = "" +
  6786. "task_facerecognition = kpu.load(\"/sd/preset/models/preset/face-recognition.kmodel\")\n" +
  6787. "anchor_face = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n" +
  6788. "a = kpu.init_yolo2(task_facerecognition, 0.5, 0.3, 5, anchor_face)\n" +
  6789. "\n";
  6790. }
  6791. return _code;
  6792. }
  6793. // 边缘检测
  6794. Blockly.Blocks['ai_model_edge_init'] = {
  6795. init: function () {
  6796. // let types = getLocalStorage("isQiehuan");
  6797. // if (!types) {
  6798. // saveLocalStorage("isQiehuan", 0);
  6799. // }
  6800. this.appendDummyInput()
  6801. .appendField(Blockly.Msg.ai_models_init_title)
  6802. .appendField(Blockly.Msg.ai_models_edge_detection_model);
  6803. this.setPreviousStatement(true, null);
  6804. this.setNextStatement(true, null);
  6805. this.setColour("#ee783a");
  6806. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_edge_detection_model);
  6807. this.setHelpUrl('');
  6808. }
  6809. };
  6810. Blockly.Python.ai_model_edge_init = function (block) {
  6811. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`
  6812. Blockly.Python.definitions_.import_KPU = `
  6813. class Edge:
  6814. model = {
  6815. "param": "/root/preset/model/sobel_int8.param",
  6816. "bin": "/root/preset/model/sobel_int8.bin"
  6817. }
  6818. input_size = (224, 224, 3)
  6819. output_size = (222, 222, 3)
  6820. options = {
  6821. "model_type": "awnn",
  6822. "inputs": {
  6823. "input0": input_size
  6824. },
  6825. "outputs": {
  6826. "output0": output_size
  6827. },
  6828. "mean": [127.5, 127.5, 127.5],
  6829. "norm": [0.0078125, 0.0078125, 0.0078125],
  6830. }
  6831. def __init__(self):
  6832. from maix import nn
  6833. print("-- load model:", self.model)
  6834. self.model = nn.load(self.model, opt=self.options)
  6835. print("-- load ok")
  6836. def __del__(self):
  6837. del self.model
  6838. m = Edge()`;
  6839. // var degee = block.getFieldValue('DEGREE');
  6840. var _code = "";
  6841. return _code;
  6842. }
  6843. // 加载边缘检测模型
  6844. Blockly.Blocks['ai_model_edge_loading'] = {
  6845. init: function () {
  6846. // let types = getLocalStorage("isQiehuan");
  6847. // if (!types) {
  6848. // saveLocalStorage("isQiehuan", 0);
  6849. // }
  6850. this.appendDummyInput()
  6851. .appendField(Blockly.Msg.ai_models_load_edge_detection_model);
  6852. this.appendDummyInput()
  6853. .appendField(Blockly.Msg.ai_models_init_source)
  6854. .appendField(new Blockly.FieldVariable("img_edgedetection"), "varitem");
  6855. this.setPreviousStatement(true, null);
  6856. this.setNextStatement(true, null);
  6857. this.setColour("#ee783a");
  6858. // var thisBlock = this;
  6859. this.setTooltip(Blockly.Msg.ai_models_load_edge_detection_model);
  6860. this.setHelpUrl('');
  6861. }
  6862. };
  6863. Blockly.Python.ai_model_edge_loading = function (block) {
  6864. var degee = block.getFieldValue('varitem');
  6865. // ${degee} = camera.capture().resize(224,224)
  6866. var _code = `out = m.model.forward(${degee}, quantize=True, layout="hwc")
  6867. out = out.astype(np.float32).reshape(m.output_size)
  6868. out = (np.ndarray.__abs__(out) * 255 / out.max()).astype(np.uint8)
  6869. data = out.tobytes()
  6870. edgeModel = ${degee}.load(data,(222, 222), mode="RGB")
  6871. `;
  6872. return _code;
  6873. }
  6874. // 获取边缘测试模型结果
  6875. Blockly.Blocks['ai_model_edge_result'] = {
  6876. init: function () {
  6877. this.appendDummyInput()
  6878. .appendField(Blockly.Msg.ai_models_get_edge_detection_result);
  6879. this.setOutput(true, null);
  6880. // this.setNextStatement(true, null);
  6881. this.setColour("#ee783a");
  6882. // var thisBlock = this;
  6883. this.setTooltip(Blockly.Msg.ai_models_get_edge_detection_result);
  6884. this.setHelpUrl('');
  6885. }
  6886. };
  6887. Blockly.Python.ai_model_edge_result = function (block) {
  6888. var degee = block.getFieldValue('varitem');
  6889. var _code = "edgeModel";
  6890. return [_code, Blockly.Python.ORDER_ATOMIC];
  6891. }
  6892. Blockly.Blocks['ai_model_allload'] = {
  6893. init: function () {
  6894. this.appendDummyInput()
  6895. .appendField(Blockly.Msg.ai_models_load_title)
  6896. .appendField(new Blockly.FieldDropdown([
  6897. [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"],
  6898. [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"],
  6899. [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]
  6900. ]), "DEGREE");
  6901. // this.appendDummyInput()
  6902. // .appendField(Blockly.Msg.ai_camera_camera_fit_set1)
  6903. // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem");
  6904. this.appendDummyInput()
  6905. .appendField(Blockly.Msg.ai_models_init_source)
  6906. .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  6907. this.setPreviousStatement(true, null);
  6908. this.setNextStatement(true, null);
  6909. this.setColour("#ee783a");
  6910. var thisBlock = this;
  6911. this.setTooltip(function () {
  6912. var mode = thisBlock.getFieldValue('DEGREE');
  6913. var TOOLTIPS = {
  6914. 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model),
  6915. 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model),
  6916. 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  6917. };
  6918. return TOOLTIPS[mode];
  6919. });
  6920. this.setHelpUrl('');
  6921. }
  6922. };
  6923. Blockly.Python.ai_model_allload = function (block) {
  6924. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  6925. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  6926. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  6927. var degee = block.getFieldValue('DEGREE');
  6928. var _code = ""
  6929. if (degee == "Single Digit Recognition") {
  6930. // Blockly.Python.addVariable('img_mnist_resized', '', true);
  6931. _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n";
  6932. _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
  6933. _code += "a=img_mnist_resized.invert()\n";
  6934. _code += "a=img_mnist_resized.strech_char(1)\n";
  6935. _code += "a=img_mnist_resized.pix_to_ai()\n";
  6936. _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n";
  6937. _code += "plist_mnist=fmap_mnist[:]\n";
  6938. _code += "pmax_mnist=max(plist_mnist)\n";
  6939. _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
  6940. } else if (degee == "Common Object Recognition") {
  6941. // Blockly.Python.addVariable('code_objectrecognition', '', true);
  6942. _code += "code_objectrecognition = kpu.run_yolo2(task_objectrecognition, " + variable_name + ")\n";
  6943. _code += variable_name + ".ai_to_pix()\n";
  6944. } else {
  6945. // Blockly.Python.addVariable('code_facerecognition', '', true);
  6946. _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
  6947. _code += variable_name + ".ai_to_pix()\n";
  6948. }
  6949. return _code;
  6950. }
  6951. Blockly.Blocks['ai_model_index_init'] = {
  6952. init: function () {
  6953. this.appendValueInput("class_input")
  6954. .setCheck(null)
  6955. .appendField(Blockly.Msg.ai_models_init_title)
  6956. // .appendField("DEGREE");
  6957. this.setPreviousStatement(true, null);
  6958. this.setNextStatement(true, null);
  6959. this.setColour("#ee783a");
  6960. this.setTooltip(Blockly.Msg.ai_models_init_title);
  6961. this.setHelpUrl('');
  6962. }
  6963. };
  6964. Blockly.Python.ai_model_index_init = function (block) {
  6965. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  6966. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  6967. console.log('value_class_input', value_class_input)
  6968. var _code = value_class_input;
  6969. // Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true);
  6970. return _code;
  6971. }
  6972. // 手写数字识别
  6973. Blockly.Blocks['ai_model_look_written_model'] = {
  6974. init: function () {
  6975. // this.appendDummyInput()
  6976. // .appendField(Blockly.Msg.ai_models_init_title)
  6977. // .appendField(new Blockly.FieldDropdown([
  6978. // [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"]
  6979. // ]), "DEGREE");
  6980. this.appendDummyInput()
  6981. .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  6982. this.setOutput(true, null);
  6983. this.setColour("#ee783a");
  6984. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
  6985. this.setHelpUrl("");
  6986. }
  6987. };
  6988. Blockly.Python.ai_model_look_written_model = function (block) {
  6989. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  6990. var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n";
  6991. return [_code, Blockly.Python.ORDER_ATOMIC];
  6992. }
  6993. Blockly.Blocks['ai_model_look_written_model_old'] = {
  6994. init: function () {
  6995. this.appendDummyInput()
  6996. .appendField(Blockly.Msg.ai_models_init_title)
  6997. .appendField(new Blockly.FieldDropdown([
  6998. [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"]
  6999. ]), "DEGREE");
  7000. // this.appendDummyInput()
  7001. // .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7002. this.setPreviousStatement(true, null);
  7003. this.setNextStatement(true, null);
  7004. this.setColour("#ee783a");
  7005. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
  7006. this.setHelpUrl("");
  7007. }
  7008. };
  7009. Blockly.Python.ai_model_look_written_model_old = function (block) {
  7010. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7011. var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n";
  7012. return _code;
  7013. }
  7014. Blockly.Blocks['ai_model_index_load'] = {
  7015. init: function () {
  7016. this.appendDummyInput()
  7017. .appendField(Blockly.Msg.ai_models_load_title)
  7018. .appendField(new Blockly.FieldDropdown([
  7019. [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"]
  7020. ]), "DEGREE");
  7021. this.appendDummyInput()
  7022. .appendField(Blockly.Msg.ai_models_init_source)
  7023. .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  7024. this.setPreviousStatement(true, null);
  7025. this.setNextStatement(true, null);
  7026. this.setColour("#ee783a");
  7027. var thisBlock = this;
  7028. this.setTooltip(function () {
  7029. var mode = thisBlock.getFieldValue('DEGREE');
  7030. var TOOLTIPS = {
  7031. 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model)
  7032. };
  7033. return TOOLTIPS[mode];
  7034. });
  7035. this.setHelpUrl('');
  7036. }
  7037. };
  7038. Blockly.Python.ai_model_index_load = function (block) {
  7039. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7040. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7041. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7042. var degee = block.getFieldValue('DEGREE');
  7043. var _code = ""
  7044. if (degee == "Single Digit Recognition") {
  7045. // Blockly.Python.addVariable('img_mnist_resized', '', true);
  7046. _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n";
  7047. _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
  7048. _code += "a=img_mnist_resized.invert()\n";
  7049. _code += "a=img_mnist_resized.strech_char(1)\n";
  7050. _code += "a=img_mnist_resized.pix_to_ai()\n";
  7051. _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n";
  7052. _code += "plist_mnist=fmap_mnist[:]\n";
  7053. _code += "pmax_mnist=max(plist_mnist)\n";
  7054. _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
  7055. }
  7056. return _code;
  7057. }
  7058. Blockly.Blocks['ai_model_index_mnist'] = {
  7059. init: function () {
  7060. this.appendDummyInput()
  7061. .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7062. this.appendDummyInput()
  7063. .appendField(Blockly.Msg.ai_models_hand_written_model_result);
  7064. this.appendDummyInput()
  7065. .appendField(new Blockly.FieldDropdown([
  7066. [Blockly.Msg.ai_models_hand_written_model_number, "c"],
  7067. [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"]
  7068. ]), "value");
  7069. this.setOutput(true, null);
  7070. this.setColour("#ee783a");
  7071. this.setTooltip(Blockly.Msg.ai_model_index_mnist_TOOLTIP);
  7072. this.setHelpUrl('');
  7073. }
  7074. };
  7075. Blockly.Python.ai_model_index_mnist = function (block) {
  7076. var value = block.getFieldValue('value');
  7077. var _code = "max_index_mnist";
  7078. if (value == "confidence") {
  7079. _code = "int(pmax_mnist*100)";
  7080. }
  7081. return [_code, Blockly.Python.ORDER_ATOMIC];
  7082. }
  7083. Blockly.Blocks['ai_model_digital_init'] = {
  7084. init: function () {
  7085. this.appendDummyInput()
  7086. .appendField(Blockly.Msg.ai_models_init_title)
  7087. .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7088. // this.appendDummyInput()
  7089. // .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7090. this.setPreviousStatement(true, null);
  7091. this.setNextStatement(true, null);
  7092. this.setColour("#ee783a");
  7093. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model);
  7094. this.setHelpUrl("");
  7095. }
  7096. };
  7097. Blockly.Python.ai_model_digital_init = function (block) {
  7098. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7099. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7100. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7101. var _code = `
  7102. class Number_recognition:
  7103. mdsc_path = "/root/preset/model/Number.mud"
  7104. labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  7105. anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38]
  7106. def __init__(self):
  7107. self.model = nn.load(self.mdsc_path)
  7108. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  7109. def __del__(self):
  7110. del self.model
  7111. del self.decoder
  7112. def cal_fps(self ,start , end):
  7113. one_second = 1
  7114. one_flash = end - start
  7115. fps = one_second / one_flash
  7116. return fps
  7117. number_recognition = Number_recognition()
  7118. `;
  7119. return _code;
  7120. }
  7121. Blockly.Blocks['ai_model_digital_init_loding'] = {
  7122. init: function () {
  7123. this.appendDummyInput()
  7124. .appendField(Blockly.Msg.ai_models_load_title)
  7125. .appendField(Blockly.Msg.ai_models_init_hand_written_model);
  7126. this.appendDummyInput()
  7127. .appendField(Blockly.Msg.ai_models_init_source)
  7128. .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
  7129. this.setPreviousStatement(true, null);
  7130. this.setNextStatement(true, null);
  7131. this.setColour("#ee783a");
  7132. var thisBlock = this;
  7133. this.setTooltip(function () {
  7134. var mode = thisBlock.getFieldValue('DEGREE');
  7135. var TOOLTIPS = {
  7136. 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model)
  7137. };
  7138. return TOOLTIPS[mode];
  7139. });
  7140. this.setHelpUrl('');
  7141. }
  7142. };
  7143. Blockly.Python.ai_model_digital_init_loding = function (block) {
  7144. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7145. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7146. Blockly.Python.definitions_.import_KPU = ``;
  7147. var degee = block.getFieldValue('DEGREE');
  7148. var _code = `out = number_recognition.model.forward(${variable_name}, quantize=1, layout = "hwc")
  7149. boxes, probs = number_recognition.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  7150. if len(boxes):
  7151. for boxesi, box in enumerate(boxes):
  7152. boxes[boxesi].append(probs[boxesi])
  7153. `
  7154. return _code;
  7155. }
  7156. Blockly.Blocks['ai_model_digital_result'] = {
  7157. init: function () {
  7158. this.appendDummyInput()
  7159. .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7160. this.appendDummyInput()
  7161. .appendField(Blockly.Msg.ai_models_from)
  7162. .appendField(new Blockly.FieldVariable("i"), "varitem")
  7163. .appendField(Blockly.Msg.ai_models_hand_written_model_result);
  7164. this.appendDummyInput()
  7165. .appendField(new Blockly.FieldDropdown([
  7166. [Blockly.Msg.ai_models_hand_written_model_number, "c"],
  7167. [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"],
  7168. [Blockly.Msg.ai_models_object_model_x, "X"],
  7169. [Blockly.Msg.ai_models_object_model_y, "Y"],
  7170. [Blockly.Msg.ai_models_object_model_w, "W"],
  7171. [Blockly.Msg.ai_models_object_model_h, "H"],
  7172. [Blockly.Msg.ai_models_face_model_ws, "2"],
  7173. [Blockly.Msg.ai_models_face_model_hs, "3"],
  7174. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7175. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  7176. ]), "value");
  7177. this.setOutput(true, null);
  7178. this.setColour("#ee783a");
  7179. this.setTooltip(Blockly.Msg.ai_models_hand_written_model_result);
  7180. this.setHelpUrl('');
  7181. }
  7182. };
  7183. Blockly.Python.ai_model_digital_result = function (block) {
  7184. var value = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7185. var type = block.getFieldValue('value');
  7186. // var _code = `"{}:{:.2f}%".format(number_recognition.labels[probs[${value}][0]], probs[${value}][1][probs[${value}][0]]*100)`;
  7187. if (type == "confidence") {
  7188. _code = `${value}[4][1][${value}[4][0]]*100`;
  7189. }
  7190. else if (type == "X") {
  7191. _code = `${value}[0]`;
  7192. }
  7193. else if (type == "Y") {
  7194. _code = `${value}[1]`;
  7195. }
  7196. else if (type == "W") {
  7197. _code = `int(${value}[0] + ${value}[2])`;
  7198. }
  7199. else if (type == "H") {
  7200. _code = `int(${value}[1] + ${value}[3])`;
  7201. }
  7202. else if (type == "c") {
  7203. _code = `number_recognition.labels[${value}[4][0]]`;
  7204. } else if (type == "CX") {
  7205. _code = `int((${value}[0] +${value}[0] + ${value}[2])/2)`;
  7206. } else if (type == "CY") {
  7207. _code = `int((${value}[1] + ${value}[1] + ${value}[3])/2)`;
  7208. }
  7209. else {
  7210. _code = `${value}[${type}]`;
  7211. }
  7212. return [_code, Blockly.Python.ORDER_ATOMIC];
  7213. }
  7214. Blockly.Blocks['ai_model_digital'] = {
  7215. init: function () {
  7216. this.appendDummyInput()
  7217. .appendField(Blockly.Msg.ai_model_digital);
  7218. this.setInputsInline(false);
  7219. this.setOutput(true, null);
  7220. this.setColour("#ee783a");
  7221. this.setTooltip(Blockly.Msg.ai_model_digital);
  7222. this.setHelpUrl("");
  7223. }
  7224. };
  7225. Blockly.Python.ai_model_digital = function (block) {
  7226. var _code = "boxes";
  7227. return [_code, Blockly.Python.ORDER_ATOMIC];
  7228. }
  7229. Blockly.Blocks['ai_model_digital_attribute'] = {
  7230. init: function () {
  7231. this.appendDummyInput()
  7232. .appendField(Blockly.Msg.ai_model_digital_attribute);
  7233. this.setOutput(true, null);
  7234. this.setColour("#ee783a");
  7235. this.setTooltip(Blockly.Msg.ai_model_digital_attribute);
  7236. this.setHelpUrl("");
  7237. }
  7238. };
  7239. Blockly.Python['ai_model_digital_attribute'] = function (block) {
  7240. var code = 'len(boxes)';
  7241. return [code, Blockly.Python.ORDER_NONE];
  7242. };
  7243. Blockly.Blocks['ai_model_object_init'] = {
  7244. init: function () {
  7245. this.appendDummyInput()
  7246. .appendField(Blockly.Msg.ai_models_init_title)
  7247. .appendField(Blockly.Msg.ai_models_init_object_model);
  7248. // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
  7249. // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
  7250. // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
  7251. // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
  7252. // ]), "interface")
  7253. // this.appendValueInput("class_input")
  7254. // .setCheck(null)
  7255. // .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  7256. this.setPreviousStatement(true, null);
  7257. this.setNextStatement(true, null);
  7258. this.setColour("#ee783a");
  7259. var thisBlock = this;
  7260. this.setTooltip(function () {
  7261. var mode = thisBlock.getFieldValue('DEGREE');
  7262. var TOOLTIPS = {
  7263. 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title)
  7264. };
  7265. return TOOLTIPS[mode];
  7266. });
  7267. this.setHelpUrl('');
  7268. }
  7269. };
  7270. Blockly.Python.ai_model_object_init = function (block) {
  7271. var language = localStorage.getItem("handPyLanguage");
  7272. let a = ''
  7273. if (language == "en") {
  7274. a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]'
  7275. } else if (language == "zh-hans") {
  7276. a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]'
  7277. } else {
  7278. a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]'
  7279. }
  7280. console.log(language)
  7281. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7282. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7283. Blockly.Python.definitions_.import_object = `
  7284. model = {
  7285. "param": "/root/preset/model/yolo2_20class_awnn.param",
  7286. "bin": "/root/preset/model/yolo2_20class_awnn.bin"
  7287. }
  7288. options = {
  7289. "model_type": "awnn",
  7290. "inputs": {
  7291. "input0": (224, 224, 3)
  7292. },
  7293. "outputs": {
  7294. "output0": (7, 7, (1+4+20)*5)
  7295. },
  7296. "mean": [127.5, 127.5, 127.5],
  7297. "norm": [0.0078125, 0.0078125, 0.0078125],
  7298. }
  7299. labels = ${a}
  7300. anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8]
  7301. m = nn.load(model, opt=options)
  7302. yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
  7303. `;
  7304. var _code = "";
  7305. return _code;
  7306. }
  7307. Blockly.Blocks['ai_model_object_load'] = {
  7308. init: function () {
  7309. this.appendDummyInput()
  7310. .appendField(Blockly.Msg.ai_models_load_title)
  7311. .appendField(Blockly.Msg.ai_models_init_object_model);
  7312. this.appendDummyInput()
  7313. .appendField(Blockly.Msg.ai_models_init_source)
  7314. .appendField(new Blockly.FieldVariable("img_objectrecognition"), "varitem");
  7315. this.setPreviousStatement(true, null);
  7316. this.setNextStatement(true, null);
  7317. this.setColour("#ee783a");
  7318. var thisBlock = this;
  7319. this.setTooltip(function () {
  7320. var mode = thisBlock.getFieldValue('DEGREE');
  7321. var TOOLTIPS = {
  7322. 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model)
  7323. };
  7324. return TOOLTIPS[mode];
  7325. });
  7326. this.setHelpUrl('');
  7327. }
  7328. };
  7329. Blockly.Python.ai_model_object_load = function (block) {
  7330. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7331. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7332. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7333. var degee = block.getFieldValue('DEGREE');
  7334. var _code = `out = m.forward(${variable_name}.tobytes(), quantize=True, layout="hwc")
  7335. boxes, probs = yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]))
  7336. if len(boxes):
  7337. for boxesi, box in enumerate(boxes):
  7338. boxes[boxesi].append(probs[boxesi])
  7339. `
  7340. return _code;
  7341. }
  7342. Blockly.Blocks['ai_model_look'] = {
  7343. init: function () {
  7344. this.appendDummyInput()
  7345. .appendField(Blockly.Msg.ai_models_object_model_if);
  7346. this.setInputsInline(false);
  7347. this.setOutput(true, null);
  7348. this.setColour("#ee783a");
  7349. this.setTooltip(Blockly.Msg.ai_model_look_TOOLTIP);
  7350. this.setHelpUrl("");
  7351. }
  7352. };
  7353. Blockly.Python.ai_model_look = function (block) {
  7354. var _code = "len(boxes)";
  7355. return [_code, Blockly.Python.ORDER_ATOMIC];
  7356. }
  7357. Blockly.Blocks['ai_model_get'] = {
  7358. init: function () {
  7359. this.appendDummyInput()
  7360. .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7361. this.appendDummyInput()
  7362. .appendField(Blockly.Msg.ai_models_from)
  7363. .appendField(new Blockly.FieldVariable("i"), "varitem")
  7364. .appendField(Blockly.Msg.ai_models_object_model_get)
  7365. .appendField(new Blockly.FieldDropdown([
  7366. [Blockly.Msg.ai_models_object_model_name, "Object"],
  7367. [Blockly.Msg.ai_models_object_model_x, "X"],
  7368. [Blockly.Msg.ai_models_object_model_y, "Y"],
  7369. [Blockly.Msg.ai_models_object_model_w, "W"],
  7370. [Blockly.Msg.ai_models_object_model_h, "H"],
  7371. // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7372. // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  7373. // [Blockly.Msg.ai_models_object_model_count, "Number"],
  7374. // [Blockly.Msg.ai_models_object_model_index, "Serial"],
  7375. [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
  7376. [Blockly.Msg.ai_models_face_model_ws, "2"],
  7377. [Blockly.Msg.ai_models_face_model_hs, "3"],
  7378. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7379. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  7380. ]), "TYPE");
  7381. this.setInputsInline(false);
  7382. this.setOutput(true, null);
  7383. this.setColour("#ee783a");
  7384. var thisBlock = this;
  7385. this.setTooltip(function () {
  7386. var mode = thisBlock.getFieldValue('TYPE');
  7387. var TOOLTIPS = {
  7388. 'Object': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_name),
  7389. 'X': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x),
  7390. 'Y': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y),
  7391. 'W': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_w),
  7392. 'H': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_h),
  7393. // 'CX': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x_center),
  7394. // 'CY': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y_center),
  7395. // 'Number': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_count),
  7396. // 'Serial': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_index),
  7397. // 'Confidence': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_confidence)
  7398. };
  7399. return TOOLTIPS[mode];
  7400. });
  7401. this.setHelpUrl("");
  7402. }
  7403. };
  7404. Blockly.Python.ai_model_get = function (block) {
  7405. var type = block.getFieldValue('TYPE');
  7406. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7407. var _code = "";
  7408. if (type == "Object") {
  7409. _code = `labels[${variable_name}[4][0]]`
  7410. // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
  7411. } else if (type == "X") {
  7412. _code = '' + variable_name + '[0]';
  7413. } else if (type == "Y") {
  7414. _code = '' + variable_name + '[1]';
  7415. } else if (type == "W") {
  7416. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  7417. } else if (type == "H") {
  7418. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  7419. } else if (type == "Confidence") {
  7420. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  7421. } else if (type == "CX") {
  7422. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  7423. } else if (type == "CY") {
  7424. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  7425. }
  7426. else {
  7427. _code = `${variable_name}[${type}]`;
  7428. }
  7429. return [_code, Blockly.Python.ORDER_ATOMIC];
  7430. }
  7431. Blockly.Blocks['ai_model_look_attribute'] = {
  7432. init: function () {
  7433. this.appendDummyInput()
  7434. .appendField(Blockly.Msg.ai_model_look_attribute);
  7435. this.setOutput(true, null);
  7436. this.setColour("#ee783a");
  7437. this.setTooltip(Blockly.Msg.ai_model_look_attribute_TOOLTIP);
  7438. this.setHelpUrl("");
  7439. }
  7440. };
  7441. Blockly.Python['ai_model_look_attribute'] = function (block) {
  7442. var code = 'boxes';
  7443. return [code, Blockly.Python.ORDER_NONE];
  7444. };
  7445. // 猜拳识别
  7446. Blockly.Blocks['ai_model_Guesswork_init'] = {
  7447. init: function () {
  7448. this.appendDummyInput()
  7449. .appendField(Blockly.Msg.ai_models_init_title)
  7450. .appendField(Blockly.Msg.ai_models_init_guesswork_model);
  7451. // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([
  7452. // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"],
  7453. // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"],
  7454. // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"]
  7455. // ]), "interface")
  7456. // this.appendValueInput("class_input")
  7457. // .setCheck(null)
  7458. // .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  7459. this.setPreviousStatement(true, null);
  7460. this.setNextStatement(true, null);
  7461. this.setColour("#ee783a");
  7462. var thisBlock = this;
  7463. this.setTooltip(function () {
  7464. var mode = thisBlock.getFieldValue('DEGREE');
  7465. var TOOLTIPS = {
  7466. 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title)
  7467. };
  7468. return TOOLTIPS[mode];
  7469. });
  7470. this.setHelpUrl('');
  7471. }
  7472. };
  7473. Blockly.Python.ai_model_Guesswork_init = function (block) {
  7474. var language = localStorage.getItem("handPyLanguage");
  7475. console.log(language)
  7476. let a = ''
  7477. if (language == "en") {
  7478. a = '["Scissors", "Stone" ,"Paper"]'
  7479. } else if (language == "zh-hans") {
  7480. a = '["剪刀", "石头" ,"布"]'
  7481. } else {
  7482. a = '["剪刀", "石頭" ,"布"]'
  7483. }
  7484. console.log(language)
  7485. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7486. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7487. Blockly.Python.definitions_.import_Guesswork_init = `class Mora:
  7488. mud_path = "/root/preset/model/mora_int8.mud"
  7489. labels = ${a}
  7490. anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56]
  7491. def __init__(self) -> None:
  7492. from maix import nn
  7493. self.model = nn.load(self.mud_path)
  7494. from maix.nn import decoder
  7495. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  7496. def __del__(self):
  7497. del self.model
  7498. del self.decoder
  7499. def cal_fps(self ,start , end):
  7500. one_second = 1
  7501. one_flash = end - start
  7502. fps = one_second / one_flash
  7503. return fps
  7504. def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
  7505. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
  7506. img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2)
  7507. #img.draw_string(0, 0 ,"FPS :"+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
  7508. def process(self,input):
  7509. t = time()
  7510. out = self.model.forward(input, quantize=1, layout = "hwc")
  7511. boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  7512. for i, box in enumerate(boxes):
  7513. class_id = probs[i][0]
  7514. prob = probs[i][1][class_id]
  7515. disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100)
  7516. fps = self.cal_fps(t, time())
  7517. self.draw_rectangle_with_title(input, box, disp_str, fps)
  7518. Mora = Mora()
  7519. `;
  7520. var _code = "";
  7521. return _code;
  7522. }
  7523. Blockly.Blocks['ai_model_Guesswork_load'] = {
  7524. init: function () {
  7525. this.appendDummyInput()
  7526. .appendField(Blockly.Msg.ai_models_load_title)
  7527. .appendField(Blockly.Msg.ai_models_init_guesswork_model);
  7528. this.appendDummyInput()
  7529. .appendField(Blockly.Msg.ai_models_init_source)
  7530. .appendField(new Blockly.FieldVariable("img_guessworkrecognition"), "varitem");
  7531. this.setPreviousStatement(true, null);
  7532. this.setNextStatement(true, null);
  7533. this.setColour("#ee783a");
  7534. var thisBlock = this;
  7535. this.setTooltip(function () {
  7536. var mode = thisBlock.getFieldValue('DEGREE');
  7537. var TOOLTIPS = {
  7538. 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model)
  7539. };
  7540. return TOOLTIPS[mode];
  7541. });
  7542. this.setHelpUrl('');
  7543. }
  7544. };
  7545. Blockly.Python.ai_model_Guesswork_load = function (block) {
  7546. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7547. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  7548. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  7549. var degee = block.getFieldValue('DEGREE');
  7550. var _code = `out = Mora.model.forward(${variable_name}, quantize=1, layout = "hwc")
  7551. boxes, probs = Mora.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  7552. if len(boxes):
  7553. for boxesi, box in enumerate(boxes):
  7554. boxes[boxesi].append(probs[boxesi])
  7555. `
  7556. return _code;
  7557. }
  7558. Blockly.Blocks['ai_model_Guesswork_look'] = {
  7559. init: function () {
  7560. this.appendDummyInput()
  7561. .appendField(Blockly.Msg.ai_models_guesswork_model_if);
  7562. this.setInputsInline(false);
  7563. this.setOutput(true, null);
  7564. this.setColour("#ee783a");
  7565. this.setTooltip(Blockly.Msg.ai_models_guesswork_model_if);
  7566. this.setHelpUrl("");
  7567. }
  7568. };
  7569. Blockly.Python.ai_model_Guesswork_look = function (block) {
  7570. var _code = "len(boxes)";
  7571. return [_code, Blockly.Python.ORDER_ATOMIC];
  7572. }
  7573. Blockly.Blocks['ai_model_Guesswork_get'] = {
  7574. init: function () {
  7575. this.appendDummyInput()
  7576. .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7577. this.appendDummyInput()
  7578. .appendField(Blockly.Msg.ai_models_from)
  7579. .appendField(new Blockly.FieldVariable("i"), "varitem")
  7580. .appendField(Blockly.Msg.ai_models_guesswork_model_get)
  7581. .appendField(new Blockly.FieldDropdown([
  7582. [Blockly.Msg.ai_models_object_model_name, "Object"],
  7583. [Blockly.Msg.ai_models_object_model_x, "X"],
  7584. [Blockly.Msg.ai_models_object_model_y, "Y"],
  7585. [Blockly.Msg.ai_models_object_model_w, "W"],
  7586. [Blockly.Msg.ai_models_object_model_h, "H"],
  7587. // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7588. // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  7589. // [Blockly.Msg.ai_models_object_model_count, "Number"],
  7590. // [Blockly.Msg.ai_models_object_model_index, "Serial"],
  7591. [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
  7592. [Blockly.Msg.ai_models_face_model_ws, "2"],
  7593. [Blockly.Msg.ai_models_face_model_hs, "3"],
  7594. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7595. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  7596. ]), "TYPE");
  7597. this.setInputsInline(false);
  7598. this.setOutput(true, null);
  7599. this.setColour("#ee783a");
  7600. var thisBlock = this;
  7601. this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get);
  7602. this.setHelpUrl("");
  7603. }
  7604. };
  7605. Blockly.Python.ai_model_Guesswork_get = function (block) {
  7606. var type = block.getFieldValue('TYPE');
  7607. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7608. var _code = "";
  7609. if (type == "Object") {
  7610. _code = `Mora.labels[${variable_name}[4][0]]`
  7611. // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
  7612. } else if (type == "X") {
  7613. _code = '' + variable_name + '[0]';
  7614. } else if (type == "Y") {
  7615. _code = '' + variable_name + '[1]';
  7616. } else if (type == "W") {
  7617. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  7618. } else if (type == "H") {
  7619. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  7620. } else if (type == "Confidence") {
  7621. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  7622. } else if (type == "CX") {
  7623. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  7624. } else if (type == "CY") {
  7625. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  7626. }
  7627. else {
  7628. _code = `${variable_name}[${type}]`;
  7629. }
  7630. return [_code, Blockly.Python.ORDER_ATOMIC];
  7631. }
  7632. Blockly.Blocks['ai_model_Guesswork_look_attribute'] = {
  7633. init: function () {
  7634. this.appendDummyInput()
  7635. .appendField(Blockly.Msg.ai_model_guesswork_look_attribute);
  7636. this.setOutput(true, null);
  7637. this.setColour("#ee783a");
  7638. this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute);
  7639. this.setHelpUrl("");
  7640. }
  7641. };
  7642. Blockly.Python['ai_model_Guesswork_look_attribute'] = function (block) {
  7643. var code = 'boxes';
  7644. return [code, Blockly.Python.ORDER_NONE];
  7645. };
  7646. Blockly.Blocks['ai_model_face_recognition_init'] = {
  7647. init: function () {
  7648. this.appendDummyInput()
  7649. .appendField(Blockly.Msg.ai_models_init_title)
  7650. .appendField(Blockly.Msg.ai_models_init_face_model);
  7651. this.setPreviousStatement(true, null);
  7652. this.setNextStatement(true, null);
  7653. this.setColour("#ee783a");
  7654. var thisBlock = this;
  7655. this.setTooltip(function () {
  7656. var mode = thisBlock.getFieldValue('DEGREE');
  7657. var TOOLTIPS = {
  7658. 'Human Face Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  7659. };
  7660. return TOOLTIPS[mode];
  7661. });
  7662. this.setHelpUrl('');
  7663. }
  7664. };
  7665. Blockly.Python.ai_model_face_recognition_init = function (block) {
  7666. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7667. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7668. Blockly.Python.definitions_.import_face_recognition = `
  7669. model = {
  7670. "param": "/root/preset/model/yolo2_face_awnn.param",
  7671. "bin": "/root/preset/model/yolo2_face_awnn.bin"
  7672. }
  7673. labels = ["person"]
  7674. options = {
  7675. "model_type": "awnn",
  7676. "inputs": {
  7677. "input0": (224, 224, 3)
  7678. },
  7679. "outputs": {
  7680. "output0": (7, 7, (1+4+len(labels))*5)
  7681. },
  7682. "mean": [127.5, 127.5, 127.5],
  7683. "norm": [0.0078125, 0.0078125, 0.0078125],
  7684. }
  7685. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  7686. m = nn.load(model, opt=options)
  7687. yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7))
  7688. `;
  7689. var _code = "";
  7690. return _code;
  7691. }
  7692. Blockly.Blocks['ai_model_face_recognition_load'] = {
  7693. init: function () {
  7694. this.appendDummyInput()
  7695. .appendField(Blockly.Msg.ai_models_load_title)
  7696. .appendField(Blockly.Msg.ai_models_init_face_model);
  7697. this.appendDummyInput()
  7698. .appendField(Blockly.Msg.ai_models_init_source)
  7699. .appendField(new Blockly.FieldVariable("img_facedetection"), "varitem");
  7700. this.setPreviousStatement(true, null);
  7701. this.setNextStatement(true, null);
  7702. this.setColour("#ee783a");
  7703. var thisBlock = this;
  7704. this.setTooltip(function () {
  7705. var mode = thisBlock.getFieldValue('DEGREE');
  7706. var TOOLTIPS = {
  7707. 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  7708. };
  7709. return TOOLTIPS[mode];
  7710. });
  7711. this.setHelpUrl('');
  7712. }
  7713. };
  7714. Blockly.Python.ai_model_face_recognition_load = function (block) {
  7715. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7716. var _code = `out = m.forward(${variable_name}.tobytes(), quantize=True, layout="hwc")
  7717. boxes, probs = yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]))
  7718. if len(boxes):
  7719. for boxesi, box in enumerate(boxes):
  7720. boxes[boxesi].append(probs[boxesi])
  7721. `
  7722. return _code;
  7723. }
  7724. Blockly.Blocks['ai_model_face'] = {
  7725. init: function () {
  7726. this.appendDummyInput()
  7727. .appendField(Blockly.Msg.ai_models_face_model_if);
  7728. this.setInputsInline(false);
  7729. this.setOutput(true, null);
  7730. this.setColour("#ee783a");
  7731. this.setTooltip(Blockly.Msg.ai_models_face_model_if);
  7732. this.setHelpUrl("");
  7733. }
  7734. };
  7735. Blockly.Python.ai_model_face = function (block) {
  7736. var _code = "len(boxes)";
  7737. return [_code, Blockly.Python.ORDER_ATOMIC];
  7738. }
  7739. Blockly.Blocks['ai_model_xy'] = {
  7740. init: function () {
  7741. this.appendDummyInput()
  7742. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7743. this.appendDummyInput()
  7744. .appendField(Blockly.Msg.ai_models_from)
  7745. .appendField(new Blockly.FieldVariable("i"), "varitem")
  7746. .appendField(Blockly.Msg.ai_models_face_model_get)
  7747. .appendField(new Blockly.FieldDropdown([
  7748. [Blockly.Msg.ai_models_object_model_name, "Object"],
  7749. [Blockly.Msg.ai_models_face_model_x, "X"],
  7750. [Blockly.Msg.ai_models_face_model_y, "Y"],
  7751. [Blockly.Msg.ai_models_face_model_w, "W"],
  7752. [Blockly.Msg.ai_models_face_model_h, "H"],
  7753. // [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  7754. // [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  7755. [Blockly.Msg.ai_models_face_model_count, "Number"],
  7756. // [Blockly.Msg.ai_models_face_model_index, "Serial"],
  7757. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"],
  7758. [Blockly.Msg.ai_models_face_model_ws, "2"],
  7759. [Blockly.Msg.ai_models_face_model_hs, "3"],
  7760. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7761. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  7762. ]), "TYPE");
  7763. this.setInputsInline(false);
  7764. this.setOutput(true, null);
  7765. this.setColour("#ee783a");
  7766. var thisBlock = this;
  7767. this.setTooltip(function () {
  7768. var mode = thisBlock.getFieldValue('TYPE');
  7769. var TOOLTIPS = {
  7770. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  7771. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  7772. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  7773. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  7774. // 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  7775. // 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  7776. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  7777. // 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  7778. // 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  7779. };
  7780. return TOOLTIPS[mode];
  7781. });
  7782. this.setHelpUrl("");
  7783. }
  7784. };
  7785. Blockly.Python.ai_model_xy = function (block) {
  7786. var type = block.getFieldValue('TYPE');
  7787. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7788. var _code = "";
  7789. if (type == "X") {
  7790. _code = '' + variable_name + '[0]';
  7791. } else if (type == "Y") {
  7792. _code = '' + variable_name + '[1]';
  7793. } else if (type == "W") {
  7794. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  7795. } else if (type == "H") {
  7796. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  7797. } else if (type == "Confidence") {
  7798. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  7799. } else if (type == "Object") {
  7800. _code = `"Face"`;
  7801. } else if (type == "CX") {
  7802. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  7803. } else if (type == "CY") {
  7804. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  7805. } else if (type == "Number") {
  7806. _code = `len(boxes)`;
  7807. }
  7808. else {
  7809. _code = `${variable_name}[${type}]`;
  7810. }
  7811. return [_code, Blockly.Python.ORDER_ATOMIC];
  7812. };
  7813. Blockly.Blocks['ai_model_face_attribute'] = {
  7814. init: function () {
  7815. this.appendDummyInput()
  7816. .appendField(Blockly.Msg.ai_model_face_model_list);
  7817. this.setOutput(true, null);
  7818. this.setColour("#ee783a");
  7819. this.setTooltip(Blockly.Msg.ai_model_face_model_list);
  7820. this.setHelpUrl("");
  7821. }
  7822. };
  7823. Blockly.Python['ai_model_face_attribute'] = function (block) {
  7824. var code = 'boxes';
  7825. return [code, Blockly.Python.ORDER_NONE];
  7826. };
  7827. // 车牌识别
  7828. Blockly.Blocks['ai_model_card_recognition_init'] = {
  7829. init: function () {
  7830. // this.appendDummyInput()
  7831. // .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  7832. this.appendDummyInput()
  7833. .appendField(Blockly.Msg.ai_models_init_title)
  7834. .appendField(Blockly.Msg.ai_models_init_card_model);
  7835. this.setInputsInline(false);
  7836. this.setPreviousStatement(true, null);
  7837. this.setNextStatement(true, null);
  7838. this.setColour("#ee783a");
  7839. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
  7840. this.setHelpUrl("");
  7841. }
  7842. };
  7843. Blockly.Python['ai_model_card_recognition_init'] = function (block) {
  7844. // TODO: Assemble Python into code variable.
  7845. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  7846. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  7847. Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true)
  7848. Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR:
  7849. loc_model_path = "/root/preset/model/loc.mud"
  7850. reg_model_path = "/root/preset/model/reg.mud"
  7851. chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑",
  7852. "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤",
  7853. "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁",
  7854. "新", "警", "学", "A", "B", "C", "D", "E", "F", "G",
  7855. "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S",
  7856. "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3",
  7857. "4", "5", "6", "7", "8", "9", "-"]
  7858. variances = [0.1, 0.2]
  7859. steps = [8, 16, 32]
  7860. min_sizes = [12, 24, 48, 96, 192, 320]
  7861. card_input_img = None
  7862. def __init__(self) -> None:
  7863. from maix import nn
  7864. self.loc_model = nn.load(self.loc_model_path, opt=None)
  7865. self.reg_model = nn.load(self.reg_model_path, opt=None)
  7866. from maix.nn import decoder
  7867. self.loc_decoder = decoder.license_plate_location(
  7868. [224, 224], self.steps, self.min_sizes, self.variances)
  7869. self.reg_decoder = decoder.CTC((1, 68, 18))
  7870. def __del__(self):
  7871. del self.loc_model
  7872. del self.loc_decoder
  7873. def cal_fps(self, start, end):
  7874. one_second = 1
  7875. one_flash = end - start
  7876. fps = one_second / one_flash
  7877. return fps
  7878. def draw_fps(self, img, fps):
  7879. img.draw_string(0, 0, "FPS :"+str(fps), scale=1,
  7880. color=(255, 0, 255), thickness=1)
  7881. def draw_string(self, img, x, y, string, color):
  7882. img.draw_string(x, y, string, color=color)
  7883. def draw_paste(self, src, dst):
  7884. src.paste(dst, 0, 0)
  7885. def draw_rectangle(self, img, box):
  7886. img.draw_rectangle(box[0], box[1], box[2], box[3],
  7887. color=(230, 230, 250), thickness=2)
  7888. def draw_point(self, img, landmark):
  7889. for i in range(4):
  7890. x = landmark[2 * i]
  7891. y = landmark[2 * i + 1]
  7892. img.draw_rectangle(x-2, y-2, x+2, y+2,
  7893. color=(193, 255, 193), thickness=-1)
  7894. def process(self, input):
  7895. global CARDDATABOEX
  7896. self.card_input_img = input
  7897. # retinaface decoder only support chw layout
  7898. loc_out = self.loc_model.forward(input, quantize=1, layout="chw")
  7899. boxes, landmarks = self.loc_decoder.run(loc_out, nms=0.2, score_thresh=0.7, outputs_shape=[
  7900. [1, 4, 2058], [1, 2, 2058], [1, 8, 2058]])
  7901. if len(boxes):
  7902. # print(boxes,landmarks)
  7903. for boxesi, box in enumerate(boxes):
  7904. boxes[boxesi].append(landmarks[boxesi])
  7905. CARDDATABOEX = boxes
  7906. def get_card_data(self, landmark):
  7907. # landmark = i[4][:6]
  7908. reg_in = self.card_input_img.crop_affine(landmark, 94, 24)
  7909. reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw")
  7910. LP_number = self.reg_decoder.run(reg_out)
  7911. string_LP = ""
  7912. for id in LP_number:
  7913. string_LP += self.chars[id]
  7914. return string_LP
  7915. LPRCARD = LPR()
  7916. `;
  7917. var code = '';
  7918. return code;
  7919. };
  7920. // 车牌识别
  7921. Blockly.Blocks['ai_model_card_recognition_load'] = {
  7922. init: function () {
  7923. this.appendDummyInput()
  7924. .appendField(Blockly.Msg.ai_models_load_title)
  7925. .appendField(Blockly.Msg.ai_models_init_card_model);
  7926. this.appendDummyInput()
  7927. .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  7928. .appendField(new Blockly.FieldVariable("img_card_recognition"), "varitem");
  7929. this.setInputsInline(false);
  7930. this.setPreviousStatement(true, null);
  7931. this.setNextStatement(true, null);
  7932. this.setColour("#ee783a");
  7933. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
  7934. this.setHelpUrl("");
  7935. }
  7936. };
  7937. Blockly.Python['ai_model_card_recognition_load'] = function (block) {
  7938. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7939. // TODO: Assemble Python into code variable.
  7940. var code = `LPRCARD.process(${variable_name})
  7941. `;
  7942. return code;
  7943. };
  7944. Blockly.Blocks['ai_model_card_get'] = {
  7945. init: function () {
  7946. this.appendDummyInput()
  7947. .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  7948. this.appendDummyInput()
  7949. .appendField(Blockly.Msg.ai_models_from)
  7950. .appendField(new Blockly.FieldVariable("i"), "varitem")
  7951. .appendField(Blockly.Msg.ai_models_card_model_get)
  7952. .appendField(new Blockly.FieldDropdown([
  7953. [Blockly.Msg.ai_models_init_card_result, "Object"],
  7954. [Blockly.Msg.ai_models_object_model_x, "X"],
  7955. [Blockly.Msg.ai_models_object_model_y, "Y"],
  7956. [Blockly.Msg.ai_models_object_model_w, "W"],
  7957. [Blockly.Msg.ai_models_object_model_h, "H"],
  7958. // [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7959. // [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  7960. // [Blockly.Msg.ai_models_object_model_count, "Number"],
  7961. // [Blockly.Msg.ai_models_object_model_index, "Serial"],
  7962. // [Blockly.Msg.ai_models_object_model_confidence, "Confidence"],
  7963. [Blockly.Msg.ai_models_face_model_ws, "2"],
  7964. [Blockly.Msg.ai_models_face_model_hs, "3"],
  7965. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  7966. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  7967. ]), "TYPE");
  7968. this.setInputsInline(false);
  7969. this.setOutput(true, null);
  7970. this.setColour("#ee783a");
  7971. var thisBlock = this;
  7972. this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get);
  7973. this.setHelpUrl("");
  7974. }
  7975. };
  7976. Blockly.Python.ai_model_card_get = function (block) {
  7977. var type = block.getFieldValue('TYPE');
  7978. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  7979. var _code = "";
  7980. if (type == "Object") {
  7981. _code = `LPRCARD.get_card_data(${variable_name}[4][:6])`
  7982. // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)`
  7983. } else if (type == "X") {
  7984. _code = '' + variable_name + '[0]';
  7985. } else if (type == "Y") {
  7986. _code = '' + variable_name + '[1]';
  7987. } else if (type == "W") {
  7988. _code = 'int(' + variable_name + '[2])';
  7989. } else if (type == "H") {
  7990. _code = 'int(' + variable_name + '[3])';
  7991. } else if (type == "Confidence") {
  7992. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  7993. } else if (type == "CX") {
  7994. _code = `int((${variable_name}[0] + ${variable_name}[2])/2)`;
  7995. } else if (type == "CY") {
  7996. _code = `int((${variable_name}[1] + ${variable_name}[3])/2)`;
  7997. }
  7998. else {
  7999. _code = `${variable_name}[${type}]-${variable_name}[${type - 2}]`;
  8000. }
  8001. // }
  8002. return [_code, Blockly.Python.ORDER_ATOMIC];
  8003. }
  8004. //
  8005. // 车牌识别
  8006. Blockly.Blocks['ai_model_card_xy'] = {
  8007. init: function () {
  8008. this.appendDummyInput()
  8009. .appendField(Blockly.Msg.ai_models_card_if_true);
  8010. this.setInputsInline(false);
  8011. this.setOutput(true, null);
  8012. this.setColour("#ee783a");
  8013. this.setTooltip(Blockly.Msg.ai_models_card_if_true);
  8014. this.setHelpUrl("");
  8015. }
  8016. };
  8017. Blockly.Python['ai_model_card_xy'] = function (block) {
  8018. var code = 'len(CARDDATABOEX)';
  8019. return [code, Blockly.Python.ORDER_ATOMIC];
  8020. };
  8021. Blockly.Blocks['ai_model_card_result'] = {
  8022. init: function () {
  8023. this.appendDummyInput()
  8024. .appendField(Blockly.Msg.ai_models_card_attribute);
  8025. this.setInputsInline(false);
  8026. this.setOutput(true, null);
  8027. this.setColour("#ee783a");
  8028. this.setTooltip(Blockly.Msg.ai_models_card_attribute);
  8029. this.setHelpUrl("");
  8030. }
  8031. };
  8032. Blockly.Python['ai_model_card_result'] = function (block) {
  8033. var code = 'CARDDATABOEX';
  8034. return [code, Blockly.Python.ORDER_ATOMIC];
  8035. };
  8036. // 人体检测
  8037. Blockly.Blocks['ai_model_gesture_recognition_init'] = {
  8038. init: function () {
  8039. this.appendDummyInput()
  8040. .appendField(Blockly.Msg.ai_models_init_title)
  8041. .appendField(Blockly.Msg.ai_models_init_humane_model);
  8042. this.setPreviousStatement(true, null);
  8043. this.setNextStatement(true, null);
  8044. this.setColour("#ee783a");
  8045. this.setTooltip(Blockly.Msg.ai_models_init_title);
  8046. this.setHelpUrl('');
  8047. }
  8048. }
  8049. Blockly.Python['ai_model_gesture_recognition_init'] = function (block) {
  8050. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8051. Blockly.Python.definitions_.import_hunman_init = `class humanPerson:
  8052. mud_path = "/root/preset/model/person_int8.mud"
  8053. labels = ["person"]
  8054. anchors = [4.72, 6.26, 1.39, 3.53, 0.78, 1.9, 0.35, 0.95, 2.49, 4.87]
  8055. def __init__(self) -> None:
  8056. self.model = nn.load(self.mud_path)
  8057. from maix.nn import decoder
  8058. self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7))
  8059. def __del__(self):
  8060. del self.model
  8061. del self.decoder
  8062. def cal_fps(self ,start , end):
  8063. one_second = 1
  8064. one_flash = end - start
  8065. fps = one_second / one_flash
  8066. return fps
  8067. def draw_rectangle_with_title(self ,img, box, disp_str , fps ):
  8068. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2)
  8069. img.draw_string(box[0], box[1]+ box[3] ,disp_str, scale=1,color=(0, 0, 255), thickness=2)
  8070. #img.draw_string(0, 0 ,'FPS :'+str(fps), scale=2 ,color=(0, 0, 255), thickness=2)
  8071. humanPerson = humanPerson()
  8072. `
  8073. var code = '';
  8074. return code;
  8075. };
  8076. Blockly.Blocks['ai_model_gesture_recognition_load'] = {
  8077. init: function () {
  8078. this.appendDummyInput()
  8079. .appendField(Blockly.Msg.ai_models_load_title)
  8080. .appendField(Blockly.Msg.ai_models_init_humane_model);
  8081. this.appendDummyInput()
  8082. .appendField(Blockly.Msg.ai_models_init_source)
  8083. .appendField(new Blockly.FieldVariable("img_gesture_facedetection"), "varitem");
  8084. this.setPreviousStatement(true, null);
  8085. this.setNextStatement(true, null);
  8086. this.setColour("#ee783a");
  8087. this.setTooltip(Blockly.Msg.ai_models_load_title);
  8088. this.setHelpUrl('');
  8089. }
  8090. };
  8091. Blockly.Python.ai_model_gesture_recognition_load = function (block) {
  8092. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8093. var _code = `out = humanPerson.model.forward(${variable_name}, quantize=1, layout = "hwc")
  8094. boxes, probs = humanPerson.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224))
  8095. if len(boxes):
  8096. for boxesi, box in enumerate(boxes):
  8097. boxes[boxesi].append(probs[boxesi])
  8098. `
  8099. return _code;
  8100. }
  8101. Blockly.Blocks['ai_model_gesture'] = {
  8102. init: function () {
  8103. this.appendDummyInput()
  8104. .appendField(Blockly.Msg.ai_models_human_model_if);
  8105. this.setInputsInline(false);
  8106. this.setOutput(true, null);
  8107. this.setColour("#ee783a");
  8108. this.setTooltip(Blockly.Msg.ai_models_human_model_if);
  8109. this.setHelpUrl("");
  8110. }
  8111. };
  8112. Blockly.Python.ai_model_gesture = function (block) {
  8113. var _code = "len(boxes)";
  8114. return [_code, Blockly.Python.ORDER_ATOMIC];
  8115. }
  8116. Blockly.Blocks['ai_model_gesture_xy'] = {
  8117. init: function () {
  8118. this.appendDummyInput()
  8119. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  8120. this.appendDummyInput()
  8121. .appendField(Blockly.Msg.ai_models_from)
  8122. .appendField(new Blockly.FieldVariable("i"), "varitem")
  8123. .appendField(Blockly.Msg.ai_models_human_model_get)
  8124. .appendField(new Blockly.FieldDropdown([
  8125. // [Blockly.Msg.ai_models_object_model_name, "Object"],
  8126. [Blockly.Msg.ai_models_face_model_x, "X"],
  8127. [Blockly.Msg.ai_models_face_model_y, "Y"],
  8128. [Blockly.Msg.ai_models_face_model_w, "W"],
  8129. [Blockly.Msg.ai_models_face_model_h, "H"],
  8130. // [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  8131. // [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  8132. // [Blockly.Msg.ai_models_face_model_count, "Number"],
  8133. // [Blockly.Msg.ai_models_face_model_index, "Serial"],
  8134. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"],
  8135. [Blockly.Msg.ai_models_face_model_ws, "2"],
  8136. [Blockly.Msg.ai_models_face_model_hs, "3"],
  8137. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8138. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  8139. ]), "TYPE");
  8140. this.setInputsInline(false);
  8141. this.setOutput(true, null);
  8142. this.setColour("#ee783a");
  8143. var thisBlock = this;
  8144. this.setTooltip(function () {
  8145. var mode = thisBlock.getFieldValue('TYPE');
  8146. var TOOLTIPS = {
  8147. 'X': Blockly.Msg.ai_model_human_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  8148. 'Y': Blockly.Msg.ai_model_human_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  8149. 'W': Blockly.Msg.ai_model_human_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  8150. 'H': Blockly.Msg.ai_model_human_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  8151. // 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  8152. // 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  8153. // 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  8154. // 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  8155. 'Confidence': Blockly.Msg.ai_model_human_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  8156. };
  8157. return TOOLTIPS[mode];
  8158. });
  8159. this.setHelpUrl("");
  8160. }
  8161. };
  8162. Blockly.Python.ai_model_gesture_xy = function (block) {
  8163. var type = block.getFieldValue('TYPE');
  8164. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8165. var _code = "";
  8166. if (type == "X") {
  8167. _code = '' + variable_name + '[0]';
  8168. } else if (type == "Y") {
  8169. _code = '' + variable_name + '[1]';
  8170. } else if (type == "W") {
  8171. _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])';
  8172. } else if (type == "H") {
  8173. _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])';
  8174. } else if (type == "Confidence") {
  8175. _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`;
  8176. } else if (type == "Object") {
  8177. _code = `Person`;
  8178. } else if (type == "CX") {
  8179. _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`;
  8180. } else if (type == "CY") {
  8181. _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`;
  8182. }
  8183. else {
  8184. _code = `${variable_name}[${type}]`;
  8185. }
  8186. return [_code, Blockly.Python.ORDER_ATOMIC];
  8187. };
  8188. Blockly.Blocks['ai_model_gesture_attribute'] = {
  8189. init: function () {
  8190. this.appendDummyInput()
  8191. .appendField(Blockly.Msg.ai_model_human_attribute);
  8192. this.setOutput(true, null);
  8193. this.setColour("#ee783a");
  8194. this.setTooltip(Blockly.Msg.ai_model_human_attribute);
  8195. this.setHelpUrl("");
  8196. }
  8197. };
  8198. Blockly.Python['ai_model_gesture_attribute'] = function (block) {
  8199. var code = 'boxes';
  8200. return [code, Blockly.Python.ORDER_NONE];
  8201. };
  8202. Blockly.Blocks['ai_model_face_recognition_init_new'] = {
  8203. init: function () {
  8204. this.appendDummyInput().appendField(Blockly.Msg.ai_models_init_title)
  8205. .appendField('人脸识别模型');
  8206. this.setPreviousStatement(true, null);
  8207. this.setNextStatement(true, null);
  8208. this.setColour("#ee783a");
  8209. this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_face_model);
  8210. this.setHelpUrl("");
  8211. }
  8212. };
  8213. Blockly.Python.ai_model_face_recognition_init_new = function (block) {
  8214. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8215. Blockly.Python.definitions_['v831_import_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize`
  8216. Blockly.Python.definitions_.import_face_recognition_init_new = `
  8217. class Face_recognize:
  8218. score_threshold = 70 #识别分数阈值
  8219. input_size = (224, 224, 3) #输入图片尺寸
  8220. input_size_fe = (128, 128, 3) #输入人脸数据
  8221. feature_len = 256 #人脸数据宽度
  8222. steps = [8, 16, 32] #
  8223. channel_num = 0 #通道数量
  8224. users = [] #初始化用户列表
  8225. threshold = 0.5 #人脸阈值
  8226. nms = 0.3
  8227. max_face_num = 3 #输出的画面中的人脸的最大个数
  8228. 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"] #人脸标签定义
  8229. model = {
  8230. "param": "/root/preset/model/model_int8.param",
  8231. "bin": "/root/preset/model/model_int8.bin"
  8232. }
  8233. model_fe = {
  8234. "param": "/root/preset/model/fe_res18_117.param",
  8235. "bin": "/root/preset/model/fe_res18_117.bin"
  8236. }
  8237. def __init__(self):
  8238. for i in range(len(self.steps)):
  8239. self.channel_num += self.input_size[1] / self.steps[i] * (self.input_size[0] / self.steps[i]) * 2
  8240. self.channel_num = int(self.channel_num) #统计通道数量
  8241. self.options = { #准备人脸输出参数
  8242. "model_type": "awnn",
  8243. "inputs": {
  8244. "input0": self.input_size
  8245. },
  8246. "outputs": {
  8247. "output0": (1, 4, self.channel_num) ,
  8248. "431": (1, 2, self.channel_num) ,
  8249. "output2": (1, 10, self.channel_num)
  8250. },
  8251. "mean": [127.5, 127.5, 127.5],
  8252. "norm": [0.0078125, 0.0078125, 0.0078125],
  8253. }
  8254. self.options_fe = { #准备特征提取参数
  8255. "model_type": "awnn",
  8256. "inputs": {
  8257. "inputs_blob": self.input_size_fe
  8258. },
  8259. "outputs": {
  8260. "FC_blob": (1, 1, self.feature_len)
  8261. },
  8262. "mean": [127.5, 127.5, 127.5],
  8263. "norm": [0.0078125, 0.0078125, 0.0078125],
  8264. }
  8265. print("-- load model:", self.model)
  8266. self.m = nn.load(self.model, opt=self.options)
  8267. print("-- load ok")
  8268. print("-- load model:", self.model_fe)
  8269. self.m_fe = nn.load(self.model_fe, opt=self.options_fe)
  8270. print("-- load ok")
  8271. self.face_recognizer = FaceRecognize(self.m, self.m_fe, self.feature_len, self.input_size, self.threshold, self.nms, self.max_face_num)
  8272. def map_face(self,box,points): #将224*224空间的位置转换到240*240或320*240空间内
  8273. from maix import display # print(box,points)
  8274. if display.width() == display.height():
  8275. def tran(x):
  8276. return int(x/224*display.width())
  8277. box = list(map(tran, box))
  8278. def tran_p(p):
  8279. return list(map(tran, p))
  8280. points = list(map(tran_p, points))
  8281. else:
  8282. # 168x224(320x240) > 224x224(240x240) > 320x240
  8283. s = (224*display.height()/display.width()) # 168x224
  8284. w, h, c = display.width()/224, display.height()/224, 224/s
  8285. t, d = c*h, (224 - s) // 2 # d = 224 - s // 2 == 28
  8286. 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)
  8287. def tran_p(p):
  8288. return [int(p[0]*w), int((p[1]-d)*t)] # 224 - 168 / 2 = 28 so 168 / (old_h - 28) = 240 / new_h
  8289. points = list(map(tran_p, points))
  8290. # print(box,points)
  8291. return box,points
  8292. def recognize(self, feature): #进行人脸匹配
  8293. def _compare(user): #定义映射函数
  8294. return self.face_recognizer.compare(user, feature) #推测匹配分数 score相关分数
  8295. face_score_l = list(map(_compare,self.users)) #映射特征数据在记录中的比对分数
  8296. return max(enumerate(face_score_l), key=lambda x: x[-1]) #提取出人脸分数最大值和最大值所在的位置
  8297. def __del__(self):
  8298. del self.face_recognizer
  8299. del self.m_fe
  8300. del self.m
  8301. face_recognizer = Face_recognize()
  8302. `;
  8303. // var degee = block.getFieldValue('DEGREE');
  8304. var _code = "";
  8305. // Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true);
  8306. return [_code, Blockly.Python.ORDER_ATOMIC];
  8307. }
  8308. Blockly.Blocks['ai_model_face_recognition_load_new'] = {
  8309. init: function () {
  8310. this.appendDummyInput()
  8311. .appendField(Blockly.Msg.ai_models_load_title)
  8312. .appendField(Blockly.Msg.ai_models_init_face_model);
  8313. this.appendDummyInput()
  8314. .appendField(Blockly.Msg.ai_models_init_source)
  8315. .appendField(new Blockly.FieldVariable("img_facerecognition"), "varitem");
  8316. this.setPreviousStatement(true, null);
  8317. this.setNextStatement(true, null);
  8318. this.setColour("#ee783a");
  8319. var thisBlock = this;
  8320. this.setTooltip(function () {
  8321. var mode = thisBlock.getFieldValue('DEGREE');
  8322. var TOOLTIPS = {
  8323. 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model)
  8324. };
  8325. return TOOLTIPS[mode];
  8326. });
  8327. this.setHelpUrl('');
  8328. }
  8329. };
  8330. Blockly.Python.ai_model_face_recognition_load_new = function (block) {
  8331. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8332. // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE);
  8333. // Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  8334. // var degee = block.getFieldValue('DEGREE');
  8335. var _code = `facesRecognitionLoadNew = face_recognizer.face_recognizer.get_faces(AI_img.tobytes(),False) #提取人脸特征信息
  8336. `;
  8337. // Blockly.Python.addVariable('code_facerecognition', '', true);
  8338. // _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
  8339. // _code += variable_name + ".ai_to_pix()\n";
  8340. return _code;
  8341. }
  8342. Blockly.Blocks['ai_model_face_new'] = {
  8343. init: function () {
  8344. this.appendDummyInput()
  8345. .appendField(Blockly.Msg.ai_models_face_model_if);
  8346. this.setInputsInline(false);
  8347. this.setOutput(true, null);
  8348. this.setColour("#ee783a");
  8349. this.setTooltip(Blockly.Msg.ai_model_face_TOOLTIP);
  8350. this.setHelpUrl("");
  8351. }
  8352. };
  8353. Blockly.Python.ai_model_face_new = function (block) {
  8354. var _code = "facesRecognitionLoadNew";
  8355. return [_code, Blockly.Python.ORDER_ATOMIC];
  8356. }
  8357. Blockly.Blocks['ai_model_xy_new'] = {
  8358. init: function () {
  8359. this.appendDummyInput()
  8360. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  8361. this.appendDummyInput()
  8362. .appendField(Blockly.Msg.ai_models_from)
  8363. .appendField(new Blockly.FieldVariable("i"), "varitem")
  8364. .appendField(Blockly.Msg.ai_models_face_model_get)
  8365. .appendField(new Blockly.FieldDropdown([
  8366. [Blockly.Msg.ai_models_face_model_x, "X"],
  8367. [Blockly.Msg.ai_models_face_model_y, "Y"],
  8368. [Blockly.Msg.ai_models_face_model_w, "W"],
  8369. [Blockly.Msg.ai_models_face_model_h, "H"],
  8370. [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  8371. [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  8372. [Blockly.Msg.ai_models_face_model_count, "Number"],
  8373. [Blockly.Msg.ai_models_face_model_index, "Serial"],
  8374. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]
  8375. ]), "TYPE");
  8376. this.setInputsInline(false);
  8377. this.setOutput(true, null);
  8378. this.setColour("#ee783a");
  8379. var thisBlock = this;
  8380. this.setTooltip(function () {
  8381. var mode = thisBlock.getFieldValue('TYPE');
  8382. var TOOLTIPS = {
  8383. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  8384. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  8385. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  8386. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  8387. 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  8388. 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  8389. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  8390. 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  8391. 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  8392. };
  8393. return TOOLTIPS[mode];
  8394. });
  8395. this.setHelpUrl("");
  8396. }
  8397. };
  8398. Blockly.Python.ai_model_xy_new = function (block) {
  8399. var type = block.getFieldValue('TYPE');
  8400. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8401. var _code = "";
  8402. if (type == "X") {
  8403. _code = variable_name + "[0]";
  8404. } else if (type == "Y") {
  8405. _code = variable_name + "[1]";
  8406. } else if (type == "W") {
  8407. _code = variable_name + "[0] + " + variable_name + "[2]";
  8408. } else if (type == "H") {
  8409. _code = variable_name + "[1] + " + variable_name + "[3]";
  8410. }
  8411. // else if (type == "Number") {
  8412. // _code = variable_name + ".objnum()";
  8413. // } else if (type == "Serial") {
  8414. // _code = variable_name + ".index()";
  8415. // } else if (type == "Confidence") {
  8416. // _code = variable_name + ".value()";
  8417. // } else if (type == "CX") {
  8418. // _code = variable_name + ".x()+(" + variable_name + ".w()/2)";
  8419. // } else if (type == "CY") {
  8420. // _code = variable_name + ".y()+(" + variable_name + ".h()/2)";
  8421. // }
  8422. return [_code, Blockly.Python.ORDER_ATOMIC];
  8423. };
  8424. Blockly.Blocks['ai_model_face_attribute_new'] = {
  8425. init: function () {
  8426. this.appendDummyInput()
  8427. .appendField(Blockly.Msg.ai_model_face_attribute);
  8428. this.setOutput(true, null);
  8429. this.setColour("#ee783a");
  8430. this.setTooltip(Blockly.Msg.ai_model_face_attribute_TOOLTIP);
  8431. this.setHelpUrl("");
  8432. }
  8433. };
  8434. Blockly.Python['ai_model_face_attribute_new'] = function (block) {
  8435. var code = 'facesRecognitionLoadNew';
  8436. return [code, Blockly.Python.ORDER_NONE];
  8437. };
  8438. // 人脸识别
  8439. Blockly.Blocks['face_recognition_init'] = {
  8440. init: function () {
  8441. this.appendDummyInput()
  8442. .appendField(Blockly.Msg.ai_model_face)
  8443. this.appendDummyInput()
  8444. .appendField(Blockly.Msg.ai_model_face_name);
  8445. this.appendValueInput("class_input")
  8446. .setCheck(null)
  8447. .appendField(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD + ":")
  8448. .appendField(new Blockly.FieldVariable("people_name_list"), "varitem");;
  8449. this.setInputsInline(false);
  8450. this.setPreviousStatement(true, null);
  8451. this.setNextStatement(true, null);
  8452. this.setColour("#ee783a");
  8453. this.setTooltip(Blockly.Msg.ai_model_face);
  8454. this.setHelpUrl("");
  8455. }
  8456. };
  8457. Blockly.Python['face_recognition_init'] = function (block) {
  8458. var face_list = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8459. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  8460. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8461. Blockly.Python.definitions_['v831_import_from_maix_nn_face'] = `from maix.nn.app import face`
  8462. Blockly.Python.definitions_['v831_import_from_maix_nn_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize`
  8463. Blockly.Python.addVariable('score_threshold', 'score_threshold = 70', true);
  8464. Blockly.Python.addVariable('CLASSNAMEFACELIST', ``, true);
  8465. Blockly.Python.definitions_.import_self_learning_init = `
  8466. max_face_num = 4
  8467. detect_threshold = 0.5
  8468. detect_nms = 0.3
  8469. #score_threshold = 70
  8470. FEATURES = []
  8471. `
  8472. var code = `${face_list} = ${value_class_input}
  8473. CLASSNAMEFACELIST = ${face_list}
  8474. `;
  8475. return code;
  8476. };
  8477. Blockly.Blocks['face_recognition_load'] = {
  8478. init: function () {
  8479. this.appendDummyInput()
  8480. .appendField(Blockly.Msg.v831_face_recognition_load);
  8481. this.appendDummyInput()
  8482. .appendField(Blockly.Msg.ai_models_init_source)
  8483. .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem");
  8484. this.setInputsInline(false);
  8485. this.setPreviousStatement(true, null);
  8486. this.setNextStatement(true, null);
  8487. this.setColour("#ee783a");
  8488. this.setTooltip(Blockly.Msg.v831_face_recognition_load_title);
  8489. this.setHelpUrl("");
  8490. }
  8491. };
  8492. Blockly.Python['face_recognition_load'] = function (block) {
  8493. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8494. Blockly.Python.definitions_.import_Face_Recognizer = `class Face_Recognizer:
  8495. def __init__(self, threshold = 0.5, nms = 0.3, max_face_num = 1):
  8496. model = "/root/preset/model/retinaface.mud"
  8497. model_fe = "/root/preset/model/fe_resnet.mud"
  8498. self.input_size = (224, 224, 3)
  8499. input_size_fe = (128, 128, 3)
  8500. self.feature_len = 256
  8501. self.features = []
  8502. print("-- load model:", model)
  8503. m = nn.load(model)
  8504. print("-- load ok")
  8505. print("-- load model:", model_fe)
  8506. m_fe = nn.load(model_fe)
  8507. print("-- load ok")
  8508. self.recognizer = FaceRecognize(m, m_fe, self.feature_len, self.input_size, threshold, nms, max_face_num)
  8509. print("-- init end")
  8510. def get_faces(self, img, std_img = False):
  8511. faces = self.recognizer.get_faces(img, std_img)
  8512. return faces
  8513. def __len__(self):
  8514. return len(self.features)
  8515. def add_user(self, name, feature):
  8516. self.features.append([name, feature])
  8517. return True
  8518. def remove_user(self, name_del):
  8519. rm = None
  8520. for name, feature in self.features:
  8521. if name_del == name:
  8522. rm = [name, feature]
  8523. if rm:
  8524. self.features.remove(rm)
  8525. return True
  8526. return False
  8527. def recognize(self, feature):
  8528. max_score = 0
  8529. uid = -1
  8530. for i, user in enumerate(self.features):
  8531. score = self.recognizer.compare(user[1], feature)
  8532. if score > max_score:
  8533. max_score = score
  8534. uid = i
  8535. if uid >= 0:
  8536. return self.features[uid][0], max_score
  8537. return None, 0
  8538. def get_input_size(self):
  8539. return self.input_size
  8540. def get_feature_len(self):
  8541. return self.feature_len
  8542. def darw_info(self, img, box, points, disp_str, bg_color=(255, 0, 0, 255), font_color=(255, 255, 255, 255), font_size=32):
  8543. font_wh = image.get_string_size(disp_str)
  8544. for p in points:
  8545. img.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=bg_color)
  8546. img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color=bg_color, thickness=2)
  8547. if disp_str:
  8548. img.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color=bg_color, thickness = -1)
  8549. img.draw_string(box[0], box[1] - font_wh[1], disp_str, color=font_color)
  8550. def map_face(self,box,points,IMAGEFACESHOW):
  8551. # print(box,points)
  8552. for p in points:
  8553. IMAGEFACESHOW.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=(255,200,255))
  8554. #return box,points
  8555. def darw_title(self, img, dis_size ,key_l = None, key_r =None):
  8556. if key_C:
  8557. key_l = "| "+ key_l
  8558. img.draw_string( 1, 2 ,key_l , scale = 1, color = (255, 255, 255), thickness = 2)
  8559. if key_D:
  8560. key_r = key_r+" |"
  8561. w = int(dis_size[0] - 4 - image.get_string_size(key_r)[0] * 1)
  8562. img.draw_string( w, 2 ,key_r , scale = 1, color = (255, 255, 255), thickness = 2)
  8563. FACERECGNIZER = Face_Recognizer(0.5, 0.3, max_face_num = 4)
  8564. `
  8565. var code = `FACESRECOGNITONRESULT = FACERECGNIZER.get_faces(${variable_name})
  8566. `;
  8567. return code;
  8568. };
  8569. Blockly.Blocks['face_recognition_if_face'] = {
  8570. init: function () {
  8571. this.appendDummyInput()
  8572. .appendField(Blockly.Msg.ai_models_face_model_if_new);
  8573. this.setInputsInline(false);
  8574. this.setOutput(true, null);
  8575. this.setColour("#ee783a");
  8576. this.setTooltip(Blockly.Msg.ai_models_face_model_if_new);
  8577. this.setHelpUrl("");
  8578. }
  8579. };
  8580. Blockly.Python['face_recognition_if_face'] = function (block) {
  8581. var code = `len(FACESRECOGNITONRESULT)`;
  8582. return [code, Blockly.Python.ORDER_ATOMIC];
  8583. };
  8584. Blockly.Blocks['face_recognition_face_result'] = {
  8585. init: function () {
  8586. this.appendDummyInput()
  8587. .appendField(Blockly.Msg.ai_model_face_attribute_new);
  8588. this.setInputsInline(false);
  8589. this.setOutput(true, null);
  8590. this.setColour("#ee783a");
  8591. this.setTooltip(Blockly.Msg.ai_model_face_attribute_new);
  8592. this.setHelpUrl("");
  8593. }
  8594. };
  8595. Blockly.Python['face_recognition_face_result'] = function (block) {
  8596. var code = `FACESRECOGNITONRESULT`;
  8597. return [code, Blockly.Python.ORDER_ATOMIC];
  8598. };
  8599. Blockly.Blocks['face_recognition_detection_rectangle'] = {
  8600. init: function () {
  8601. this.appendDummyInput()
  8602. .appendField(Blockly.Msg.ai_models_from)
  8603. .appendField(new Blockly.FieldVariable("i"), "varitem")
  8604. .appendField(Blockly.Msg.ai_models_face_model_get)
  8605. .appendField(new Blockly.FieldDropdown([
  8606. // [Blockly.Msg.face_information, "rect"],
  8607. [Blockly.Msg.ai_models_face_model_x, "X"],
  8608. [Blockly.Msg.ai_models_face_model_y, "Y"],
  8609. [Blockly.Msg.ai_models_face_model_w, "W"],
  8610. [Blockly.Msg.ai_models_face_model_h, "H"],
  8611. // [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  8612. // [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  8613. // [Blockly.Msg.ai_models_face_model_count, "Number"],
  8614. // [Blockly.Msg.ai_models_face_model_index, "Serial"],
  8615. [Blockly.Msg.ai_models_face_model_confidence_1, "Confidence"],
  8616. [Blockly.Msg.ai_models_face_model_ws, "2"],
  8617. [Blockly.Msg.ai_models_face_model_hs, "3"],
  8618. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  8619. [Blockly.Msg.ai_models_object_model_y_center, "CY"],
  8620. [Blockly.Msg.v831_model_face_name, "0"],
  8621. [Blockly.Msg.v831_models_face_model_confidence, "1"],
  8622. ]), "TYPE");
  8623. this.setInputsInline(false);
  8624. this.setOutput(true, null);
  8625. this.setColour("#ee783a");
  8626. var thisBlock = this;
  8627. this.setTooltip(function () {
  8628. var mode = thisBlock.getFieldValue('TYPE');
  8629. var TOOLTIPS = {
  8630. 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect),
  8631. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  8632. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  8633. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  8634. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  8635. 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  8636. 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  8637. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  8638. 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  8639. 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  8640. };
  8641. return TOOLTIPS[mode];
  8642. });
  8643. this.setHelpUrl("");
  8644. }
  8645. };
  8646. Blockly.Python.face_recognition_detection_rectangle = function (block) {
  8647. var type = block.getFieldValue('TYPE');
  8648. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8649. var _code = "";
  8650. if (type == "rect") {
  8651. _code = variable_name + "[3]";
  8652. } else if (type == "X") {
  8653. _code = variable_name + "[1][0]";
  8654. } else if (type == "Y") {
  8655. _code = variable_name + "[1][1]";
  8656. } else if (type == "W") {
  8657. _code = `int(${variable_name}[1][2]+${variable_name}[1][0])`;
  8658. } else if (type == "H") {
  8659. _code = `int(${variable_name}[1][3]+${variable_name}[1][1])`;
  8660. } else if (type == "Number") {
  8661. _code = variable_name + ".objnum()";
  8662. } else if (type == "Serial") {
  8663. _code = variable_name + ".index()";
  8664. } else if (type == "Confidence") {
  8665. _code = variable_name + "[0]";
  8666. } else if (type == "CX") {
  8667. _code = `int((${variable_name}[1][2]+${variable_name}[1][0]+${variable_name}[1][0])/2)`;
  8668. } else if (type == "CY") {
  8669. _code = `int((${variable_name}[1][3]+${variable_name}[1][1]+${variable_name}[1][1])/2)`;
  8670. } else if (type == "0" || type == "1") {
  8671. _code = `FACERECGNIZER.recognize(${variable_name}[3])[${type}]`
  8672. }
  8673. else {
  8674. _code = `${variable_name}[1][${type}]`;
  8675. }
  8676. return [_code, Blockly.Python.ORDER_ATOMIC];
  8677. };
  8678. Blockly.Blocks['face_recognition_map_face'] = {
  8679. init: function () {
  8680. this.appendDummyInput()
  8681. .appendField(Blockly.Msg.face_recognition_map_face_canvas)
  8682. .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem")
  8683. .appendField(Blockly.Msg.face_recognition_map_face_show)
  8684. .appendField(new Blockly.FieldVariable("i"), "varitem1")
  8685. .appendField(Blockly.Msg.face_recognition_map_face_key_point);
  8686. // this.setInputsInline(false);
  8687. this.setPreviousStatement(true, null);
  8688. this.setNextStatement(true, null);
  8689. this.setColour("#ee783a");
  8690. this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title);
  8691. this.setHelpUrl("");
  8692. }
  8693. };
  8694. Blockly.Python['face_recognition_map_face'] = function (block) {
  8695. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8696. var variable1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
  8697. var code = `FACERECGNIZER.map_face(${variable1}[1],${variable1}[2],${variable_name})
  8698. `;
  8699. return code;
  8700. };
  8701. Blockly.Blocks['face_recognition_add'] = {
  8702. init: function () {
  8703. this.appendDummyInput()
  8704. .appendField(Blockly.Msg.v831_setting_face_data_save)
  8705. .appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_model_face_gather_1);
  8706. this.appendDummyInput()
  8707. .appendField(Blockly.Msg.SYSTEM_CREATE_F_1)
  8708. .appendField("/root/user/model/recorded_face_features.py");
  8709. this.setInputsInline(false);
  8710. this.setPreviousStatement(true, null);
  8711. this.setNextStatement(true, null);
  8712. this.setColour("#ee783a");
  8713. this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title);
  8714. this.setHelpUrl("");
  8715. }
  8716. };
  8717. Blockly.Python['face_recognition_add'] = function (block) {
  8718. var value_class_input = "/root/user/model/recorded_face_features.py"
  8719. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8720. Blockly.Python.definitions_['v831_import_os'] = `import os`
  8721. Blockly.Python.definitions_['v831_import_json'] = `import json`
  8722. Blockly.Python.addVariable('ai_model_face_gather', `
  8723. def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
  8724. f = open(_path, "a")
  8725. f.write(_data + _sep)
  8726. f.close()
  8727. `, true);
  8728. var code = `FACERECGNIZER.add_user(CLASSNAMEFACELIST[len(FACERECGNIZER)], ${variable_name}[3])
  8729. FEATURES = FACERECGNIZER.features
  8730. try:
  8731. os.remove("${value_class_input}")
  8732. except:
  8733. pass
  8734. try:
  8735. _CREATE_TEXT_FILE_WITH_CONTENT("${value_class_input}", json.dumps(FACERECGNIZER.features), "\\r\\n")
  8736. except:
  8737. pass
  8738. `;
  8739. return code;
  8740. };
  8741. Blockly.Blocks['face_recognition_remove'] = {
  8742. init: function () {
  8743. this.appendDummyInput()
  8744. .appendField(Blockly.Msg.v831_setting_face_data_remove)
  8745. // .appendField(new Blockly.FieldVariable("save_face_data"), "varitem");
  8746. this.setInputsInline(false);
  8747. this.setPreviousStatement(true, null);
  8748. this.setNextStatement(true, null);
  8749. this.setColour("#ee783a");
  8750. this.setTooltip(Blockly.Msg.v831_setting_face_data_remove_title);
  8751. this.setHelpUrl("");
  8752. }
  8753. };
  8754. Blockly.Python['face_recognition_remove'] = function (block) {
  8755. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8756. Blockly.Python.definitions_['v831_import_os'] = `import os`
  8757. Blockly.Python.definitions_['v831_import_json'] = `import json`
  8758. Blockly.Python.addFunction('ai_model_face_gather', `
  8759. def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
  8760. f = open(_path, "a")
  8761. f.write(_data + _sep)
  8762. f.close()
  8763. `, true);
  8764. var code = `FACERECGNIZER.remove_user(CLASSNAMEFACELIST[len(FACERECGNIZER)-1])
  8765. FEATURES = FACERECGNIZER.features
  8766. try:
  8767. os.remove("/root/user/model/recorded_face_features.py")
  8768. except:
  8769. pass
  8770. try:
  8771. _CREATE_TEXT_FILE_WITH_CONTENT("/root/user/model/recorded_face_features.py", json.dumps(FACERECGNIZER.features), "\\r\\n")
  8772. except:
  8773. pass
  8774. `;
  8775. return code;
  8776. };
  8777. Blockly.Blocks['face_recognition_data_save_path'] = {
  8778. init: function () {
  8779. this.appendValueInput("class_input")
  8780. .setCheck(null)
  8781. .appendField(Blockly.Msg.ai_model_face_gather_1);
  8782. this.setPreviousStatement(true, null);
  8783. this.setNextStatement(true, null);
  8784. this.setColour("#ee783a");
  8785. this.setTooltip(Blockly.Msg.ai_model_face_gather_TOOLTIP);
  8786. this.setHelpUrl("");
  8787. }
  8788. };
  8789. Blockly.Python['face_recognition_data_save_path'] = function (block) {
  8790. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  8791. Blockly.Python.definitions_['v831_import_os'] = `import os`
  8792. Blockly.Python.definitions_['v831_import_json'] = `import json`
  8793. Blockly.Python.addVariable('ai_model_face_gather', `
  8794. def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
  8795. f = open(_path, "a")
  8796. f.write(_data + _sep)
  8797. f.close()
  8798. `, true);
  8799. var code = `try:
  8800. os.remove(${value_class_input})
  8801. except:
  8802. pass
  8803. try:
  8804. _CREATE_TEXT_FILE_WITH_CONTENT(${value_class_input}, json.dumps(FACERECGNIZER.features), "\\r\\n")
  8805. except:
  8806. pass
  8807. `;
  8808. return code;
  8809. };
  8810. Blockly.Blocks['face_recognition_data_load'] = {
  8811. init: function () {
  8812. this.appendDummyInput()
  8813. .appendField(Blockly.Msg.ai_model_face_data_load)
  8814. this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_CREATE_F_1)
  8815. .appendField("/root/user/model/recorded_face_features.py");
  8816. this.setPreviousStatement(true, null);
  8817. this.setNextStatement(true, null);
  8818. this.setColour("#ee783a");
  8819. this.setTooltip(Blockly.Msg.ai_model_face_data_load);
  8820. this.setHelpUrl("");
  8821. }
  8822. };
  8823. Blockly.Python['face_recognition_data_load'] = function (block) {
  8824. // var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  8825. Blockly.Python.definitions_['v831_import_json'] = `import json`
  8826. Blockly.Python.definitions_['load_face_data'] = `try:
  8827. with open("/root/user/model/recorded_face_features.py", "r") as file:
  8828. FACERECGNIZER.features = json.loads(file.read())
  8829. except:
  8830. pass
  8831. `
  8832. var code = ``;
  8833. return code;
  8834. };
  8835. Blockly.Blocks['face_recognition_data_results'] = {
  8836. init: function () {
  8837. this.appendDummyInput()
  8838. .appendField(Blockly.Msg.ai_models_from)
  8839. .appendField(new Blockly.FieldVariable("img_face_Recognizer"), "varitem")
  8840. .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_TYPE)
  8841. .appendField(new Blockly.FieldDropdown([
  8842. [Blockly.Msg.v831_model_face_name, "0"],
  8843. [Blockly.Msg.ai_models_face_model_confidence, "1"],
  8844. ]), "TYPE");
  8845. this.setInputsInline(false);
  8846. this.setOutput(true, null);
  8847. this.setColour("#ee783a");
  8848. this.setTooltip(Blockly.Msg.v831_face_recognition_result_title);
  8849. this.setHelpUrl("");
  8850. }
  8851. };
  8852. Blockly.Python['face_recognition_data_results'] = function (block) {
  8853. var type = block.getFieldValue('TYPE');
  8854. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8855. var code = `FACERECGNIZER.recognize(${variable_name})[${type}]
  8856. `;
  8857. return [code, Blockly.Python.ORDER_ATOMIC];
  8858. };
  8859. // 自学习
  8860. Blockly.Blocks['ai_model_self_learning_init'] = {
  8861. init: function () {
  8862. this.appendDummyInput()
  8863. .appendField(Blockly.Msg.ai_model_self_learning_init);
  8864. this.appendValueInput("class_input")
  8865. .setCheck(null)
  8866. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  8867. this.setInputsInline(false);
  8868. this.setPreviousStatement(true, null);
  8869. this.setNextStatement(true, null);
  8870. this.setColour("#ee783a");
  8871. this.setTooltip(Blockly.Msg.ai_model_self_learning_init);
  8872. this.setHelpUrl("");
  8873. }
  8874. };
  8875. Blockly.Python['ai_model_self_learning_init'] = function (block) {
  8876. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  8877. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8878. Blockly.Python.definitions_.import_self_learning_init = `
  8879. CLASSNUM = ${JSON.parse(value_class_input).length}
  8880. SAMPLENUM = ${JSON.parse(value_class_input).length * 5}
  8881. CLASSNAMELIST = ${value_class_input}
  8882. `
  8883. var code = ``;
  8884. return code;
  8885. };
  8886. Blockly.Blocks['ai_model_self_learning_load'] = {
  8887. init: function () {
  8888. this.appendDummyInput()
  8889. .appendField(Blockly.Msg.ai_model_self_learning_load);
  8890. this.setInputsInline(false);
  8891. this.setPreviousStatement(true, null);
  8892. this.setNextStatement(true, null);
  8893. this.setColour("#ee783a");
  8894. this.setTooltip(Blockly.Msg.ai_model_self_learning_load);
  8895. this.setHelpUrl("");
  8896. }
  8897. };
  8898. Blockly.Python['ai_model_self_learning_load'] = function (block) {
  8899. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8900. Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier`
  8901. Blockly.Python.definitions_.self_learing_load = `class Self_learn:
  8902. model = {
  8903. "param": "/root/preset/model/resnet18_1000_awnn.param",
  8904. "bin": "/root/preset/model/resnet18_1000_awnn.bin"
  8905. }
  8906. options = {
  8907. "model_type": "awnn",
  8908. "inputs": {
  8909. "input0": (224, 224, 3)
  8910. },
  8911. "outputs": {
  8912. "190": (1, 1, 512)
  8913. },
  8914. "mean": [127.5, 127.5, 127.5],
  8915. "norm": [0.0176, 0.0176, 0.0176],
  8916. }
  8917. class_num = CLASSNUM #学习类别
  8918. sample_num = SAMPLENUM #学习类别总数量
  8919. curr_class = 0
  8920. curr_sample = 0
  8921. def __init__(self):
  8922. self.m = nn.load(self.model, opt=self.options)
  8923. self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
  8924. SELFLEARN = Self_learn()
  8925. `
  8926. var code = '';
  8927. return code;
  8928. };
  8929. Blockly.Blocks['ai_model_self_learning_recognize_load'] = {
  8930. init: function () {
  8931. this.appendDummyInput()
  8932. .appendField(Blockly.Msg.ai_model_self_learning_recognize_load);
  8933. this.setInputsInline(false);
  8934. this.setPreviousStatement(true, null);
  8935. this.setNextStatement(true, null);
  8936. this.setColour("#ee783a");
  8937. this.setTooltip(Blockly.Msg.ai_model_self_learning_recognize_load);
  8938. this.setHelpUrl("");
  8939. }
  8940. };
  8941. Blockly.Python['ai_model_self_learning_recognize_load'] = function (block) {
  8942. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn`
  8943. Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier`
  8944. Blockly.Python.definitions_['v831_from_nn_import_load'] = `from maix.nn.app.classifier import load`
  8945. Blockly.Python.definitions_['v831_import_os'] = `import os`
  8946. Blockly.Python.definitions_.self_learing_load = `class Self_learn:
  8947. model = {
  8948. "param": "/root/preset/model/resnet18_1000_awnn.param",
  8949. "bin": "/root/preset/model/resnet18_1000_awnn.bin"
  8950. }
  8951. options = {
  8952. "model_type": "awnn",
  8953. "inputs": {
  8954. "input0": (224, 224, 3)
  8955. },
  8956. "outputs": {
  8957. "190": (1, 1, 512)
  8958. },
  8959. "mean": [127.5, 127.5, 127.5],
  8960. "norm": [0.0176, 0.0176, 0.0176],
  8961. }
  8962. class_num = CLASSNUM #学习类别
  8963. sample_num = SAMPLENUM #学习类别总数量
  8964. curr_class = 0
  8965. curr_sample = 0
  8966. def __init__(self):
  8967. if os.path.isfile("/root/module.bin"):
  8968. self.m = nn.load(self.model, opt=self.options)
  8969. self.classifier = load(self.m,"/root/module.bin")
  8970. else:
  8971. self.m = nn.load(self.model, opt=self.options)
  8972. self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224)
  8973. print("not have model!")
  8974. SELFLEARN = Self_learn()
  8975. `
  8976. var code = '';
  8977. return code;
  8978. };
  8979. Blockly.Blocks['ai_model_self_learning_add_class'] = {
  8980. init: function () {
  8981. this.appendDummyInput()
  8982. .appendField(Blockly.Msg.ai_model_self_learning_add_class_category + ',');
  8983. this.appendDummyInput()
  8984. .appendField(Blockly.Msg.ai_models_init_source)
  8985. .appendField(new Blockly.FieldVariable("img_self_learning"), "varitem");
  8986. this.setInputsInline(false);
  8987. this.setPreviousStatement(true, null);
  8988. this.setNextStatement(true, null);
  8989. this.setColour("#ee783a");
  8990. this.setTooltip(Blockly.Msg.ai_model_self_learning_add_class_category);
  8991. this.setHelpUrl("");
  8992. }
  8993. };
  8994. Blockly.Python['ai_model_self_learning_add_class'] = function (block) {
  8995. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  8996. var code = `SELFLEARN.classifier.add_class_img(${variable_name})
  8997. `;
  8998. return code;
  8999. };
  9000. Blockly.Blocks['ai_model_self_learning_make_data_set'] = {
  9001. init: function () {
  9002. this.appendDummyInput()
  9003. .appendField(Blockly.Msg.ai_model_self_learning_make_data_set);
  9004. this.appendDummyInput()
  9005. .appendField(Blockly.Msg.ai_models_init_source)
  9006. .appendField(new Blockly.FieldVariable("img_self_learning"), "varitem");
  9007. this.setInputsInline(false);
  9008. this.setPreviousStatement(true, null);
  9009. this.setNextStatement(true, null);
  9010. this.setColour("#ee783a");
  9011. this.setTooltip(Blockly.Msg.ai_model_self_learning_make_data_set);
  9012. this.setHelpUrl("");
  9013. }
  9014. };
  9015. Blockly.Python['ai_model_self_learning_make_data_set'] = function (block) {
  9016. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9017. var code = `for i in range(5):
  9018. SELFLEARN.classifier.add_sample_img(${variable_name})
  9019. `;
  9020. return code;
  9021. };
  9022. Blockly.Blocks['ai_model_self_learning_picture'] = {
  9023. init: function () {
  9024. this.appendDummyInput()
  9025. .appendField(Blockly.Msg.ai_model_self_learning_picture);
  9026. this.setInputsInline(false);
  9027. this.setPreviousStatement(true, null);
  9028. this.setNextStatement(true, null);
  9029. this.setColour("#ee783a");
  9030. this.setTooltip(Blockly.Msg.ai_model_self_learning_picture);
  9031. this.setHelpUrl("");
  9032. }
  9033. };
  9034. Blockly.Python['ai_model_self_learning_picture'] = function (block) {
  9035. var code = `SELFLEARN.classifier.train()
  9036. `;
  9037. return code;
  9038. }; Blockly.Blocks['ai_model_self_learning_save_modal'] = {
  9039. init: function () {
  9040. this.appendDummyInput()
  9041. .appendField(Blockly.Msg.ai_model_self_learning_save_modal);
  9042. this.setInputsInline(false);
  9043. this.setPreviousStatement(true, null);
  9044. this.setNextStatement(true, null);
  9045. this.setColour("#ee783a");
  9046. this.setTooltip(Blockly.Msg.ai_model_self_learning_save_modal);
  9047. this.setHelpUrl("");
  9048. }
  9049. };
  9050. Blockly.Python['ai_model_self_learning_save_modal'] = function (block) {
  9051. var code = `SELFLEARN.classifier.save("/root/module.bin")
  9052. `;
  9053. return code;
  9054. };
  9055. Blockly.Blocks['ai_model_self_learning_class_verification'] = {
  9056. init: function () {
  9057. this.appendDummyInput()
  9058. .appendField(Blockly.Msg.ai_model_self_learning_class_verification);
  9059. this.appendDummyInput()
  9060. .appendField(Blockly.Msg.ai_models_init_source)
  9061. .appendField(new Blockly.FieldVariable("img_self_learning"), "varitem");
  9062. this.setInputsInline(false);
  9063. this.setPreviousStatement(true, null);
  9064. this.setNextStatement(true, null);
  9065. this.setColour("#ee783a");
  9066. this.setTooltip(Blockly.Msg.ai_model_self_learning_class_verification);
  9067. this.setHelpUrl("");
  9068. }
  9069. };
  9070. Blockly.Python['ai_model_self_learning_class_verification'] = function (block) {
  9071. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9072. var code = `SELFLEARNidx, SELFLEARNdistance = SELFLEARN.classifier.predict(${variable_name})
  9073. `;
  9074. return code;
  9075. };
  9076. Blockly.Blocks['ai_model_self_learning_result'] = {
  9077. init: function () {
  9078. this.appendDummyInput()
  9079. .appendField(Blockly.Msg.ai_model_self_learning_result)
  9080. .appendField(new Blockly.FieldDropdown([
  9081. [Blockly.Msg.ai_model_self_learning_result_name, "X"],
  9082. [Blockly.Msg.ai_models_object_model_confidence, "Y"]
  9083. ]), "TYPE");;
  9084. this.setOutput(true, null);
  9085. this.setColour("#ee783a");
  9086. this.setTooltip(Blockly.Msg.ai_model_self_learning_result);
  9087. this.setHelpUrl("");
  9088. }
  9089. };
  9090. Blockly.Python['ai_model_self_learning_result'] = function (block) {
  9091. var type = block.getFieldValue('TYPE');
  9092. var code = '';
  9093. if (type == 'X') {
  9094. code = `CLASSNAMELIST[SELFLEARNidx]`
  9095. } else {
  9096. code = `100-SELFLEARNdistance`
  9097. }
  9098. return [code, Blockly.Python.ORDER_ATOMIC];
  9099. };
  9100. Blockly.Blocks['ai_model_customized_init_setup_definition'] = {
  9101. init: function () {
  9102. this.appendDummyInput()
  9103. .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" }));
  9104. this.appendDummyInput()
  9105. .appendField(Blockly.Msg.ai_model_customized_init_setup_definition);
  9106. this.setInputsInline(false);
  9107. this.setPreviousStatement(true, null);
  9108. this.setNextStatement(true, null);
  9109. this.setColour("#ee783a");
  9110. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP);
  9111. this.setHelpUrl("");
  9112. }
  9113. };
  9114. Blockly.Python['ai_model_customized_init_setup_definition'] = function (block) {
  9115. // TODO: Assemble Python into code variable.
  9116. Blockly.Python.includes_.import_amxisd = '' +
  9117. 'print("Clearing Cached Variables...", end="")\n' +
  9118. 'for name in dir(): \n' +
  9119. ' if not name.startswith(\'_\'): \n' +
  9120. ' del globals()[name]\n' +
  9121. 'print(" Done")\n' +
  9122. 'import KPU as kpu\n' +
  9123. 'kpu.memtest()\n' +
  9124. 'from Maix import utils\n' +
  9125. 'import gc\n' +
  9126. 'gc.enable()\n' +
  9127. 'utils.gc_heap_size()\n' +
  9128. '\n' +
  9129. '################# Done Init #################\n' +
  9130. '';
  9131. var code = '';
  9132. return code;
  9133. };
  9134. // 初始化serialcomm_read_setup_title_text_1
  9135. Blockly.Blocks['ai_model_index_custom_initialization_init_1'] = {
  9136. init: function () {
  9137. this.appendValueInput("class_input")
  9138. .setCheck(null)
  9139. .appendField(Blockly.Msg.serialcomm_read_setup_title_text_1)
  9140. // .appendField("DEGREE");
  9141. this.setPreviousStatement(true, null);
  9142. this.setNextStatement(true, null);
  9143. this.setColour("#ee783a");
  9144. this.setTooltip(Blockly.Msg.serialcomm_read_setup_title_text_1);
  9145. this.setHelpUrl('');
  9146. }
  9147. };
  9148. Blockly.Python.ai_model_index_custom_initialization_init_1 = function (block) {
  9149. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9150. Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  9151. var _code = value_class_input;
  9152. return _code;
  9153. }
  9154. // 自定义人脸识别
  9155. Blockly.Blocks['ai_model_face_model'] = {
  9156. init: function () {
  9157. this.appendDummyInput()
  9158. .appendField(Blockly.Msg.ai_model_face_setup);
  9159. this.setInputsInline(false);
  9160. this.setOutput(true, null);
  9161. this.setColour("#ee783a");
  9162. this.setTooltip(Blockly.Msg.ai_model_face_setup);
  9163. this.setHelpUrl("");
  9164. }
  9165. };
  9166. Blockly.Python.ai_model_face_model = function (block) {
  9167. Blockly.Python.definitions_['v831_import_time'] = `import time`
  9168. Blockly.Python.definitions_['v831_import_gc'] = `import gc`
  9169. Blockly.Python.includes_.import_amxisd = '' +
  9170. 'for name in dir(): \n' +
  9171. ' if not name.startswith(\'_\'): \n' +
  9172. ' del globals()[name]\n' +
  9173. 'gc.enable()\n' +
  9174. '\n' +
  9175. 'try:\n' +
  9176. ' from cocorobo import firmware_info\n' +
  9177. 'except BaseException as e:\n' +
  9178. ' print(str(e))\n' +
  9179. ' pass\n' +
  9180. '\n' +
  9181. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9182. ' from Maix import utils\n' +
  9183. ' utils.gc_heap_size(0xAF000)\n' +
  9184. 'else:\n' +
  9185. ' import utime\n' +
  9186. ' clock = None\n' +
  9187. ' ACCURACY = 85\n' +
  9188. '\n' +
  9189. 'task_fd = None\n' +
  9190. 'task_ld = None\n' +
  9191. 'task_fe = None\n' +
  9192. '\n' +
  9193. '';
  9194. var code = `
  9195. from fpioa_manager import *
  9196. from Maix import FPIOA, GPIO
  9197. _gp_side_buttons = [9, 10, 11]
  9198. FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)
  9199. FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)
  9200. FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)
  9201. _gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)
  9202. _gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)
  9203. _gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)
  9204. side_button_state = False
  9205. def run_face_compare(record_ftrs, feature):
  9206. scores = []
  9207. for j in range(len(record_ftrs)):
  9208. score = kpu.face_compare(record_ftrs[j], feature)
  9209. scores.append(score)
  9210. max_score = 0
  9211. # if int(str(firmware_info.ai()).split("-")[0]) < 2021:
  9212. # index = -1
  9213. # else:
  9214. # index = 0
  9215. index = -1
  9216. for k in range(len(scores)):
  9217. if max_score < scores[k]:
  9218. max_score = scores[k]
  9219. index = k
  9220. return [scores, max_score, index]
  9221. # print(scores)
  9222. `;
  9223. // var code = '';
  9224. return [code, Blockly.Python.ORDER_ATOMIC];
  9225. }
  9226. // 设置人脸识别名称
  9227. Blockly.Blocks['ai_model_face_setup'] = {
  9228. init: function () {
  9229. // this.appendDummyInput()
  9230. // .appendField(Blockly.Msg.ai_model_face_setup);
  9231. this.appendValueInput("class_input")
  9232. .setCheck(null)
  9233. .appendField(Blockly.Msg.ai_model_face_name);
  9234. this.setPreviousStatement(true, null);
  9235. this.setNextStatement(true, null);
  9236. this.setColour("#ee783a");
  9237. this.setTooltip(Blockly.Msg.ai_model_face_name.replace(":", ""));
  9238. this.setHelpUrl("");
  9239. }
  9240. };
  9241. Blockly.Python['ai_model_face_setup'] = function (block) {
  9242. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9243. var code = `
  9244. img_lcd = image.Image()
  9245. # img_face = image.Image(size=(128, 128))
  9246. collectNum = 0
  9247. record_ftrs = []
  9248. result = []
  9249. res_index = -1
  9250. # a = img_face.pix_to_ai()
  9251. names = ` + value_class_input + `
  9252. `;
  9253. return code;
  9254. };
  9255. Blockly.Blocks['ai_face_detection_model'] = {
  9256. init: function () {
  9257. this.appendDummyInput()
  9258. .appendField(Blockly.Msg.ai_face_detection_model);
  9259. this.setPreviousStatement(true, null);
  9260. this.setNextStatement(true, null);
  9261. this.setColour("#ee783a");
  9262. this.setTooltip(Blockly.Msg.ai_face_detection_model_TOOLTIP);
  9263. this.setHelpUrl("");
  9264. }
  9265. };
  9266. Blockly.Python['ai_face_detection_model'] = function (block) {
  9267. var code = '\n' +
  9268. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9269. ' task_fd = kpu.load("/sd/preset/models/face_reocgnition/FD.emodel") # 人脸检测模型\n' +
  9270. 'else:\n' +
  9271. ' task_fd = kpu.load("/sd/preset/models/face/v2/FaceDetection.emodel") # 0x300000)\n' +
  9272. 'anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n' +
  9273. 'a = kpu.init_yolo2(task_fd, 0.5, 0.3, 5, anchor)\n' +
  9274. '\n' +
  9275. '';
  9276. return code;
  9277. };
  9278. Blockly.Blocks['ai_face_point_detection_model'] = {
  9279. init: function () {
  9280. this.appendDummyInput()
  9281. .appendField(Blockly.Msg.ai_face_point_detection_model);
  9282. this.setPreviousStatement(true, null);
  9283. this.setNextStatement(true, null);
  9284. this.setColour("#ee783a");
  9285. this.setTooltip(Blockly.Msg.ai_face_point_detection_model_TOOLTIP);
  9286. this.setHelpUrl("");
  9287. }
  9288. };
  9289. Blockly.Python['ai_face_point_detection_model'] = function (block) {
  9290. Blockly.Python.definitions_.import_ai_face_point_detection_model = `
  9291. def run_five_points_inference(canvas, canvas_face, detected_face_rect):
  9292. a = canvas.draw_rectangle(detected_face_rect)
  9293. # Create face image from detection
  9294. face_cut = canvas.cut(detected_face_rect[0], detected_face_rect[1], detected_face_rect[2], detected_face_rect[3])
  9295. # Convert created face image to a dimension of 128x128
  9296. face_cut_128 = face_cut.resize(128, 128)
  9297. # 将正脸图像转为kpu格式, 便于后面的关键点模型的使用
  9298. a = face_cut_128.pix_to_ai()
  9299. # Get landmark for 5 points of the detected face
  9300. # 运行人脸5点关键点检测模型, 获取当前识别人脸的关键点数据
  9301. fmap = kpu.forward(task_ld, face_cut_128)
  9302. # print("fmap", fmap)
  9303. # 获取关键点预测结果
  9304. plist = fmap[:]
  9305. # print("plist", plist)
  9306. # Get position of left eye, then draw it on the canvas.
  9307. le = (i.x()+int(plist[0]*i.w() - 10), i.y()+int(plist[1]*i.h()))
  9308. a = canvas.draw_circle(le[0], le[1], 4)
  9309. # Get position of Right eye, then draw it on the canvas.
  9310. re = (i.x()+int(plist[2]*i.w()), i.y()+int(plist[3]*i.h()))
  9311. a = canvas.draw_circle(re[0], re[1], 4)
  9312. # Get position of Nose, then draw it on the canvas.
  9313. nose = (i.x()+int(plist[4]*i.w()), i.y()+int(plist[5]*i.h()))
  9314. a = canvas.draw_circle(nose[0], nose[1], 4)
  9315. # Get position of Left cheek, then draw it on the canvas.
  9316. lm = (i.x()+int(plist[6]*i.w()), i.y()+int(plist[7]*i.h()))
  9317. a = canvas.draw_circle(lm[0], lm[1], 4)
  9318. # Get position of Right cheek, then draw it on the canvas.
  9319. rm = (i.x()+int(plist[8]*i.w()), i.y()+int(plist[9]*i.h()))
  9320. a = canvas.draw_circle(rm[0], rm[1], 4)
  9321. # Align face to standard position
  9322. src_point = [le, re, nose, lm, rm]
  9323. '''
  9324. get_affine_transform() 函数, 根据获得的5点坐标与标准正脸坐标获取仿射变换矩阵
  9325. - 计算3个二维点对之间的仿射变换矩阵H(2行x3列),自由度为6。
  9326. - 仿射变换的原理就是根据源图像中一个三角形的顶点坐标和应用仿射变换之后的
  9327. - 目标图像中一个三角形的顶点坐标计算出一个变换矩阵,然后将这个矩阵应用到整个源图像。
  9328. src_point 为输入源图像中的三角形顶点坐标
  9329. dst_point 为输出目标图像中的三角形顶点坐标
  9330. Ref: https://zhuanlan.zhihu.com/p/142260846
  9331. '''
  9332. T = image.get_affine_transform(src_point, dst_point)
  9333. '''
  9334. warp_affine_ai() 函数, 对原始图片人脸图片进行仿射变换,变换为正脸图像
  9335. '''
  9336. a = image.warp_affine_ai(canvas, canvas_face, T)
  9337. '''
  9338. 将正脸图像转为kpu格式
  9339. '''
  9340. a = canvas_face.ai_to_pix()
  9341. # Recycle face_cut_128 in order to reduce memory usage
  9342. del(face_cut_128)
  9343. `;
  9344. var code = '\n' +
  9345. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9346. ' task_ld = kpu.load("/sd/preset/models/face_reocgnition/KP_chwise.emodel") # 人脸5点关键点检测模型\n' +
  9347. 'else:\n' +
  9348. ' task_ld = kpu.load("/sd/preset/models/face/v2/FaceLandmarkDetection.emodel")# 0x400000)\n' +
  9349. 'dst_point = [(44, 59), (84, 59), (64, 82), (47, 105),(81, 105)]\n' +
  9350. '\n' +
  9351. '';
  9352. return code;
  9353. };
  9354. Blockly.Blocks['ai_face_Vitter_eigenvalue_model'] = {
  9355. init: function () {
  9356. this.appendDummyInput()
  9357. .appendField(Blockly.Msg.ai_face_Vitter_eigenvalue_model);
  9358. this.setPreviousStatement(true, null);
  9359. this.setNextStatement(true, null);
  9360. this.setColour("#ee783a");
  9361. this.setTooltip(Blockly.Msg.ai_face_Vitter_eigenvalue_model_TOOLTIP);
  9362. this.setHelpUrl("");
  9363. }
  9364. };
  9365. Blockly.Python['ai_face_Vitter_eigenvalue_model'] = function (block) {
  9366. Blockly.Python.definitions_.import_ai_face_Vitter_eigenvalue_model = `
  9367. def run_fmap_calculation(canvas_face):
  9368. global fmap
  9369. # Calculate face feature vector from 'img_face', 计算正脸图片的196维特征值
  9370. fmap = kpu.forward(task_fe, canvas_face)
  9371. # 获取计算结果
  9372. feature = kpu.face_encode(fmap[:])
  9373. return feature
  9374. `;
  9375. var code = '\n' +
  9376. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9377. ' task_fe = kpu.load("/sd/preset/models/face_reocgnition/face_recognition_v4_2020_09_07.emodel") # 人脸196维特征值模型\n' +
  9378. ' kpu.set_outputs(task_fe, 0,1,1, 512)\n' +
  9379. 'else:\n' +
  9380. ' task_fe = kpu.load("/sd/preset/models/face/v2/FeatureExtraction.emodel")# 0x500000)\n' +
  9381. ' clock = time.clock()\n' +
  9382. '\n' +
  9383. '';
  9384. return code;
  9385. };
  9386. // 加载人脸检测模型,设置识别图像源
  9387. Blockly.Blocks['ai_model_face_start_recognition'] = {
  9388. init: function () {
  9389. this.appendDummyInput()
  9390. .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source)
  9391. .appendField(new Blockly.FieldVariable("img"), "varitem");
  9392. // this.appendDummyInput()
  9393. // .appendField(Blockly.Msg.ai_models_customized_init_type_set)
  9394. // .appendField(new Blockly.FieldDropdown([
  9395. // [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"],
  9396. // [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"]
  9397. // ]), "detect_type");
  9398. // this.appendStatementInput("NAME")
  9399. // .setCheck(null)
  9400. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  9401. this.setInputsInline(false);
  9402. this.setPreviousStatement(true, null);
  9403. this.setNextStatement(true, null);
  9404. this.setColour("#ee783a");
  9405. this.setTooltip(Blockly.Msg.ai_model_face_start_recognition_TOOLTIP);
  9406. this.setHelpUrl("");
  9407. }
  9408. }
  9409. Blockly.Python['ai_model_face_start_recognition'] = function (block) {
  9410. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  9411. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9412. // var dropdown_detect_type = block.getFieldValue('detect_type');
  9413. localStorage.setItem("ai_model_face_variable_name", variable_name);
  9414. var code = '' +
  9415. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9416. ' index = -1\n' +
  9417. 'else:\n' +
  9418. ' clock.tick()\n' +
  9419. 'a = img_face.pix_to_ai()\n' +
  9420. 'code = kpu.run_yolo2(task_fd, ' + variable_name + ')\n';
  9421. return code;
  9422. }
  9423. Blockly.Blocks['ai_models_customized_init_type_set'] = {
  9424. init: function () {
  9425. // this.appendDummyInput()
  9426. // .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source)
  9427. // .appendField(new Blockly.FieldVariable("img"), "varitem");
  9428. this.appendDummyInput()
  9429. .appendField(Blockly.Msg.ai_models_customized_init_type_set)
  9430. .appendField(new Blockly.FieldDropdown([
  9431. [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"],
  9432. [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"]
  9433. ]), "detect_type");
  9434. // this.appendStatementInput("NAME")
  9435. // .setCheck(null)
  9436. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  9437. this.setInputsInline(false);
  9438. this.setPreviousStatement(true, null);
  9439. this.setNextStatement(true, null);
  9440. this.setColour("#ee783a");
  9441. this.setTooltip(Blockly.Msg.ai_models_customized_init_type_set.replace(":", ""));
  9442. this.setHelpUrl("");
  9443. }
  9444. }
  9445. Blockly.Python['ai_models_customized_init_type_set'] = function (block) {
  9446. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  9447. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9448. var dropdown_detect_type = block.getFieldValue('detect_type');
  9449. // localStorage.setItem("ai_model_face_variable_name", variable_name);
  9450. if (dropdown_detect_type == "fast") {
  9451. // var break_string = " break\n";
  9452. var break_string = "break_string = True\n";
  9453. } else if (dropdown_detect_type == "slow") {
  9454. // var break_string = " # break\n";
  9455. var break_string = "break_string = False\n";
  9456. }
  9457. var code = '' +
  9458. break_string +
  9459. '\n';
  9460. return code;
  9461. }
  9462. Blockly.Blocks['ai_model_face_model_load_finish'] = {
  9463. init: function () {
  9464. this.appendDummyInput()
  9465. .appendField(Blockly.Msg.ai_model_face_model_load_finish);
  9466. this.setOutput(true, null);
  9467. this.setColour("#ee783a");
  9468. this.setTooltip(Blockly.Msg.ai_model_face_model_load_finish_TOOLTIP);
  9469. this.setHelpUrl("");
  9470. }
  9471. };
  9472. Blockly.Python['ai_model_face_model_load_finish'] = function (block) {
  9473. var code = 'code is not None';
  9474. return [code, Blockly.Python.ORDER_NONE];
  9475. };
  9476. Blockly.Blocks['ai_model_face_model_list'] = {
  9477. init: function () {
  9478. this.appendDummyInput()
  9479. .appendField(Blockly.Msg.ai_model_face_model_list);
  9480. this.setOutput(true, null);
  9481. this.setColour("#ee783a");
  9482. this.setTooltip(Blockly.Msg.ai_model_face_model_list_TOOLTIP);
  9483. this.setHelpUrl("");
  9484. }
  9485. };
  9486. Blockly.Python['ai_model_face_model_list'] = function (block) {
  9487. var code = 'code';
  9488. return [code, Blockly.Python.ORDER_NONE];
  9489. };
  9490. Blockly.Blocks['ai_model_face_detection_rectangle'] = {
  9491. init: function () {
  9492. this.appendDummyInput()
  9493. .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
  9494. this.appendDummyInput()
  9495. .appendField(Blockly.Msg.ai_models_from)
  9496. .appendField(new Blockly.FieldVariable("i"), "varitem")
  9497. .appendField(Blockly.Msg.ai_models_face_model_get)
  9498. .appendField(new Blockly.FieldDropdown([
  9499. [Blockly.Msg.ai_models_face_model_rect, "rect"],
  9500. [Blockly.Msg.ai_models_face_model_x, "X"],
  9501. [Blockly.Msg.ai_models_face_model_y, "Y"],
  9502. [Blockly.Msg.ai_models_face_model_w, "W"],
  9503. [Blockly.Msg.ai_models_face_model_h, "H"],
  9504. [Blockly.Msg.ai_models_face_model_x_center, "CX"],
  9505. [Blockly.Msg.ai_models_face_model_y_center, "CY"],
  9506. [Blockly.Msg.ai_models_face_model_count, "Number"],
  9507. [Blockly.Msg.ai_models_face_model_index, "Serial"],
  9508. [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]
  9509. ]), "TYPE");
  9510. this.setInputsInline(false);
  9511. this.setOutput(true, null);
  9512. this.setColour("#ee783a");
  9513. var thisBlock = this;
  9514. this.setTooltip(function () {
  9515. var mode = thisBlock.getFieldValue('TYPE');
  9516. var TOOLTIPS = {
  9517. 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect),
  9518. 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x),
  9519. 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y),
  9520. 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w),
  9521. 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h),
  9522. 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center),
  9523. 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center),
  9524. 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count),
  9525. 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index),
  9526. 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence)
  9527. };
  9528. return TOOLTIPS[mode];
  9529. });
  9530. this.setHelpUrl("");
  9531. }
  9532. };
  9533. Blockly.Python.ai_model_face_detection_rectangle = function (block) {
  9534. var type = block.getFieldValue('TYPE');
  9535. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9536. var _code = "";
  9537. if (type == "rect") {
  9538. _code = variable_name + ".rect()";
  9539. } else if (type == "X") {
  9540. _code = variable_name + ".x()";
  9541. } else if (type == "Y") {
  9542. _code = variable_name + ".y()";
  9543. } else if (type == "W") {
  9544. _code = variable_name + ".w()";
  9545. } else if (type == "H") {
  9546. _code = variable_name + ".h()";
  9547. } else if (type == "Number") {
  9548. _code = variable_name + ".objnum()";
  9549. } else if (type == "Serial") {
  9550. _code = variable_name + ".index()";
  9551. } else if (type == "Confidence") {
  9552. _code = variable_name + ".value()";
  9553. } else if (type == "CX") {
  9554. _code = variable_name + ".x()+(" + variable_name + ".w()/2)";
  9555. } else if (type == "CY") {
  9556. _code = variable_name + ".y()+(" + variable_name + ".h()/2)";
  9557. }
  9558. return [_code, Blockly.Python.ORDER_ATOMIC];
  9559. };
  9560. Blockly.Blocks['ai_model_face_load_point_detection_model'] = {
  9561. init: function () {
  9562. this.appendDummyInput()
  9563. .appendField(Blockly.Msg.ai_model_face_load_point_detection_model + Blockly.Msg.ai_models_customized_init_setup_source)
  9564. .appendField(new Blockly.FieldVariable("img"), "varitem");
  9565. this.appendDummyInput()
  9566. .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_1)
  9567. .appendField(new Blockly.FieldVariable("img_face"), "varitem1");
  9568. this.appendValueInput("class_input")
  9569. .setCheck(null)
  9570. .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_2);
  9571. this.setInputsInline(false);
  9572. this.setPreviousStatement(true, null);
  9573. this.setNextStatement(true, null);
  9574. this.setColour("#ee783a");
  9575. this.setTooltip(Blockly.Msg.ai_model_face_load_point_detection_model_TOOLTIP);
  9576. this.setHelpUrl("");
  9577. }
  9578. }
  9579. Blockly.Python.ai_model_face_load_point_detection_model = function (block) {
  9580. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9581. var variable_name_1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
  9582. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9583. var _code = "run_five_points_inference(" + variable_name + ", " + variable_name_1 + ", " + value_class_input + ")\n";
  9584. return _code;
  9585. };
  9586. Blockly.Blocks['ai_model_face_gather'] = {
  9587. init: function () {
  9588. this.appendDummyInput()
  9589. .appendField(Blockly.Msg.ai_model_face_gather);
  9590. this.appendValueInput("class_input")
  9591. .setCheck(null)
  9592. .appendField(Blockly.Msg.ai_model_face_gather_1);
  9593. this.setPreviousStatement(true, null);
  9594. this.setNextStatement(true, null);
  9595. this.setColour("#ee783a");
  9596. this.setTooltip(Blockly.Msg.ai_model_face_gather_TOOLTIP);
  9597. this.setHelpUrl("");
  9598. }
  9599. };
  9600. Blockly.Python['ai_model_face_gather'] = function (block) {
  9601. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  9602. Blockly.Python.definitions_['v831_import_os'] = `import os`
  9603. Blockly.Python.addVariable('ai_model_face_gather', `
  9604. def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):
  9605. f = open(_path, 'a')
  9606. f.write(_data + _sep)
  9607. f.close()
  9608. `, true);
  9609. var code = '' +
  9610. '# start to gather faces\n' +
  9611. 'result = run_face_compare(record_ftrs, feature)\n' +
  9612. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021 and collectNum < len(names):\n' +
  9613. ' if(len(names) > result[2]):\n' +
  9614. ' if result[1] <= 80:\n' +
  9615. ' 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' +
  9616. ' if _gp_side_b.value() == True and side_button_state == False:\n' +
  9617. ' record_ftrs.append(feature)\n' +
  9618. ' collectNum = collectNum + 1\n' +
  9619. ' side_button_state = True\n' +
  9620. ' elif _gp_side_b.value() == False and side_button_state == True:\n' +
  9621. ' side_button_state = False\n' +
  9622. 'elif int(str(firmware_info.ai()).split("-")[0]) >= 2021 and collectNum < len(names):\n' +
  9623. ' if(len(names) > result[2]):\n' +
  9624. ' if result[1] <= ACCURACY:\n' +
  9625. ' 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' +
  9626. ' if _gp_side_b.value() == True and side_button_state == False:\n' +
  9627. ' record_ftrs.append(feature)\n' +
  9628. ' collectNum = collectNum + 1\n' +
  9629. ' side_button_state = True\n' +
  9630. ' elif _gp_side_b.value() == False and side_button_state == True:\n' +
  9631. ' side_button_state = False\n' +
  9632. 'if collectNum >= len(names):\n' +
  9633. ' try:\n' +
  9634. ' os.remove("/sd/user/' + value_class_input + '.py")\n' +
  9635. ' except:\n' +
  9636. ' pass\n' +
  9637. ' all = {}\n' +
  9638. ' try:\n' +
  9639. ' for j in range(len(names)):\n' +
  9640. ' all[names[j]] = record_ftrs[j]\n' +
  9641. ' _CREATE_TEXT_FILE_WITH_CONTENT("/sd/user/' + value_class_input + '.py", "all =" + str(all), "\\r\\n")\n' +
  9642. '\n' +
  9643. ' except:\n' +
  9644. ' pass\n' +
  9645. // 'if break_string == True:\n' +
  9646. // ' break\n' +
  9647. '\n';
  9648. return code;
  9649. };
  9650. Blockly.Blocks['ai_model_face_gather_num_judge'] = {
  9651. init: function () {
  9652. this.appendDummyInput()
  9653. .appendField(Blockly.Msg.ai_model_face_gather_num_judge);
  9654. this.setOutput(true, null);
  9655. this.setColour("#ee783a");
  9656. this.setTooltip(Blockly.Msg.ai_model_face_gather_num_judge_TOOLTIP);
  9657. this.setHelpUrl("");
  9658. }
  9659. };
  9660. Blockly.Python['ai_model_face_gather_num_judge'] = function (block) {
  9661. var code = 'collectNum >= len(names)';
  9662. return [code, Blockly.Python.ORDER_NONE];
  9663. };
  9664. Blockly.Blocks['ai_model_face_data_load'] = {
  9665. init: function () {
  9666. this.appendDummyInput()
  9667. .appendField(Blockly.Msg.ai_model_face_data_load);
  9668. this.appendValueInput("class_input")
  9669. .setCheck(null)
  9670. .appendField(Blockly.Msg.ai_model_face_data_load_1);
  9671. this.setPreviousStatement(true, null);
  9672. this.setNextStatement(true, null);
  9673. this.setColour("#ee783a");
  9674. this.setTooltip(Blockly.Msg.ai_model_face_data_load_TOOLTIP);
  9675. this.setHelpUrl("");
  9676. }
  9677. };
  9678. Blockly.Python['ai_model_face_data_load'] = function (block) {
  9679. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  9680. Blockly.Python.addVariable('ai_model_face_data_load', `
  9681. try:
  9682. import user.${value_class_input} as recorded_face_features
  9683. except:
  9684. pass
  9685. `, true);
  9686. var code = '' +
  9687. '# load faces data\n' +
  9688. 'all = {}\n' +
  9689. 'record_ftrs = []\n' +
  9690. 'collectNum = len(names)\n' +
  9691. 'try:\n' +
  9692. ' all = recorded_face_features.all\n' +
  9693. ' for j in range(len(names)):\n' +
  9694. ' record_ftrs.append(all[names[j]])\n' +
  9695. '\n' +
  9696. 'except:\n' +
  9697. ' pass\n' +
  9698. '\n';
  9699. // 'all = recorded_face_features.all\n' +
  9700. return code;
  9701. };
  9702. Blockly.Blocks['ai_model_face_recognition'] = {
  9703. init: function () {
  9704. this.appendDummyInput()
  9705. .appendField(Blockly.Msg.ai_model_face_recognition);
  9706. this.setPreviousStatement(true, null);
  9707. this.setNextStatement(true, null);
  9708. this.setColour("#ee783a");
  9709. this.setTooltip(Blockly.Msg.ai_model_face_recognition_TOOLTIP);
  9710. this.setHelpUrl("");
  9711. }
  9712. };
  9713. Blockly.Python['ai_model_face_recognition'] = function (block) {
  9714. var code = '' +
  9715. 'if collectNum >= len(names):\n' +
  9716. ' result = run_face_compare(record_ftrs, feature)\n' +
  9717. ' if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9718. ' if(len(names) > result[2]):\n' +
  9719. ' if result[1] > 80:\n' +
  9720. ' 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' +
  9721. ' else:\n' +
  9722. ' if(len(names) > result[2]):\n' +
  9723. ' if result[1] > ACCURACY:\n' +
  9724. ' 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' +
  9725. ' res_index = result[2]\n' +
  9726. '\n' +
  9727. 'if break_string == True:\n' +
  9728. ' break\n' +
  9729. '\n' +
  9730. '';
  9731. return code;
  9732. };
  9733. Blockly.Blocks['ai_model_face_recognition_get_result'] = {
  9734. init: function () {
  9735. this.appendDummyInput()
  9736. .appendField(Blockly.Msg.ai_model_face_recognition_get_result);
  9737. // this.appendStatementInput("NAME")
  9738. // .setCheck(null)
  9739. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  9740. this.setOutput(true);
  9741. this.setColour("#ee783a");
  9742. this.setTooltip(Blockly.Msg.ai_model_face_recognition_get_result_TOOLTIP);
  9743. this.setHelpUrl("");
  9744. }
  9745. };
  9746. Blockly.Python['ai_model_face_recognition_get_result'] = function (block) {
  9747. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  9748. var code = '(len(names) > result[2] and collectNum >= len(names))';
  9749. // statements_name +
  9750. // 'if break_string == True:\n' +
  9751. // ' break\n' +
  9752. // 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9753. // ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' +
  9754. // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' +
  9755. // ' gc.collect()\n' +
  9756. // ' # kpu.memtest()\n' +
  9757. // 'else:\n' +
  9758. // ' fps = clock.fps()\n' +
  9759. // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' +
  9760. // ' gc.collect()\n' +
  9761. // ' # kpu.memtest()\n' +
  9762. // '\n' +
  9763. // '';
  9764. return [code, Blockly.Python.ORDER_NONE];
  9765. };
  9766. Blockly.Blocks['ai_model_getfaceresult'] = {
  9767. init: function () {
  9768. this.appendDummyInput()
  9769. .appendField(Blockly.Msg.ai_model_getface);
  9770. this.setOutput(true, null);
  9771. this.setColour("#ee783a");
  9772. this.setTooltip(Blockly.Msg.ai_model_getface_TOOLTIP);
  9773. this.setHelpUrl("");
  9774. }
  9775. };
  9776. Blockly.Python['ai_model_getfaceresult'] = function (block) {
  9777. // TODO: Assemble Python into code variable.
  9778. var code = 'names[res_index] if (res_index != -1 and len(names) > res_index and collectNum >= len(names)) else ""';
  9779. // TODO: Change ORDER_NONE to the correct strength.
  9780. return [code, Blockly.Python.ORDER_NONE];
  9781. };
  9782. Blockly.Blocks['ai_model_show_face'] = {
  9783. init: function () {
  9784. this.appendDummyInput()
  9785. .appendField(Blockly.Msg.ai_model_show_face);
  9786. this.setPreviousStatement(true, null);
  9787. this.setNextStatement(true, null);
  9788. this.setColour("#ee783a");
  9789. this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP);
  9790. this.setHelpUrl("");
  9791. }
  9792. };
  9793. Blockly.Python['ai_model_show_face'] = function (block) {
  9794. var code = '' +
  9795. // ' if break_string == True:\n' +
  9796. // ' break\n' +
  9797. 'lcd_draw_string(img, 240, 0, (str(num)), color = (255, 102, 0), scale = 2, mono_space = False)\n' +
  9798. 'if isCollect == 0:\n' +
  9799. ' lcd_draw_string(img, 40, 0, "按A识别上次样本", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  9800. ' lcd_draw_string(img, 40, 16, "按C重新拍摄", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  9801. 'elif isCollect == 1:\n' +
  9802. ' lcd_draw_string(img, 40, 0, "开始识别", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  9803. 'elif isCollect == 2:\n' +
  9804. ' lcd_draw_string(img, 40, 0, "开始采集人脸模板数据", color = (255, 0, 0), scale = 1, mono_space = False)\n' +
  9805. 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' +
  9806. ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' +
  9807. ' lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' +
  9808. ' gc.collect()\n' +
  9809. 'else:\n' +
  9810. ' fps = clock.fps()\n' +
  9811. ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' +
  9812. ' gc.collect()\n' +
  9813. '';
  9814. return code;
  9815. };
  9816. Blockly.Blocks['ai_model_class_setup'] = {
  9817. init: function () {
  9818. // this.appendDummyInput()
  9819. // .appendField(Blockly.Msg.ai_model_class_setup);
  9820. this.appendValueInput("class_input")
  9821. .setCheck(null)
  9822. .appendField(Blockly.Msg.ai_model_class_name);
  9823. this.setPreviousStatement(true, null);
  9824. this.setNextStatement(true, null);
  9825. this.setColour("#ee783a");
  9826. this.setTooltip(Blockly.Msg.ai_model_class_name.replace(":", ""));
  9827. this.setHelpUrl("");
  9828. }
  9829. };
  9830. Blockly.Python['ai_model_class_setup'] = function (block) {
  9831. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  9832. var code = `
  9833. ############### config #################
  9834. class_names = ` + value_class_input + `
  9835. class_num = len(class_names)
  9836. sample_num = len(class_names) * 5
  9837. THRESHOLD = 11
  9838. board_cube = 0
  9839. button_state = False
  9840. FPIOA().set_function(10, FPIOA.GPIO1)
  9841. key1 = GPIO(GPIO.GPIO1, GPIO.IN, GPIO.PULL_UP)
  9842. `;
  9843. return code;
  9844. };
  9845. Blockly.Blocks['ai_class_model'] = {
  9846. init: function () {
  9847. this.appendDummyInput()
  9848. .appendField(Blockly.Msg.ai_class_model);
  9849. this.setPreviousStatement(true, null);
  9850. this.setNextStatement(true, null);
  9851. this.setColour("#ee783a");
  9852. this.setTooltip(Blockly.Msg.ai_class_model_TOOLTIP);
  9853. this.setHelpUrl("");
  9854. }
  9855. };
  9856. Blockly.Python['ai_class_model'] = function (block) {
  9857. Blockly.Python.addVariable('ai_class_model', `
  9858. try:
  9859. del model
  9860. except Exception:
  9861. pass
  9862. try:
  9863. del classifier
  9864. except Exception:
  9865. pass
  9866. gc.collect()
  9867. cap_num = 0
  9868. train_status = 0
  9869. last_cap_time = 0
  9870. last_btn_status = 0
  9871. res_index = -1
  9872. is_save = 0
  9873. `)
  9874. var code = 'model = kpu.load("/sd/preset/models/object_classifier.emodel")\n';
  9875. return code;
  9876. };
  9877. Blockly.Blocks['ai_class_model_cluster'] = {
  9878. init: function () {
  9879. this.appendDummyInput()
  9880. .appendField(Blockly.Msg.ai_class_model_cluster);
  9881. this.setPreviousStatement(true, null);
  9882. this.setNextStatement(true, null);
  9883. this.setColour("#ee783a");
  9884. this.setTooltip(Blockly.Msg.ai_class_model_cluster_TOOLTIP);
  9885. this.setHelpUrl("");
  9886. }
  9887. };
  9888. Blockly.Python['ai_class_model_cluster'] = function (block) {
  9889. // Blockly.Python.addVariable('ai_class_model_cluster', `
  9890. // `)
  9891. var code = 'classifier = kpu.classifier(model, class_num, sample_num)\n';
  9892. return code;
  9893. };
  9894. Blockly.Blocks['ai_model_class_start_load'] = {
  9895. init: function () {
  9896. this.appendDummyInput()
  9897. .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  9898. .appendField(new Blockly.FieldVariable("img"), "varitem");
  9899. this.appendDummyInput()
  9900. .appendField(Blockly.Msg.ai_model_class_start_load);
  9901. // this.appendStatementInput("NAME")
  9902. // .setCheck(null)
  9903. // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do);
  9904. this.setInputsInline(false);
  9905. this.setPreviousStatement(true, null);
  9906. this.setNextStatement(true, null);
  9907. this.setColour("#ee783a");
  9908. this.setTooltip(Blockly.Msg.ai_model_class_start_load_TOOLTIP);
  9909. this.setHelpUrl("");
  9910. }
  9911. }
  9912. Blockly.Python['ai_model_class_start_load'] = function (block) {
  9913. // var statements_name = Blockly.Python.statementToCode(block, 'NAME');
  9914. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  9915. localStorage.setItem("ai_model_class_start_load", variable_name);
  9916. var code = '' +
  9917. 'if board_cube:\n' +
  9918. ' ' + variable_name + ' = ' + variable_name + '.rotation_corr(z_rotation=90)\n' +
  9919. ' ' + variable_name + '.pix_to_ai()\n' +
  9920. '\n';
  9921. return code;
  9922. }
  9923. Blockly.Blocks['ai_model_class_gather'] = {
  9924. init: function () {
  9925. this.appendDummyInput()
  9926. .appendField(Blockly.Msg.ai_model_class_gather);
  9927. this.setPreviousStatement(true, null);
  9928. this.setNextStatement(true, null);
  9929. this.setColour("#ee783a");
  9930. this.setTooltip(Blockly.Msg.ai_model_class_gather_TOOLTIP);
  9931. this.setHelpUrl("");
  9932. }
  9933. };
  9934. Blockly.Python['ai_model_class_gather'] = function (block) {
  9935. var code = '' +
  9936. '# capture img\n' +
  9937. 'if train_status == 0:\n' +
  9938. ' if key1.value() == 0 and last_btn_status == 1:\n' +
  9939. ' #time.sleep_ms(30)\n' +
  9940. ' #if key1.value() == 1 and (last_btn_status == 1) and (time.ticks_ms() - last_cap_time > 500):\n' +
  9941. ' last_btn_status = 0\n' +
  9942. ' last_cap_time = time.ticks_ms()\n' +
  9943. ' if cap_num < class_num:\n' +
  9944. ' index = classifier.add_class_img(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
  9945. ' cap_num += 1\n' +
  9946. ' elif cap_num < class_num + sample_num:\n' +
  9947. ' index = classifier.add_sample_img(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
  9948. ' cap_num += 1\n' +
  9949. ' #else:\n' +
  9950. ' # ' + localStorage.getItem("ai_model_class_start_load") + ' = draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 2, 200, "release boot key please", color=lcd.WHITE,scale=1, bg=lcd.RED)\n' +
  9951. ' else:\n' +
  9952. ' #time.sleep_ms(30)\n' +
  9953. ' if key1.value() == 1 and (last_btn_status == 0):\n' +
  9954. ' last_btn_status = 1\n' +
  9955. ' if cap_num < class_num:\n' +
  9956. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(-2,0, len("press right key to cap "+class_names[cap_num])*10+8 , 24, fill=True, color=lcd.RED)\n' +
  9957. ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 0, 2, "press right key to cap "+class_names[cap_num], color=lcd.WHITE,scale=1,mono_space=False)\n' +
  9958. ' elif cap_num < class_num + sample_num:\n' +
  9959. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(-2,0, len("right key to cap {} {}".format(class_names[(cap_num-class_num) // 5],5 if (cap_num-class_num+1) % 5 == 0 else (cap_num-class_num+1) % 5))*10+8 , 24, fill=True, color=lcd.RED)\n' +
  9960. ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 0, 2, "right key to cap {} {}".format(class_names[(cap_num-class_num) // 5],5 if (cap_num-class_num+1) % 5 == 0 else (cap_num-class_num+1) % 5), color=lcd.WHITE,scale=1,mono_space=False)\n' +
  9961. '\n';
  9962. return code;
  9963. };
  9964. Blockly.Blocks['ai_model_class_data_load'] = {
  9965. init: function () {
  9966. this.appendDummyInput()
  9967. .appendField(Blockly.Msg.ai_model_class_data_load);
  9968. this.appendValueInput("class_input")
  9969. .setCheck(null)
  9970. .appendField(Blockly.Msg.ai_model_class_data_load_1);
  9971. this.setPreviousStatement(true, null);
  9972. this.setNextStatement(true, null);
  9973. this.setColour("#ee783a");
  9974. this.setTooltip(Blockly.Msg.ai_model_class_data_load_TOOLTIP);
  9975. this.setHelpUrl("");
  9976. }
  9977. };
  9978. Blockly.Python['ai_model_class_data_load'] = function (block) {
  9979. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  9980. var code = '' +
  9981. 'try:\n' +
  9982. ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' +
  9983. ' f=open(saved_path,"r")\n' +
  9984. ' classifier, class_num, sample_num = kpu.classifier.load(model, saved_path)\n' +
  9985. ' train_status = 1\n' +
  9986. 'except:\n' +
  9987. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0, 0, 240,20, fill=True, color=(0,0,0))\n' +
  9988. ' 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' +
  9989. '\n';
  9990. return code;
  9991. };
  9992. Blockly.Blocks['ai_model_class_gather_load_finish'] = {
  9993. init: function () {
  9994. this.appendDummyInput()
  9995. .appendField(Blockly.Msg.ai_model_class_gather_load_finish);
  9996. this.setOutput(true, null);
  9997. this.setColour("#ee783a");
  9998. this.setTooltip(Blockly.Msg.ai_model_class_gather_load_finish_TOOLTIP);
  9999. this.setHelpUrl("");
  10000. }
  10001. };
  10002. Blockly.Python['ai_model_class_gather_load_finish'] = function (block) {
  10003. var code = 'train_status == 0';
  10004. return [code, Blockly.Python.ORDER_NONE];
  10005. };
  10006. Blockly.Blocks['ai_model_class_cluster_train'] = {
  10007. init: function () {
  10008. this.appendDummyInput()
  10009. .appendField(Blockly.Msg.ai_model_class_cluster_train);
  10010. this.appendValueInput("class_input")
  10011. .setCheck(null)
  10012. .appendField(Blockly.Msg.ai_model_class_cluster_train_1);
  10013. this.setPreviousStatement(true, null);
  10014. this.setNextStatement(true, null);
  10015. this.setColour("#ee783a");
  10016. this.setTooltip(Blockly.Msg.ai_model_class_cluster_train_TOOLTIP);
  10017. this.setHelpUrl("");
  10018. }
  10019. };
  10020. Blockly.Python['ai_model_class_cluster_train'] = function (block) {
  10021. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', '');
  10022. var code = '' +
  10023. 'if cap_num >= class_num + sample_num and train_status == 0:\n' +
  10024. ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(58,98, len("training...")*10+8 , 24, fill=True, color=lcd.RED)\n' +
  10025. ' ' + 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' +
  10026. ' lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
  10027. ' try:\n' +
  10028. ' classifier.train()\n' +
  10029. ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' +
  10030. ' f=open(saved_path,"r")\n' +
  10031. ' os.remove("/sd/user/' + value_class_input + '.classifier")\n' +
  10032. ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' +
  10033. ' except:\n' +
  10034. ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' +
  10035. ' time.sleep(2)\n' +
  10036. ' train_status = 1\n' +
  10037. '\n';
  10038. return code;
  10039. };
  10040. Blockly.Blocks['ai_model_class_recognition'] = {
  10041. init: function () {
  10042. this.appendDummyInput()
  10043. .appendField(Blockly.Msg.ai_model_class_recognition);
  10044. this.setPreviousStatement(true, null);
  10045. this.setNextStatement(true, null);
  10046. this.setColour("#ee783a");
  10047. this.setTooltip(Blockly.Msg.ai_model_class_recognition_TOOLTIP);
  10048. this.setHelpUrl("");
  10049. }
  10050. };
  10051. Blockly.Python['ai_model_class_recognition'] = function (block) {
  10052. var code = '' +
  10053. '# predict\n' +
  10054. 'if train_status == 1:\n' +
  10055. ' res_index = -1\n' +
  10056. ' try:\n' +
  10057. ' res_index, min_dist = classifier.predict(' + localStorage.getItem("ai_model_class_start_load") + ')\n' +
  10058. ' except Exception as e:\n' +
  10059. ' print("predict err:", e)\n' +
  10060. ' if res_index >= 0 and min_dist < THRESHOLD :\n' +
  10061. ' ' + 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' +
  10062. ' ' + 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' +
  10063. ' else:\n' +
  10064. ' ' + 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' +
  10065. ' ' + 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' +
  10066. '\n';
  10067. return code;
  10068. };
  10069. Blockly.Blocks['ai_model_show_class'] = {
  10070. init: function () {
  10071. this.appendDummyInput()
  10072. .appendField(Blockly.Msg.ai_model_show_face);
  10073. this.setPreviousStatement(true, null);
  10074. this.setNextStatement(true, null);
  10075. this.setColour("#ee783a");
  10076. this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP);
  10077. this.setHelpUrl("");
  10078. }
  10079. };
  10080. Blockly.Python['ai_model_show_class'] = function (block) {
  10081. var code = '' +
  10082. '' + localStorage.getItem("ai_model_class_start_load") + ' = ' + localStorage.getItem("ai_model_class_start_load") + '.cut(0,0,240,240)\n' +
  10083. 'lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ', oft=(0,0))\n' +
  10084. '';
  10085. return code;
  10086. };
  10087. Blockly.Blocks['ai_model_customized_init_setup'] = {
  10088. init: function () {
  10089. this.appendDummyInput()
  10090. .appendField(Blockly.Msg.ai_models_customized_init_setup_title);
  10091. this.appendDummyInput()
  10092. .appendField(Blockly.Msg.ai_models_customized_init_setup_path)
  10093. .appendField(new Blockly.FieldTextInput("/root/preset/model/yolov2_int8"), "model_path");
  10094. this.appendValueInput("class_input")
  10095. .setCheck(null)
  10096. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  10097. this.setPreviousStatement(true, null);
  10098. this.setNextStatement(true, null);
  10099. this.setColour("#ee783a");
  10100. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_TOOLTIP);
  10101. this.setHelpUrl("");
  10102. }
  10103. };
  10104. Blockly.Python['ai_model_customized_init_setup'] = function (block) {
  10105. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10106. var text_model_path = block.getFieldValue('model_path');
  10107. Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn";
  10108. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  10109. let code = `class Yolo:
  10110. labels = ${value_class_input}
  10111. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  10112. m = {
  10113. "param": "${text_model_path}.param",
  10114. "bin": "${text_model_path}.bin"
  10115. }
  10116. options = {
  10117. "model_type": "awnn",
  10118. "inputs": {
  10119. "input0": (224, 224, 3)
  10120. },
  10121. "outputs": {
  10122. "output0": (7, 7, (1+4+len(labels))*5)
  10123. },
  10124. "mean": [127.5, 127.5, 127.5],
  10125. "norm": [0.0078125, 0.0078125, 0.0078125],
  10126. }
  10127. def __init__(self):
  10128. from maix import nn
  10129. from maix.nn import decoder
  10130. self.model = nn.load(self.m, opt=self.options)
  10131. self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
  10132. def __del__(self):
  10133. del self.model
  10134. del self.decoder
  10135. Yolo = Yolo()
  10136. `;
  10137. return code;
  10138. };
  10139. Blockly.Blocks['ai_model_customized_load_setup'] = {
  10140. init: function () {
  10141. this.appendDummyInput()
  10142. .appendField(Blockly.Msg.ai_model_customized_load_setup_title);
  10143. this.appendDummyInput()
  10144. .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  10145. .appendField(new Blockly.FieldVariable("img_modelrecognition"), "varitem");
  10146. this.setPreviousStatement(true, null);
  10147. this.setNextStatement(true, null);
  10148. this.setColour("#ee783a");
  10149. this.setTooltip(Blockly.Msg.ai_model_customized_load_setup_TOOLTIP);
  10150. this.setHelpUrl("");
  10151. }
  10152. };
  10153. Blockly.Python['ai_model_customized_load_setup'] = function (block) {
  10154. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10155. var code = `out = Yolo.model.forward(${variable_name}, quantize=True, layout="hwc")
  10156. boxes, probs = Yolo.decoder.run(out, nms=0.3, threshold=0.3, img_size=(224, 224))
  10157. if len(boxes):
  10158. for boxesi, box in enumerate(boxes):
  10159. boxes[boxesi].append(probs[boxesi])
  10160. `;
  10161. return code;
  10162. };
  10163. Blockly.Blocks['ai_model_customized_if_got'] = {
  10164. init: function () {
  10165. this.appendDummyInput()
  10166. .appendField(Blockly.Msg.ai_models_customized_if_got);
  10167. this.setOutput(true, null);
  10168. this.setColour("#ee783a");
  10169. this.setTooltip(Blockly.Msg.ai_model_customized_if_got_TOOLTIP);
  10170. this.setHelpUrl("");
  10171. }
  10172. };
  10173. Blockly.Python['ai_model_customized_if_got'] = function (block) {
  10174. // TODO: Assemble Python into code variable.
  10175. var code = 'len(boxes)';
  10176. // TODO: Change ORDER_NONE to the correct strength.
  10177. return [code, Blockly.Python.ORDER_NONE];
  10178. };
  10179. Blockly.Blocks['ai_model_customized_attribute'] = {
  10180. init: function () {
  10181. this.appendDummyInput()
  10182. .appendField(Blockly.Msg.ai_model_customized_attribute);
  10183. this.setOutput(true, null);
  10184. this.setColour("#ee783a");
  10185. this.setTooltip(Blockly.Msg.ai_model_customized_attribute_TOOLTIP);
  10186. this.setHelpUrl("");
  10187. }
  10188. };
  10189. Blockly.Python['ai_model_customized_attribute'] = function (block) {
  10190. var code = 'boxes';
  10191. return [code, Blockly.Python.ORDER_NONE];
  10192. };
  10193. Blockly.Blocks['ai_model_customized_get_result'] = {
  10194. init: function () {
  10195. this.appendDummyInput()
  10196. .appendField(Blockly.Msg.ai_models_from)
  10197. .appendField(new Blockly.FieldVariable("i"), "varitem")
  10198. .appendField(Blockly.Msg.ai_models_customized_get_result_any)
  10199. .appendField(new Blockly.FieldDropdown([
  10200. [Blockly.Msg.ai_models_customized_get_result_name, "classid"],
  10201. [Blockly.Msg.ai_models_customized_get_result_x, "x"],
  10202. [Blockly.Msg.ai_models_customized_get_result_y, "y"],
  10203. [Blockly.Msg.ai_models_customized_get_result_w, "w"],
  10204. [Blockly.Msg.ai_models_customized_get_result_h, "h"],
  10205. // [Blockly.Msg.ai_models_customized_get_result_x_center, "cx"],
  10206. // [Blockly.Msg.ai_models_customized_get_result_y_center, "cy"],
  10207. // [Blockly.Msg.ai_models_customized_get_result_count, "objnum"],
  10208. // [Blockly.Msg.ai_models_customized_get_result_index, "index"],
  10209. [Blockly.Msg.ai_models_customized_get_result_confidence, "value"],
  10210. [Blockly.Msg.ai_models_face_model_ws, "2"],
  10211. [Blockly.Msg.ai_models_face_model_hs, "3"],
  10212. [Blockly.Msg.ai_models_object_model_x_center, "CX"],
  10213. [Blockly.Msg.ai_models_object_model_y_center, "CY"]
  10214. ]), "get_results");
  10215. this.setOutput(true, null);
  10216. this.setColour("#ee783a");
  10217. var thisBlock = this;
  10218. this.setTooltip(function () {
  10219. var mode = thisBlock.getFieldValue('get_results');
  10220. var TOOLTIPS = {
  10221. 'classid': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_name),
  10222. 'x': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x),
  10223. 'y': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y),
  10224. 'w': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_w),
  10225. 'h': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_h),
  10226. 'cx': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x_center),
  10227. 'cy': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y_center),
  10228. 'objnum': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_count),
  10229. 'index': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_index),
  10230. 'value': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_confidence)
  10231. };
  10232. return TOOLTIPS[mode];
  10233. });
  10234. this.setHelpUrl("");
  10235. }
  10236. };
  10237. Blockly.Python['ai_model_customized_get_result'] = function (block) {
  10238. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10239. var dropdown_get_results = block.getFieldValue('get_results');
  10240. // TODO: Assemble Python into code variable.
  10241. var code = '';
  10242. if (dropdown_get_results == "classid") {
  10243. code = 'Yolo.labels[' + variable_name + '[4][0]]';
  10244. } else if (dropdown_get_results == 'x') {
  10245. code = variable_name + '[0]';
  10246. } else if (dropdown_get_results == "y") {
  10247. code = variable_name + "[1]";
  10248. } else if (dropdown_get_results == "w") {
  10249. code = `${variable_name}[0]+${variable_name}[2]`;
  10250. } else if (dropdown_get_results == "h") {
  10251. code = `${variable_name}[1]+${variable_name}[3]`;
  10252. } else if (dropdown_get_results == "value") {
  10253. code = `${variable_name}[4][1][${variable_name}[4][0]]`;
  10254. } else if (dropdown_get_results == "CX") {
  10255. code = `int((${variable_name}[0] + ${variable_name}[2])/2)`;
  10256. } else if (dropdown_get_results == "CY") {
  10257. code = `int((${variable_name}[1] + ${variable_name}[3])/2)`;
  10258. }
  10259. else {
  10260. code = `${variable_name}[${dropdown_get_results}]`;
  10261. }
  10262. // TODO: Change ORDER_NONE to the correct strength.
  10263. return [code, Blockly.Python.ORDER_NONE];
  10264. };
  10265. Blockly.Blocks['ai_model_customized_init_setup_Graphics'] = {
  10266. init: function () {
  10267. this.appendDummyInput()
  10268. .appendField(Blockly.Msg.ai_models_customized_init_setup_title_Graphics);
  10269. this.appendDummyInput()
  10270. .appendField(Blockly.Msg.ai_models_customized_init_setup_path)
  10271. .appendField(new Blockly.FieldTextInput("/root/preset/model/yolov2_int8"), "model_path");
  10272. this.appendValueInput("class_input")
  10273. .setCheck(null)
  10274. .appendField(Blockly.Msg.ai_models_customized_init_setup_name);
  10275. this.setPreviousStatement(true, null);
  10276. this.setNextStatement(true, null);
  10277. this.setColour("#ee783a");
  10278. this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_TOOLTIP);
  10279. this.setHelpUrl("");
  10280. }
  10281. };
  10282. Blockly.Python['ai_model_customized_init_setup_Graphics'] = function (block) {
  10283. var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  10284. var text_model_path = block.getFieldValue('model_path');
  10285. Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn";
  10286. Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder`
  10287. let code = `class Yolo:
  10288. labels = ${value_class_input}
  10289. anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65]
  10290. m = {
  10291. "param": "${text_model_path}.param",
  10292. "bin": "${text_model_path}.bin"
  10293. }
  10294. options = {
  10295. "model_type": "awnn",
  10296. "inputs": {
  10297. "input0": (224, 224, 3)
  10298. },
  10299. "outputs": {
  10300. "output0": (7, 7, (1+4+len(labels))*5)
  10301. },
  10302. "mean": [127.5, 127.5, 127.5],
  10303. "norm": [0.0078125, 0.0078125, 0.0078125],
  10304. }
  10305. def __init__(self):
  10306. from maix import nn
  10307. from maix.nn import decoder
  10308. self.model = nn.load(self.m, opt=self.options)
  10309. self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7))
  10310. def __del__(self):
  10311. del self.model
  10312. del self.decoder
  10313. Yolo = Yolo()
  10314. `;
  10315. return code;
  10316. };
  10317. Blockly.Blocks['ai_model_customized_load_setup_Graphics'] = {
  10318. init: function () {
  10319. this.appendDummyInput()
  10320. .appendField(Blockly.Msg.ai_model_customized_load_setup_title_Graphics);
  10321. this.appendDummyInput()
  10322. .appendField(Blockly.Msg.ai_models_customized_init_setup_source)
  10323. .appendField(new Blockly.FieldVariable("img_modelrecognition"), "varitem");
  10324. this.setPreviousStatement(true, null);
  10325. this.setNextStatement(true, null);
  10326. this.setColour("#ee783a");
  10327. this.setTooltip(Blockly.Msg.ai_model_customized_load_setup_TOOLTIP);
  10328. this.setHelpUrl("");
  10329. }
  10330. };
  10331. Blockly.Python['ai_model_customized_load_setup_Graphics'] = function (block) {
  10332. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10333. var code = `outGraphics = Yolo.model.forward(${variable_name}, quantize=True, layout="hwc")
  10334. `;
  10335. return code;
  10336. };
  10337. Blockly.Blocks['ai_model_customized_get_result_Graphics'] = {
  10338. init: function () {
  10339. this.appendDummyInput()
  10340. .appendField(Blockly.Msg.ai_models_customized_get_result_any_Graphics)
  10341. .appendField(new Blockly.FieldDropdown([
  10342. [Blockly.Msg.ai_models_customized_get_result_name, "classid"],
  10343. [Blockly.Msg.ai_models_customized_get_result_confidence, "value"]
  10344. ]), "get_results");
  10345. this.setOutput(true, null);
  10346. this.setColour("#ee783a");
  10347. var thisBlock = this;
  10348. this.setTooltip(function () {
  10349. var mode = thisBlock.getFieldValue('get_results');
  10350. var TOOLTIPS = {
  10351. 'classid': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_name),
  10352. 'value': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_confidence)
  10353. };
  10354. return TOOLTIPS[mode];
  10355. });
  10356. this.setHelpUrl("");
  10357. }
  10358. };
  10359. Blockly.Python['ai_model_customized_get_result_Graphics'] = function (block) {
  10360. var dropdown_get_results = block.getFieldValue('get_results');
  10361. // TODO: Assemble Python into code variable.
  10362. var code = '';
  10363. if (dropdown_get_results == "classid") {
  10364. code = 'Yolo.labels[outGraphics.argmax()]';
  10365. } else if (dropdown_get_results == "value") {
  10366. code = `int(outGraphics.max() * 10)`;
  10367. }
  10368. // TODO: Change ORDER_NONE to the correct strength.
  10369. return [code, Blockly.Python.ORDER_NONE];
  10370. };
  10371. Blockly.Blocks['ai_model_Classification_validation'] = {
  10372. init: function () {
  10373. this.appendDummyInput()
  10374. .appendField('从摄像头获取图像')
  10375. .appendField(new Blockly.FieldVariable("AI_img"), "varitem")
  10376. .appendField('并通过训练的模型对图片进行验证')
  10377. this.setPreviousStatement(true, null);
  10378. this.setNextStatement(true, null);
  10379. this.setColour("#ee783a");
  10380. this.setTooltip('对训练的模型进行分类验证')
  10381. }
  10382. }
  10383. Blockly.Python['ai_model_Classification_validation'] = function (block) {
  10384. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10385. Blockly.Python.definitions_['v831_import_time'] = `import time`
  10386. Blockly.Python.definitions_.import_self_learn_Classification_validation = `from maix import nn
  10387. `
  10388. let code = `idx, distance = SELFLEARN.classifier.predict(${variable_name}.copy().resize(224, 224))`;
  10389. return code
  10390. }
  10391. Blockly.Blocks['ai_model_Classification_validation_result'] = {
  10392. init: function () {
  10393. this.appendDummyInput()
  10394. .appendField('验证结果')
  10395. this.setOutput(true, null);
  10396. this.setColour("#ee783a");
  10397. this.setTooltip('验证结果')
  10398. }
  10399. }
  10400. Blockly.Python['ai_model_Classification_validation_result'] = function (block) {
  10401. let code = `"predict class:" str(idx+1), "conf:" str(100-distance)`;
  10402. return [code, Blockly.Python.ORDER_NONE];
  10403. }
  10404. /*
  10405. _ ___ ____ _
  10406. / \ |_ _| / ___| _ _ ___| |_ ___ _ __ ___
  10407. / _ \ | | \___ \| | | / __| __/ _ \ '_ ` _ \
  10408. / ___ \ | | ___) | |_| \__ \ || __/ | | | | |
  10409. /_/ \_\___| |____/ \__, |___/\__\___|_| |_| |_|
  10410. |___/
  10411. */
  10412. Blockly.Blocks['ai_system_off'] = {
  10413. init: function () {
  10414. this.appendDummyInput()
  10415. .appendField(Blockly.Msg.ai_system_off);
  10416. this.setPreviousStatement(true);
  10417. this.setNextStatement(true);
  10418. this.setColour("#22398e");
  10419. this.setTooltip(Blockly.Msg.ai_system_restart_TOOLTIP);
  10420. this.setHelpUrl("");
  10421. }
  10422. };
  10423. Blockly.Python.ai_system_off = function (block) {
  10424. Blockly.Python.definitions_['v831_import_os'] = `import os`
  10425. var _code = `os.system("poweroff")
  10426. `
  10427. return _code;
  10428. }
  10429. Blockly.Blocks['ai_system_restart'] = {
  10430. init: function () {
  10431. this.appendDummyInput()
  10432. .appendField(Blockly.Msg.ai_system_restart);
  10433. this.setPreviousStatement(true);
  10434. this.setNextStatement(true);
  10435. this.setColour("#22398e");
  10436. this.setTooltip(Blockly.Msg.ai_system_off_TOOLTIP);
  10437. this.setHelpUrl("");
  10438. }
  10439. };
  10440. Blockly.Python.ai_system_restart = function (block) {
  10441. Blockly.Python.definitions_['v831_import_os'] = `import os`
  10442. var _code = `os.system("reboot")
  10443. `
  10444. return _code;
  10445. }
  10446. Blockly.Blocks['ai_system_refresh'] = {
  10447. init: function () {
  10448. this.appendDummyInput()
  10449. .appendField(Blockly.Msg.ai_system_refresh);
  10450. this.setPreviousStatement(true);
  10451. this.setNextStatement(true);
  10452. this.setColour("#22398e");
  10453. this.setTooltip(Blockly.Msg.ai_system_refresh_TOOLTIP);
  10454. this.setHelpUrl("");
  10455. }
  10456. };
  10457. Blockly.Python.ai_system_refresh = function (block) {
  10458. Blockly.Python.definitions_['v831_import_os'] = `import os`
  10459. var _code = `os.system("sync")
  10460. `
  10461. return _code;
  10462. }
  10463. Blockly.Blocks['ai_system_volume'] = {
  10464. init: function () {
  10465. this.appendDummyInput()
  10466. .appendField(Blockly.Msg.system_voice)
  10467. .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol");
  10468. this.setPreviousStatement(true);
  10469. this.setNextStatement(true);
  10470. this.setColour("#22398e");
  10471. }
  10472. }
  10473. Blockly.Python.ai_system_volume = function (block) {
  10474. var number_play_vol = block.getFieldValue('play_vol');
  10475. Blockly.Python.definitions_['v831_import_os'] = `import os`
  10476. Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value):
  10477. valueScaled = float(value - 0) / float(100)
  10478. return int(valueScaled * 31)
  10479. `
  10480. var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol}))
  10481. time.sleep(0.01)
  10482. SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+""
  10483. os.system(SYSTEMVOICE)
  10484. `
  10485. return _code;
  10486. }
  10487. Blockly.Blocks['ai_system_thread'] = {
  10488. init: function () {
  10489. this.appendDummyInput()
  10490. .appendField(Blockly.Msg.ai_system_thread_setting).appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
  10491. this.appendStatementInput("input")
  10492. .setCheck(null)
  10493. .appendField(Blockly.Msg.basic_motion_statement_exec);
  10494. this.setColour("#22398e");
  10495. this.setTooltip(Blockly.Msg.ai_system_thread_setting);
  10496. this.setHelpUrl("");
  10497. }
  10498. };
  10499. Blockly.Python['ai_system_thread'] = function (block) {
  10500. var threadNum = block.getFieldValue('thread');
  10501. var statements_input = Blockly.Python.statementToCode(block, 'input');
  10502. Blockly.Python.definitions_['v831_import_threading'] = `import threading`
  10503. let allBlocks = block.workspace.getAllBlocks();
  10504. let global = ""
  10505. try {
  10506. global = allBlocks[0].workspace.variableList.toString()
  10507. }
  10508. catch (e) {
  10509. console.log(e)
  10510. }
  10511. Blockly.Python.definitions_['v831_import_thread_calsss_fun' + threadNum] = `def thread_calsss_fun${threadNum}():
  10512. global ${global}
  10513. ${statements_input}
  10514. CocoPiThread${threadNum} = threading.Thread(target=thread_calsss_fun${threadNum})
  10515. `
  10516. var code = ``;
  10517. return code;
  10518. };
  10519. Blockly.Blocks['ai_system_thread_create_with_container'] = {
  10520. init: function () {
  10521. this.setColour("#22398e");
  10522. this.appendDummyInput()
  10523. .appendField(Blockly.Msg.serialcomm_write_item);
  10524. this.appendStatementInput('STACK');
  10525. this.setTooltip('');
  10526. this.contextMenu = false;
  10527. }
  10528. };
  10529. Blockly.Blocks['ai_system_thread_data_create_with_item'] = {
  10530. init: function () {
  10531. this.setColour("#22398e");
  10532. this.appendDummyInput()
  10533. .appendField(Blockly.Msg.ai_systen_thread_val);
  10534. this.setPreviousStatement(true);
  10535. this.setNextStatement(true);
  10536. this.setTooltip('');
  10537. this.contextMenu = false;
  10538. }
  10539. };
  10540. Blockly.Blocks['ai_system_thread_set_setDaemon'] = {
  10541. init: function () {
  10542. this.appendDummyInput()
  10543. .appendField(Blockly.Msg.ai_system_thread_setting).appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
  10544. .appendField(Blockly.Msg.digital_set_as).appendField(new Blockly.FieldDropdown([
  10545. [Blockly.Msg.ai_system_thread_setDaemon, "True"],
  10546. [Blockly.Msg.ai_system_thread_not_setDaemon, "False"]
  10547. ]), "setDaemon");
  10548. this.setPreviousStatement(true, null);
  10549. this.setNextStatement(true, null)
  10550. this.setColour("#22398e");
  10551. this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
  10552. this.setHelpUrl("");
  10553. }
  10554. };
  10555. Blockly.Python['ai_system_thread_set_setDaemon'] = function (block) {
  10556. var threadNum = block.getFieldValue('thread');
  10557. var queue_value = block.getFieldValue('setDaemon');
  10558. var code = `CocoPiThread${threadNum}.setDaemon(${queue_value})
  10559. `;
  10560. return code;
  10561. };
  10562. Blockly.Blocks['ai_system_thread_set_join'] = {
  10563. init: function () {
  10564. this.appendDummyInput()
  10565. .appendField(Blockly.Msg.ai_system_thread_setting)
  10566. .appendField(new Blockly.FieldNumber(1, 1, 5), "thread")
  10567. .appendField(Blockly.Msg.ai_system_thread_set_join)
  10568. this.setPreviousStatement(true, null);
  10569. this.setNextStatement(true, null)
  10570. this.setColour("#22398e");
  10571. this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
  10572. this.setHelpUrl("");
  10573. }
  10574. };
  10575. Blockly.Python['ai_system_thread_set_join'] = function (block) {
  10576. var threadNum = block.getFieldValue('thread');
  10577. var code = `CocoPiThread${threadNum}.join()
  10578. `;
  10579. return code;
  10580. };
  10581. Blockly.Blocks['ai_system_thread_start'] = {
  10582. init: function () {
  10583. this.appendDummyInput()
  10584. .appendField(Blockly.Msg.ai_system_thread).appendField(new Blockly.FieldNumber(1, 1, 5), "thread");
  10585. // this.appendStatementInput("input")
  10586. // .setCheck(null)
  10587. // .appendField(Blockly.Msg.basic_motion_statement_exec);
  10588. this.setPreviousStatement(true, null);
  10589. this.setNextStatement(true, null)
  10590. this.setColour("#22398e");
  10591. this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP);
  10592. this.setHelpUrl("");
  10593. }
  10594. };
  10595. Blockly.Python['ai_system_thread_start'] = function (block) {
  10596. var threadNum = block.getFieldValue('thread');
  10597. // var statements_input = Blockly.Python.statementToCode(block, 'input');
  10598. var code = `CocoPiThread${threadNum}.start()
  10599. `;
  10600. return code;
  10601. };
  10602. Blockly.Blocks["ai_system_set_queue"] = {
  10603. init: function () {
  10604. this.appendDummyInput()
  10605. .appendField(Blockly.Msg.ai_systen_queue_aritem)
  10606. this.appendValueInput("queueVaritem")
  10607. .setCheck(null);
  10608. this.appendDummyInput().appendField(Blockly.Msg.ai_systen_queue_put)
  10609. .appendField(new Blockly.FieldDropdown([
  10610. ["1", "1"],
  10611. ["2", "2"],
  10612. ["3", "3"],
  10613. ["4", "4"],
  10614. ["5", "5"]
  10615. ]), "queue_value");
  10616. this.setPreviousStatement(true, null);
  10617. this.setNextStatement(true, null);
  10618. this.setColour("#22398e");
  10619. this.setTooltip("");
  10620. }
  10621. }
  10622. Blockly.Python['ai_system_set_queue'] = function (block) {
  10623. var variable_name = Blockly.Python.valueToCode(block, 'queueVaritem', Blockly.Python.ORDER_ATOMIC);
  10624. // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  10625. var queue_value = block.getFieldValue('queue_value');
  10626. Blockly.Python.definitions_["v831_import_queue"] = `import queue`
  10627. Blockly.Python.definitions_["v831_import_queue_init" + queue_value] = `queue${queue_value} = queue.Queue()`
  10628. var code = `queue${queue_value}.append(${variable_name})
  10629. `;
  10630. return code;
  10631. }
  10632. Blockly.Blocks["ai_system_get_queue"] = {
  10633. init: function () {
  10634. this.appendDummyInput()
  10635. .appendField(Blockly.Msg.ai_systen_queue_get)
  10636. .appendField(new Blockly.FieldDropdown([
  10637. ["1", "1"],
  10638. ["2", "2"],
  10639. ["3", "3"],
  10640. ["4", "4"],
  10641. ["5", "5"]
  10642. ]), "queue_value")
  10643. .appendField(Blockly.Msg.ai_systen_queue_value);
  10644. this.setOutput(true, null);
  10645. this.setColour("#22398e");
  10646. this.setTooltip("");
  10647. }
  10648. }
  10649. Blockly.Python['ai_system_get_queue'] = function (block) {
  10650. var queue_value = block.getFieldValue('queue_value');
  10651. var code = `queue${queue_value}`;
  10652. return [code, Blockly.Python.ORDER_NONE];
  10653. }
  10654. // 拼音识别
  10655. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_setup'] = {
  10656. init: function () {
  10657. this.appendDummyInput()
  10658. .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" }));
  10659. this.appendDummyInput()
  10660. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_setup);
  10661. this.setPreviousStatement(true, null);
  10662. this.setNextStatement(true, null);
  10663. this.setColour("#ee783a");
  10664. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_setup_TOOLTIP);
  10665. this.setHelpUrl("");
  10666. }
  10667. };
  10668. Blockly.Python['speech_recognition_phonetic_to_pinyin_setup'] = function (block) {
  10669. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  10670. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  10671. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  10672. Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech`
  10673. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr()
  10674. asr.open("hw:0,0", "/root/preset/drivers/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1")
  10675. asr.clear()
  10676. asr_kws_result=[0,0] #获取识别结果及识别概率
  10677. similars = [
  10678. ["pai3", "ai4"],
  10679. ["le4", "luo4"],
  10680. ]
  10681. def asr_kws(keys):
  10682. global asr_kws_result
  10683. tmp = max(keys)
  10684. asr_kws_result[0] = keys.index(tmp)
  10685. asr_kws_result[1] = round(tmp,2)
  10686. `
  10687. var code = "";
  10688. return code;
  10689. };
  10690. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_set_param_new'] = {
  10691. init: function () {
  10692. this.appendDummyInput()
  10693. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param);
  10694. // this.appendValueInput("data")
  10695. // .setCheck(null)
  10696. // .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  10697. this.setPreviousStatement(true, null);
  10698. this.setNextStatement(true, null);
  10699. this.setInputsInline(true);
  10700. this.setColour("#ee783a");
  10701. this.pinyinitemCount_ = 1
  10702. this.updateShape_();
  10703. this.setMutator(new Blockly.Mutator(["v831_to_pinyin_set_param"]));
  10704. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param_TOOLTIP+Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param_max );
  10705. this.setHelpUrl("");
  10706. },
  10707. mutationToDom: function () {
  10708. var a = document.createElement("mutation");
  10709. a.setAttribute("items", this.pinyinitemCount_);
  10710. return a
  10711. },
  10712. domToMutation: function (a) {
  10713. this.pinyinitemCount_ = parseInt(a.getAttribute("items"), 10);
  10714. this.updateShape_()
  10715. },
  10716. decompose: function (a) {
  10717. var b = a.newBlock("v831_to_pinyin_set_param_container");
  10718. b.initSvg();
  10719. for (var c = b.getInput("STACK").connection, e = 0; e < this.pinyinitemCount_; e++) {
  10720. var d = a.newBlock("v831_to_pinyin_set_param");
  10721. d.initSvg();
  10722. c.connect(d.previousConnection);
  10723. c = d.nextConnection
  10724. }
  10725. return b
  10726. },
  10727. compose: function (a) {
  10728. var b = a.getInputTargetBlock("STACK");
  10729. for (a = []; b;)
  10730. a.push(b.valueConnection_),
  10731. b = b.nextConnection && b.nextConnection.targetBlock();
  10732. for (b = 0; b < this.pinyinitemCount_; b++) {
  10733. var c = this.getInput("PINYIN" + b).connection.targetConnection;
  10734. c && -1 == a.indexOf(c) && c.disconnect()
  10735. }
  10736. this.pinyinitemCount_ = a.length;
  10737. this.updateShape_();
  10738. for (b = 0; b < this.pinyinitemCount_; b++)
  10739. Blockly.Mutator.reconnect(a[b], this, "PINYIN" + b)
  10740. },
  10741. saveConnections: function (a) {
  10742. a = a.getInputTargetBlock("STACK");
  10743. for (var b = 0; a;) {
  10744. var c = this.getInput("PINYIN" + b);
  10745. a.valueConnection_ = c && c.connection.targetConnection;
  10746. b++;
  10747. a = a.nextConnection && a.nextConnection.targetBlock()
  10748. }
  10749. },
  10750. updateShape_: function () {
  10751. // this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE);
  10752. for (var a = 0; a < this.pinyinitemCount_; a++)
  10753. if (!this.getInput("PINYIN" + a)) {
  10754. var b = this.appendValueInput("PINYIN" + a);
  10755. 0 == a && b.appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone)
  10756. }
  10757. for (; this.getInput("PINYIN" + a);)
  10758. this.removeInput("PINYIN" + a),
  10759. a++
  10760. }
  10761. };
  10762. Blockly.Blocks['v831_to_pinyin_set_param'] = {
  10763. init: function () {
  10764. this.appendDummyInput()
  10765. .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone);
  10766. this.setPreviousStatement(true);
  10767. this.setNextStatement(true);
  10768. this.setColour("#ee783a")
  10769. this.setTooltip('');
  10770. this.contextMenu = false;
  10771. }
  10772. };
  10773. Blockly.Blocks['v831_to_pinyin_set_param_container'] = {
  10774. init: function () {
  10775. this.setColour("#ee783a");
  10776. this.appendDummyInput()
  10777. .appendField(Blockly.Msg.ARD_SERIAL_SETUP);
  10778. this.appendStatementInput('STACK');
  10779. this.setTooltip('');
  10780. this.contextMenu = false;
  10781. }
  10782. };
  10783. Blockly.Python['speech_recognition_phonetic_to_pinyin_set_param_new'] = function (block) {
  10784. // var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  10785. Blockly.Python.definitions_['v831_import_display'] = `from maix import display`;
  10786. Blockly.Python.definitions_['v831_import_image'] = `from maix import image`;
  10787. Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`;
  10788. Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech`
  10789. var a = Array(this.pinyinitemCount_)
  10790. for (let b = 0; b < this.pinyinitemCount_; b++) {
  10791. var c = Blockly.Python.valueToCode(this, "PINYIN" + b, Blockly.Python.ORDER_NONE)
  10792. a[b] = c.slice(1, -1).replaceAll(",", "")
  10793. }
  10794. a = a.map(r => [r, 0.1])
  10795. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr()
  10796. asr.open("hw:0,0", "/root/preset/drivers/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1")
  10797. asr.clear()
  10798. asr_kws_result=[0,0] #获取识别结果及识别概率
  10799. similars = [
  10800. ["pai3", "ai4"],
  10801. ["le4", "luo4"],
  10802. ]
  10803. def asr_kws(keys):
  10804. global asr_kws_result
  10805. tmp = max(keys)
  10806. asr_kws_result[0] = keys.index(tmp)
  10807. asr_kws_result[1] = round(tmp,2)
  10808. `
  10809. // Blockly.Python.definitions_["set_keywords_function"] = `def SetKeywords(data):
  10810. // dataList = []
  10811. // for obj in data:
  10812. // dataList.append([obj,0.1])
  10813. // print(dataList)
  10814. // return dataList
  10815. // `
  10816. var code = `keywords = ${JSON.stringify(a)}
  10817. asr.set_kws(keywords, similars, asr_kws)
  10818. `;
  10819. return code;
  10820. };
  10821. Blockly.Blocks['speech_recognition_set_pinyin_tone'] = {
  10822. init: function () {
  10823. this.appendDummyInput()
  10824. .appendField("声调").appendField(new Blockly.FieldDropdown([
  10825. ["1", "1"],
  10826. ["2", "2"],
  10827. ["3", "3"],
  10828. ["4", "4"],
  10829. ]), "tone");
  10830. this.setOutput(true, null);
  10831. this.setColour("#ee783a");
  10832. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP);
  10833. this.setHelpUrl("");
  10834. }
  10835. };
  10836. Blockly.Python['speech_recognition_set_pinyin_tone'] = function (block) {
  10837. let tone = block.getFieldValue('tone');
  10838. console.log(tone)
  10839. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult():
  10840. global asr_kws_result,keywords
  10841. if(asr_kws_result[1]!=0):
  10842. asr_kws_result_list = keywords[asr_kws_result[0]][0]
  10843. return asr_kws_result_list
  10844. `
  10845. var code = tone;
  10846. return [code, Blockly.Python.ORDER_NONE];
  10847. };
  10848. Blockly.Blocks.set_pinyin_dict_create_with_items_insert = {
  10849. init: function () {
  10850. this.setColour("#ee783a");
  10851. this.appendDummyInput("").appendField(new Blockly.FieldLabel(Blockly.Msg.ai_speech_recognition_setup_pinyin), "TIP");
  10852. this.itemCount_ = 3;
  10853. this.updateShape_();
  10854. this.setOutput(!0);
  10855. this.setMutator(new Blockly.Mutator(["set_pinyin_dict_create_with_item"]));
  10856. this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone)
  10857. },
  10858. mutationToDom: function () {
  10859. var a = document.createElement("mutation");
  10860. a.setAttribute("items", this.itemCount_);
  10861. return a
  10862. },
  10863. domToMutation: function (a) {
  10864. this.itemCount_ = parseInt(a.getAttribute("items"), 10);
  10865. this.updateShape_()
  10866. },
  10867. decompose: function (a) {
  10868. var b = a.newBlock("set_pinyin_dict_create_with_container");
  10869. b.initSvg();
  10870. for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) {
  10871. var d = a.newBlock("set_pinyin_dict_create_with_item");
  10872. d.initSvg();
  10873. c.connect(d.previousConnection);
  10874. c = d.nextConnection
  10875. }
  10876. return b
  10877. },
  10878. compose: function (a) {
  10879. a = a.getInputTargetBlock("STACK");
  10880. for (var b = [], c = 0; a;)
  10881. b[c] = a.valueConnection_,
  10882. a = a.nextConnection && a.nextConnection.targetBlock(),
  10883. c++;
  10884. this.itemCount_ = c;
  10885. this.updateShape_();
  10886. for (c = 0; c < this.itemCount_; c++)
  10887. b[c] && this.getInput("ADD" + c).connection.connect(b[c])
  10888. },
  10889. saveConnections: function (a) {
  10890. a = a.getInputTargetBlock("STACK");
  10891. for (var b = 0; a;) {
  10892. var c = this.getInput("ADD" + b);
  10893. a.valueConnection_ = c && c.connection;
  10894. b++;
  10895. a = a.nextConnection && a.nextConnection.targetBlock()
  10896. }
  10897. },
  10898. updateShape_: function () {
  10899. this.getInput("EMPTY") && this.removeInput("EMPTY");
  10900. for (var a = [], b = 0; this.getInput("ADD" + b); b++)
  10901. a.push(this.getFieldValue("KEY" + b)),
  10902. this.removeInput("ADD" + b);
  10903. if (0 == this.itemCount_)
  10904. this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  10905. else
  10906. for (this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin),
  10907. b = 0; b < this.itemCount_; b++)
  10908. 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(":")
  10909. .appendField(Blockly.Msg.ai_speech_recognition_setup_tone).appendField(new Blockly.FieldDropdown([
  10910. ["1", "1"],
  10911. ["2", "2"],
  10912. ["3", "3"],
  10913. ["4", "4"],
  10914. ]), "toneADD" + b + b)
  10915. },
  10916. getVars: function () {
  10917. return [this.getFieldValue("VAR")]
  10918. },
  10919. renameVar: function (a, b) {
  10920. Blockly.Names.equals(a, this.getFieldValue("VAR")) && this.setTitleValue(b, "VAR")
  10921. }
  10922. };
  10923. Blockly.Python.set_pinyin_dict_create_with_items_insert = function (block) {
  10924. for (var a = Array(this.itemCount_), b = 0; b < this.itemCount_; b++) {
  10925. var c = this.getFieldValue("KEY" + b);
  10926. a[b] = c + block.getFieldValue("toneADD" + b + b);
  10927. }
  10928. // console.log(a.join(" "))
  10929. a = `"${a.join(" ")}"`;
  10930. return [a, Blockly.Python.ORDER_ATOMIC]
  10931. };
  10932. Blockly.Blocks.set_pinyin_dict_create_with_item = {
  10933. init: function () {
  10934. this.setColour("#ee783a");
  10935. this.appendDummyInput().appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  10936. this.setPreviousStatement(!0);
  10937. this.setNextStatement(!0);
  10938. this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  10939. this.contextMenu = !1
  10940. }
  10941. };
  10942. Blockly.Blocks.set_pinyin_dict_create_with_container = {
  10943. init: function () {
  10944. this.setColour("#ee783a");
  10945. this.appendDummyInput().appendField(Blockly.Msg.robot_dog_servo_execution);
  10946. this.appendStatementInput("STACK");
  10947. this.setTooltip(Blockly.Msg.robot_dog_servo_execution);
  10948. this.contextMenu = !1
  10949. }
  10950. };
  10951. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_set_param'] = {
  10952. init: function () {
  10953. this.appendDummyInput()
  10954. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param);
  10955. this.appendValueInput("data")
  10956. .setCheck(null)
  10957. .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin);
  10958. this.setPreviousStatement(true, null);
  10959. this.setNextStatement(true, null);
  10960. this.setInputsInline(false);
  10961. this.setColour("#ee783a");
  10962. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param_TOOLTIP);
  10963. this.setHelpUrl("");
  10964. }
  10965. };
  10966. Blockly.Python['speech_recognition_phonetic_to_pinyin_set_param'] = function (block) {
  10967. var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
  10968. var code = `keywords = ${data}
  10969. asr.set_kws(keywords, similars, asr_kws)
  10970. `;
  10971. return code;
  10972. };
  10973. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_start_recognition'] = {
  10974. init: function () {
  10975. this.appendDummyInput()
  10976. .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition);
  10977. this.setPreviousStatement(true, null);
  10978. this.setNextStatement(true, null);
  10979. this.setColour("#ee783a");
  10980. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition_TOOLTIP);
  10981. this.setHelpUrl("");
  10982. }
  10983. };
  10984. Blockly.Python['speech_recognition_phonetic_to_pinyin_start_recognition'] = function (block) {
  10985. var code = "asr.run(1)\n";
  10986. return code;
  10987. };
  10988. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_stop_recognition'] = {
  10989. init: function () {
  10990. this.appendDummyInput()
  10991. .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition);
  10992. this.setPreviousStatement(true, null);
  10993. this.setNextStatement(true, null);
  10994. this.setColour("#ee783a");
  10995. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition_TOOLTIP);
  10996. this.setHelpUrl("");
  10997. }
  10998. };
  10999. Blockly.Python['speech_recognition_phonetic_to_pinyin_stop_recognition'] = function (block) {
  11000. var code = "asr.exit()\n";
  11001. return code;
  11002. };
  11003. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_pause_recognition'] = {
  11004. init: function () {
  11005. this.appendDummyInput()
  11006. .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition);
  11007. this.setPreviousStatement(true, null);
  11008. this.setNextStatement(true, null);
  11009. this.setColour("#ee783a");
  11010. this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition_TOOLTIP);
  11011. this.setHelpUrl("");
  11012. }
  11013. };
  11014. Blockly.Python['speech_recognition_phonetic_to_pinyin_pause_recognition'] = function (block) {
  11015. var code = "asr.clear()\n";
  11016. return code;
  11017. };
  11018. Blockly.Blocks['speech_recognition_phonetic_to_pinyin_get_result'] = {
  11019. init: function () {
  11020. this.appendDummyInput()
  11021. .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result);
  11022. this.setOutput(true, null);
  11023. this.setColour("#ee783a");
  11024. this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP);
  11025. this.setHelpUrl("");
  11026. }
  11027. };
  11028. Blockly.Python['speech_recognition_phonetic_to_pinyin_get_result'] = function (block) {
  11029. Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult():
  11030. global asr_kws_result,keywords
  11031. if(asr_kws_result[1]!=0):
  11032. asr_kws_result_list = keywords[asr_kws_result[0]][0]
  11033. return asr_kws_result_list
  11034. `
  11035. var code = 'getAsrResult()';
  11036. return [code, Blockly.Python.ORDER_NONE];
  11037. };
  11038. // numpy + mnist
  11039. Blockly.Blocks['Numpy_Neural_Network_init'] = {
  11040. init: function () {
  11041. this.appendDummyInput()
  11042. .appendField(Blockly.Msg.numpy_mnist_model_init);
  11043. this.setPreviousStatement(true, null);
  11044. this.setNextStatement(true, null);
  11045. this.setColour("#ee783a");
  11046. this.setTooltip(Blockly.Msg.numpy_mnist_model_init);
  11047. this.setHelpUrl("");
  11048. }
  11049. };
  11050. Blockly.Python['Numpy_Neural_Network_init'] = function (block) {
  11051. Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`;
  11052. Blockly.Python.definitions_["v831_import_pickle"] = `import pickle`
  11053. Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x):
  11054. return 1/(1+np.exp(-x))
  11055. def grad(x):
  11056. return x*(1-x)
  11057. class NeuralNetwork:
  11058. """
  11059. 三层全连接前馈神经网络
  11060. """
  11061. def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1):
  11062. """
  11063. :param inputnodes: 输入层结点数
  11064. :param hiddennodes: 隐藏层节点数
  11065. :param outputnodes: 输出层节点数
  11066. :param learningrate: 学习率
  11067. :param active_function: 激活函数
  11068. :param gradient: 激活函数的导数
  11069. :param lambda_: L2正则化系数
  11070. """
  11071. self.inputnodes = inputnodes
  11072. self.hiddennodes = hiddennodes
  11073. self.outputnodes = outputnodes
  11074. self.learningrate = learningrate
  11075. self.active_function = active_function
  11076. self.gradient = gradient
  11077. self.lambda_ = lambda_
  11078. # 权值矩阵
  11079. self.weights_i_h = np.random.rand(
  11080. self.hiddennodes, self.inputnodes) - 0.5
  11081. self.weights_h_o = np.random.rand(
  11082. self.outputnodes, self.hiddennodes) - 0.5
  11083. def train_sgd(self, x, y):
  11084. """梯度下降训练"""
  11085. TRAINX = np.array(x).reshape(-1, 1)
  11086. target = np.zeros((self.outputnodes, 1)) + 0.01
  11087. target[y, 0] = 0.99
  11088. hiddeninputs = np.dot(self.weights_i_h, TRAINX)
  11089. hiddenoutputs = self.active_function(hiddeninputs)
  11090. outputinputs = np.dot(self.weights_h_o, hiddenoutputs)
  11091. final_outputs = self.active_function(outputinputs)
  11092. error = target - final_outputs
  11093. hidden_error = np.dot(self.weights_h_o.transpose(), error)
  11094. self.weights_h_o += self.learningrate * error * \
  11095. np.dot(self.gradient(final_outputs), hiddenoutputs.transpose())
  11096. self.weights_i_h += self.learningrate * hidden_error * \
  11097. np.dot(self.gradient(hiddenoutputs), TRAINX.transpose())
  11098. def fit(self, TRAINX, targets):
  11099. TRAINX = np.array(TRAINX)
  11100. for i in range(TRAINX.shape[0]):
  11101. self.train_sgd(TRAINX[i], targets[i])
  11102. def query(self, inputs, debug=False):
  11103. """单个值预测"""
  11104. inputs = np.array(inputs).reshape(-1, 1)
  11105. hidden_input = np.dot(self.weights_i_h, inputs)
  11106. hidden_output = self.active_function(hidden_input)
  11107. output_input = np.dot(self.weights_h_o, hidden_output)
  11108. final_output = self.active_function(output_input)
  11109. if debug:
  11110. print("predict: ", final_output)
  11111. return np.argmax(final_output)
  11112. def predict(self, inputs):
  11113. """批量预测"""
  11114. res = []
  11115. for x in inputs:
  11116. res.append(self.query(x))
  11117. return res
  11118. def __str__(self):
  11119. return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate)
  11120. # 用测试数据测试
  11121. def accuracy(y_true, y_pred):
  11122. """准确度"""
  11123. y_true = np.array(y_true)
  11124. y_pred = np.array(y_pred)
  11125. return sum(y_true == y_pred)/y_true.shape[0]
  11126. # 用全部数据进行训练
  11127. def get_data():
  11128. # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str)
  11129. # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str)
  11130. global train_df, test_df
  11131. print(train_df.shape)
  11132. print(test_df.shape)
  11133. train_data = train_df.astype("int")
  11134. TRAINX = train_data[:, 1:]
  11135. TRAINY = train_data[:, 0]
  11136. TRAINX = TRAINX / 255 * 0.99 + 0.01
  11137. test_data = test_df.astype("int")
  11138. TESTX = test_data[:, 1:]
  11139. TESTY = test_data[:, 0]
  11140. TESTX = TESTX / 255 * 0.99 + 0.01
  11141. return TRAINX, TRAINY, TESTX, TESTY
  11142. `
  11143. var code = '';
  11144. return code;
  11145. };
  11146. Blockly.Blocks['Numpy_Neural_Network_load'] = {
  11147. init: function () {
  11148. this.appendDummyInput()
  11149. .appendField("numpy + mnist 训练模型加载");
  11150. this.setPreviousStatement(true, null);
  11151. this.setNextStatement(true, null);
  11152. this.setColour("#ee783a");
  11153. this.setTooltip("numpy + mnist 训练模型加载");
  11154. this.setHelpUrl("");
  11155. }
  11156. };
  11157. Blockly.Python['Numpy_Neural_Network_load'] = function (block) {
  11158. var code = `#构建神经网络训练服务
  11159. TRAINX, TRAINY, TESTX, TESTY = get_data()
  11160. NN = NeuralNetwork(784, 100, 10, 0.3)
  11161. NN.fit(TRAINX, TRAINY)
  11162. y_pred = NN.predict(TESTX)
  11163. `;
  11164. return code;
  11165. };
  11166. Blockly.Blocks['Numpy_Neural_Network_LOading_test_train'] = {
  11167. init: function () {
  11168. this.appendDummyInput()
  11169. .appendField(Blockly.Msg.numpy_mnist_loading_train_and_test_set);
  11170. this.appendValueInput("class_input")
  11171. .setCheck(null)
  11172. .appendField(Blockly.Msg.numpy_mnist_train_set_url);
  11173. this.appendValueInput("class_input1")
  11174. .setCheck(null)
  11175. .appendField(Blockly.Msg.numpy_mnist_test_set_url);
  11176. this.setPreviousStatement(true, null);
  11177. this.setNextStatement(true, null);
  11178. this.setColour("#ee783a");
  11179. this.setTooltip(Blockly.Msg.numpy_mnist_loading_train_and_test_set);
  11180. this.setHelpUrl("");
  11181. }
  11182. };
  11183. Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) {
  11184. var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  11185. var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
  11186. // TODO: Assemble Python into code variable.
  11187. var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str)
  11188. train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str)
  11189. `;
  11190. // TODO: Change ORDER_NONE to the correct strength.
  11191. return code;
  11192. };
  11193. Blockly.Blocks['Numpy_Neural_Network_numpy_isStart'] = {
  11194. init: function () {
  11195. this.appendDummyInput()
  11196. .appendField(Blockly.Msg.numpy_mnist_is_training_start);
  11197. this.setOutput(true, null);
  11198. this.setColour("#ee783a");
  11199. this.setTooltip(Blockly.Msg.numpy_mnist_is_training_start);
  11200. this.setHelpUrl("");
  11201. }
  11202. };
  11203. Blockly.Python['Numpy_Neural_Network_numpy_isStart'] = function (block) {
  11204. // TODO: Assemble Python into code variable.
  11205. var code = `not os.path.exists("/usr/lib/python3.8/site-packages/numpy/random/__init__.py")`;
  11206. // TODO: Change ORDER_NONE to the correct strength.
  11207. return [code, Blockly.Python.ORDER_NONE];
  11208. };
  11209. Blockly.Blocks['Numpy_Neural_Network_setting_training_argument'] = {
  11210. init: function () {
  11211. this.appendDummyInput()
  11212. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument);
  11213. this.appendValueInput("class_input")
  11214. .setCheck(null)
  11215. .appendField(Blockly.Msg.numpy_mnist_input_trait_dimensionality);
  11216. this.appendValueInput("class_input1")
  11217. .setCheck(null)
  11218. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_number_node);
  11219. this.appendValueInput("class_input2")
  11220. .setCheck(null)
  11221. .appendField(Blockly.Msg.numpy_mnist_output_dimensionality);
  11222. this.appendValueInput("class_input3")
  11223. .setCheck(null)
  11224. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_learning_rate);
  11225. this.appendValueInput("class_input4")
  11226. .setCheck(null)
  11227. .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_frequency);
  11228. this.appendValueInput("class_input5")
  11229. .setCheck(null)
  11230. .appendField(Blockly.Msg.VIDEO_S_S);
  11231. this.setPreviousStatement(true, null);
  11232. this.setNextStatement(true, null);
  11233. this.setColour("#ee783a");
  11234. this.setTooltip(Blockly.Msg.numpy_mnist_setting_training_argument);
  11235. this.setHelpUrl("");
  11236. }
  11237. };
  11238. Blockly.Python['Numpy_Neural_Network_setting_training_argument'] = function (block) {
  11239. var class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  11240. var class_input1 = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
  11241. var class_input2 = Blockly.Python.valueToCode(block, 'class_input2', Blockly.Python.ORDER_ATOMIC);
  11242. var class_input3 = Blockly.Python.valueToCode(block, 'class_input3', Blockly.Python.ORDER_ATOMIC);
  11243. var class_input4 = Blockly.Python.valueToCode(block, 'class_input4', Blockly.Python.ORDER_ATOMIC);
  11244. var class_input5 = Blockly.Python.valueToCode(block, 'class_input5', Blockly.Python.ORDER_ATOMIC);
  11245. // TODO: Assemble Python into code variable.
  11246. console.log(Number(class_input.slice(1, -1)), class_input1, class_input2, class_input3)
  11247. var code = `TRAINX, TRAINY, TESTX, TESTY = get_data()
  11248. 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))})
  11249. #开启神经网络训练,记录时长
  11250. AccuracyRATE = 0
  11251. # 训练10次,每3次训练下降一次学习率
  11252. for e in range(1, ${Number(class_input4.slice(1, -1)) + 1}):
  11253. if e % 3 == 0:
  11254. NN.learningrate /= 2
  11255. NN.fit(TRAINX, TRAINY)
  11256. y_pred = NN.predict(TESTX)
  11257. CURRENTACCURACY = accuracy(TESTY, y_pred)
  11258. if CURRENTACCURACY > AccuracyRATE:
  11259. AccuracyRATE = CURRENTACCURACY
  11260. #文件已保存至
  11261. with open(${class_input5}, "wb") as f: # 保存模型
  11262. pickle.dump(pickle.dumps(NN), f)
  11263. os.system("touch /usr/lib/python3.8/site-packages/numpy/random/__init__.py")
  11264. `;
  11265. // TODO: Change ORDER_NONE to the correct strength.
  11266. return code;
  11267. };
  11268. //
  11269. Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model'] = {
  11270. init: function () {
  11271. this.appendDummyInput()
  11272. .appendField(Blockly.Msg.numpy_mnist_loading_model);
  11273. this.appendValueInput("class_input")
  11274. .setCheck(null)
  11275. .appendField(Blockly.Msg.AUDIO_S_PF);
  11276. this.setPreviousStatement(true, null);
  11277. this.setNextStatement(true, null);
  11278. this.setColour("#ee783a");
  11279. this.setTooltip(Blockly.Msg.numpy_mnist_loading_model);
  11280. this.setHelpUrl("");
  11281. }
  11282. };
  11283. Blockly.Python['Numpy_Neural_Network_numpy_loading_model'] = function (block) {
  11284. var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  11285. // TODO: Assemble Python into code variable.
  11286. var code = `try:
  11287. with open(${trainUrl},"rb") as f:
  11288. b_data = pickle.load(f)
  11289. net_model = pickle.loads(b_data)
  11290. except:
  11291. pass
  11292. `;
  11293. // TODO: Change ORDER_NONE to the correct strength.
  11294. return code;
  11295. };
  11296. Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) {
  11297. var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  11298. var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC);
  11299. // TODO: Assemble Python into code variable.
  11300. var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str)
  11301. train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str)
  11302. `;
  11303. // TODO: Change ORDER_NONE to the correct strength.
  11304. return code;
  11305. };
  11306. Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_fun'] = {
  11307. init: function () {
  11308. // this.appendDummyInput()
  11309. // .appendField("获取检测结果");
  11310. this.appendDummyInput()
  11311. .appendField(Blockly.Msg.ai_models_init_source)
  11312. .appendField(new Blockly.FieldVariable("img_numpyrecognition"), "varitem");
  11313. this.setPreviousStatement(true, null);
  11314. this.setNextStatement(true, null);
  11315. this.setColour("#ee783a");
  11316. this.setTooltip(Blockly.Msg.ai_model_getclass_TOOLTIP);
  11317. this.setHelpUrl("");
  11318. }
  11319. };
  11320. Blockly.Python['Numpy_Neural_Network_numpy_loading_model_fun'] = function (block) {
  11321. var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  11322. Blockly.Python.definitions_["v831_import_PIL_image"] = `from PIL import Image`
  11323. Blockly.Python.definitions_["v831_function_numpy_result"] = `def numpyResult(img):
  11324. img_path="/root/user/image_1.png"
  11325. img_gray_path="/root/user/image_gray.png"
  11326. mk = img.crop(0, 0, 240, 240) #裁剪图像为320*240
  11327. mk1=img.crop(0, 0, 240, 240).resize(224,224) #继续裁剪图像为224*224
  11328. numpyResultcanvas= image.new(size = (320, 240), color = (0,255,0), mode = 'RGB') #创建背景图
  11329. numpyResultcanvas.draw_image(mk1.rotate(90,adjust=1),58,8) #贴224*224的图片
  11330. mk2=mk1.resize(28,28) #裁剪图片为28*28
  11331. numpyResultcanvas.draw_image(mk2,8,8) #贴28*28的图
  11332. mk2.save(img_path)
  11333. origin=Image.open(img_path).convert('L') #转为8位分辨率灰度图(0~255)
  11334. origin.save(img_gray_path)
  11335. origin_gray=image.open(img_gray_path)
  11336. numpyResultcanvas.draw_image(origin_gray,8,48)
  11337. numpyResultImg = np.array(origin).reshape(1, 784).astype('int')
  11338. numpyResultImg = numpyResultImg / 255 * 0.99 + 0.01
  11339. print(numpyResultImg.shape)
  11340. result = net_model.query(numpyResultImg)
  11341. return result
  11342. `
  11343. // TODO: Assemble Python into code variable.
  11344. var code = `GETNUMPYRESULT = numpyResult(${variable_name})
  11345. `;
  11346. // TODO: Change ORDER_NONE to the correct strength.
  11347. return code;
  11348. };
  11349. Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_result'] = {
  11350. init: function () {
  11351. this.appendDummyInput()
  11352. .appendField(Blockly.Msg.numpy_mnist_get_result);
  11353. this.setOutput(true, null);
  11354. this.setColour("#ee783a");
  11355. this.setTooltip(Blockly.Msg.numpy_mnist_get_result);
  11356. this.setHelpUrl("");
  11357. }
  11358. };
  11359. Blockly.Python['Numpy_Neural_Network_numpy_loading_model_result'] = function (block) {
  11360. var code = `GETNUMPYRESULT`;
  11361. // TODO: Change ORDER_NONE to the correct strength.
  11362. return [code, Blockly.Python.ORDER_NONE];
  11363. };
  11364. //
  11365. Blockly.Blocks['Numpy_Neural_Network_numpy_clear'] = {
  11366. init: function () {
  11367. this.appendDummyInput()
  11368. .appendField(Blockly.Msg.numpy_mnist_clear);
  11369. this.setPreviousStatement(true, null);
  11370. this.setNextStatement(true, null);
  11371. this.setColour("#ee783a");
  11372. this.setTooltip(Blockly.Msg.numpy_mnist_clear);
  11373. this.setHelpUrl("");
  11374. }
  11375. };
  11376. Blockly.Python['Numpy_Neural_Network_numpy_clear'] = function (block) {
  11377. var code = `os.system('rm -rf /usr/lib/python3.8/site-packages/numpy/random/__init__.py')
  11378. `;
  11379. // TODO: Change ORDER_NONE to the correct strength.
  11380. return code;
  11381. };
  11382. Blockly.Blocks["cocopi_chatGpt_init"] = {
  11383. init: function () {
  11384. this.appendDummyInput()
  11385. .appendField(Blockly.Msg.ChatGpt_init)
  11386. this.setPreviousStatement(true, null);
  11387. this.setNextStatement(true, null);
  11388. this.setColour("#7e3cca");
  11389. this.setTooltip(Blockly.Msg.ChatGpt_init);
  11390. this.setHelpUrl("");
  11391. }
  11392. };
  11393. Blockly.Python['cocopi_chatGpt_init'] = function (block) {
  11394. Blockly.Python.definitions_['v831_import_sys'] = `import sys
  11395. sys.path.append("/root/")`
  11396. Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try:
  11397. from CocoPi import GPTrequest
  11398. except:
  11399. import sys
  11400. sys.path.append("/root/preset/drivers/pylib/")
  11401. from GPTrequest import GPTrequest`
  11402. Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()`
  11403. var code = ``;
  11404. // TODO: Change ORDER_NONE to the correct strength.
  11405. return code;
  11406. };
  11407. Blockly.Blocks["cocopi_chatGpt_text_to_img_loading"] = {
  11408. init: function () {
  11409. this.appendDummyInput().appendField(Blockly.Msg.AIGC_select_model)
  11410. .appendField(new Blockly.FieldDropdown([
  11411. ["cogview-3", "cogview-3"],
  11412. ["cogview-3-flash", "cogview-3-flash"],
  11413. ["dall-e-3", "dall-e-3"],
  11414. ["dall-e-2", "dall-e-2"],
  11415. ]), "select_model");
  11416. this.appendValueInput("NAME")
  11417. .setCheck(null)
  11418. .appendField(Blockly.Msg.ChatGpt_set_img_des);
  11419. this.setPreviousStatement(true, null);
  11420. this.setNextStatement(true, null);
  11421. this.setColour("#7e3cca");
  11422. this.setTooltip(Blockly.Msg.ChatGpt_set_img_des);
  11423. this.setHelpUrl("");
  11424. }
  11425. };
  11426. Blockly.Python['cocopi_chatGpt_text_to_img_loading'] = function (block) {
  11427. var model = block.getFieldValue('select_model');
  11428. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  11429. Blockly.Python.addVariable("TextContent", `TextContent = ""`, true)
  11430. Blockly.Python.addVariable("text_to_img", `textToImgModel = "${model}"`, true)
  11431. var code = `TextContent = ${text}
  11432. `;
  11433. // TODO: Change ORDER_NONE to the correct strength.
  11434. return code;
  11435. };
  11436. Blockly.Blocks["cocopi_chatGpt_text_to_img_result"] = {
  11437. init: function () {
  11438. this.appendDummyInput()
  11439. .appendField(Blockly.Msg.ChatGpt_get_img_path_result);
  11440. this.setOutput(true, null);
  11441. this.setColour("#7e3cca");
  11442. this.setTooltip(Blockly.Msg.ChatGpt_get_img_path_result);
  11443. this.setHelpUrl("");
  11444. }
  11445. };
  11446. Blockly.Python['cocopi_chatGpt_text_to_img_result'] = function (block) {
  11447. var code = `gptInit.get_text_to_img(TextContent)`;
  11448. return [code, Blockly.Python.ORDER_ATOMIC];;
  11449. };
  11450. Blockly.Blocks["cocopi_chatGpt_image_to_text_loading"] = {
  11451. init: function () {
  11452. this.appendDummyInput().appendField(Blockly.Msg.AIGC_select_model)
  11453. .appendField(new Blockly.FieldDropdown([
  11454. ["4o", "gpt-4o"],
  11455. ["4o-mini", "gpt-4o-mini"],
  11456. ["qwen-vl-max", "qwen-vl-max"],
  11457. ["qwen-vl-plus", "qwen-vl-plus"],
  11458. // ["qwen-vl-ocr", "qwen-vl-ocr"],
  11459. ["glm-4v", "glm-4v"],
  11460. ["glm-4v-flash", "glm-4v-flash"],
  11461. ]), "select_model");
  11462. this.appendValueInput("NAME")
  11463. .setCheck(null)
  11464. .appendField(Blockly.Msg.ChatGpt_set_text_path);
  11465. this.appendValueInput("NAME1")
  11466. .setCheck(null)
  11467. .appendField(Blockly.Msg.ChatGpt_set_text_text_content);
  11468. this.setPreviousStatement(true, null);
  11469. this.setNextStatement(true, null);
  11470. this.setColour("#7e3cca");
  11471. this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
  11472. this.setHelpUrl("");
  11473. }
  11474. };
  11475. Blockly.Python['cocopi_chatGpt_image_to_text_loading'] = function (block) {
  11476. var model = block.getFieldValue('select_model');
  11477. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  11478. var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
  11479. Blockly.Python.addVariable("IMAGEPATH", `IMAGEPATH = ""`, true)
  11480. Blockly.Python.addVariable("IMAGECONTENT", `IMAGECONTENT = ""`, true)
  11481. Blockly.Python.addVariable("imageToTextModel", `imageToTextModel = ""`, true)
  11482. var code = `IMAGEPATH = ${text}
  11483. IMAGECONTENT = ${content}
  11484. imageToTextModel = "${model}"
  11485. `;
  11486. // TODO: Change ORDER_NONE to the correct strength.
  11487. return code;
  11488. };
  11489. Blockly.Blocks["cocopi_chatGpt_image_to_text_result"] = {
  11490. init: function () {
  11491. this.appendDummyInput()
  11492. .appendField(Blockly.Msg.ChatGpt_get_text_content_result);
  11493. this.setOutput(true, null);
  11494. this.setColour("#7e3cca");
  11495. this.setTooltip(Blockly.Msg.ChatGpt_get_text_content_result);
  11496. this.setHelpUrl("");
  11497. }
  11498. };
  11499. Blockly.Python['cocopi_chatGpt_image_to_text_result'] = function (block) {
  11500. var code = `gptInit.get_image_to_text(IMAGEPATH,IMAGECONTENT)`;
  11501. return [code, Blockly.Python.ORDER_ATOMIC];;
  11502. };
  11503. Blockly.Blocks["cocopi_chatGpt_text_to_voice_loading"] = {
  11504. init: function () {
  11505. this.appendDummyInput().appendField(Blockly.Msg.AIGC_select_model)
  11506. .appendField(new Blockly.FieldDropdown([
  11507. ["tts-1", "tts-1"],
  11508. ["tts-1-hd", "tts-1-hd"],
  11509. ]), "select_model");
  11510. this.appendValueInput("NAME")
  11511. .setCheck(null)
  11512. .appendField(Blockly.Msg.ChatGpt_set_text_content);
  11513. this.setPreviousStatement(true, null);
  11514. this.setNextStatement(true, null);
  11515. this.setColour("#7e3cca");
  11516. this.setTooltip(Blockly.Msg.ChatGpt_set_text_content);
  11517. this.setHelpUrl("");
  11518. }
  11519. };
  11520. Blockly.Python['cocopi_chatGpt_text_to_voice_loading'] = function (block) {
  11521. var model = block.getFieldValue('select_model');
  11522. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  11523. Blockly.Python.addVariable("VOICECONTENT", `VOICECONTENT = ""`, true)
  11524. Blockly.Python.addVariable("text_to_voice", `textToVoiceModel = ""`, true)
  11525. var code = `VOICECONTENT = ${text}
  11526. textToVoiceModel = "${model}"
  11527. `;
  11528. // TODO: Change ORDER_NONE to the correct strength.
  11529. return code;
  11530. };
  11531. Blockly.Blocks["cocopi_chatGpt_text_to_voice_result"] = {
  11532. init: function () {
  11533. this.appendDummyInput()
  11534. .appendField(Blockly.Msg.ChatGpt_get_voice_path_result);
  11535. this.setOutput(true, null);
  11536. this.setColour("#7e3cca");
  11537. this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result);
  11538. this.setHelpUrl("");
  11539. }
  11540. };
  11541. Blockly.Python['cocopi_chatGpt_text_to_voice_result'] = function (block) {
  11542. var code = `gptInit.get_text_to_voice(VOICECONTENT)`;
  11543. return [code, Blockly.Python.ORDER_ATOMIC];;
  11544. };
  11545. Blockly.Blocks["cocopi_chatGpt_voice_to_text_loading"] = {
  11546. init: function () {
  11547. this.appendDummyInput().appendField(Blockly.Msg.AIGC_select_model)
  11548. .appendField(new Blockly.FieldDropdown([
  11549. ["tts-1", "tts-1"],
  11550. ["tts-1-hd", "tts-1-hd"],
  11551. ]), "select_model");
  11552. this.appendValueInput("NAME")
  11553. .setCheck(null)
  11554. .appendField(Blockly.Msg.ChatGpt_set_voice_path);
  11555. this.setPreviousStatement(true, null);
  11556. this.setNextStatement(true, null);
  11557. this.setColour("#7e3cca");
  11558. this.setTooltip(Blockly.Msg.ChatGpt_set_voice_path);
  11559. this.setHelpUrl("");
  11560. }
  11561. };
  11562. Blockly.Python['cocopi_chatGpt_voice_to_text_loading'] = function (block) {
  11563. var model = block.getFieldValue('select_model');
  11564. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  11565. Blockly.Python.addVariable("VOICEPATH", `VOICEPATH = ""`, true)
  11566. Blockly.Python.addVariable("voiceToTextModel", `voiceToTextModel = ""`, true)
  11567. var code = `VOICEPATH = ${text}
  11568. voiceToTextModel = ""
  11569. `;
  11570. // TODO: Change ORDER_NONE to the correct strength.
  11571. return code;
  11572. };
  11573. Blockly.Blocks["cocopi_chatGpt_voice_to_text_result"] = {
  11574. init: function () {
  11575. this.appendDummyInput()
  11576. .appendField(Blockly.Msg.ChatGpt_get_voice_text_content_result);
  11577. this.setOutput(true, null);
  11578. this.setColour("#7e3cca");
  11579. this.setTooltip(Blockly.Msg.ChatGpt_get_voice_text_content_result);
  11580. this.setHelpUrl("");
  11581. }
  11582. };
  11583. Blockly.Python['cocopi_chatGpt_voice_to_text_result'] = function (block) {
  11584. var code = `gptInit.get_voice_to_text(VOICEPATH)`;
  11585. return [code, Blockly.Python.ORDER_ATOMIC];;
  11586. };
  11587. Blockly.Blocks["cocopi_chatGpt_post_chatgpt_loading"] = {
  11588. init: function () {
  11589. this.appendDummyInput().appendField(Blockly.Msg.AIGC_select_model)
  11590. .appendField(new Blockly.FieldDropdown([
  11591. ["deepseek-chat", "deepseek-chat"],
  11592. ["4o", "gpt-4o"],
  11593. ["4o-mini", "gpt-4o-mini"],
  11594. ["qwen-max", "qwen-max"],
  11595. ["qwen-turbo", "qwen-turbo"],
  11596. ["qwen-max-longcontext", "qwen-max-longcontext"],
  11597. ["qwen-long", "qwen-long"],
  11598. ["qwen-plus", "qwen-plus"],
  11599. ["glm-4-plus", "glm-4-plus"],
  11600. ["glm-4-flash", "glm-4-flash"],
  11601. ["llama3.2", "llama3.2"],
  11602. ["deepseek-reasoner", "deepseek-reasoner"],
  11603. ["deepseek-r1:latest", "deepseek-r1:latest"],
  11604. ["deepseek-r1:8b", "deepseek-r1:8b"],
  11605. ]), "select_model");
  11606. this.appendValueInput("NAME")
  11607. .setCheck(null)
  11608. .appendField(Blockly.Msg.ChatGpt_set_problem_content);
  11609. this.setPreviousStatement(true, null);
  11610. this.setNextStatement(true, null);
  11611. this.setColour("#7e3cca");
  11612. this.setTooltip(Blockly.Msg.ChatGpt_set_problem_content);
  11613. this.setHelpUrl("");
  11614. }
  11615. };
  11616. Blockly.Python['cocopi_chatGpt_post_chatgpt_loading'] = function (block) {
  11617. var model = block.getFieldValue('select_model');
  11618. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  11619. Blockly.Python.addVariable("CHATGPTPROBLEM", `CHATGPTPROBLEM = ""`, true)
  11620. Blockly.Python.addVariable("chatGptModel", `chatGptModel = ""`, true)
  11621. var code = `CHATGPTPROBLEM = ${text}
  11622. chatGptModel = "${model}"
  11623. `;
  11624. // TODO: Change ORDER_NONE to the correct strength.
  11625. return code;
  11626. };
  11627. Blockly.Blocks["cocopi_chatGpt_post_chatgpt_result"] = {
  11628. init: function () {
  11629. this.appendDummyInput()
  11630. .appendField(Blockly.Msg.ChatGpt_get_problem_result);
  11631. this.setOutput(true, null);
  11632. this.setColour("#7e3cca");
  11633. this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result);
  11634. this.setHelpUrl("");
  11635. }
  11636. };
  11637. Blockly.Python['cocopi_chatGpt_post_chatgpt_result'] = function (block) {
  11638. var code = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`;
  11639. return [code, Blockly.Python.ORDER_ATOMIC];;
  11640. };
  11641. //
  11642. Blockly.Blocks["cocopi_chatGpt_result"] = {
  11643. init: function () {
  11644. this.appendDummyInput()
  11645. // .appendField(Blockly.Msg.ChatGpt_get_problem_result)
  11646. .appendField(new Blockly.FieldDropdown([
  11647. [Blockly.Msg.ChatGpt_get_img_path_result, "1"],
  11648. [Blockly.Msg.ChatGpt_get_text_content_result, "2"],
  11649. [Blockly.Msg.ChatGpt_get_voice_path_result, "3"],
  11650. [Blockly.Msg.ChatGpt_get_voice_text_content_result, "4"],
  11651. [Blockly.Msg.ChatGpt_get_problem_result, "5"],
  11652. [Blockly.Msg.ChatGpt_ai_agent_chat_result, "6"]
  11653. ]), "gpt_return");
  11654. this.setOutput(true, null);
  11655. this.setColour("#7e3cca");
  11656. this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result);
  11657. this.setHelpUrl("");
  11658. }
  11659. };
  11660. Blockly.Python['cocopi_chatGpt_result'] = function (block) {
  11661. var queue_value = block.getFieldValue('gpt_return');
  11662. var res = ``;
  11663. let resModel = ""
  11664. if (queue_value == 5) {
  11665. res = `gptInit.get_post_chatgpt(CHATGPTPROBLEM,chatGptModel)`
  11666. resModel = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`
  11667. } else if (queue_value == 4) {
  11668. res = `gptInit.get_voice_to_text(VOICEPATH,voiceToTextModel)`
  11669. resModel = `gptInit.get_voice_to_text(VOICEPATH)`
  11670. } else if (queue_value == 3) {
  11671. res = `gptInit.get_text_to_voice(VOICECONTENT,textToVoiceModel)`
  11672. resModel = `gptInit.get_text_to_voice(VOICECONTENT)`
  11673. } else if (queue_value == 2) {
  11674. res = `gptInit.get_image_to_text(IMAGEPATH,IMAGECONTENT,imageToTextModel)`
  11675. resModel = `gptInit.get_image_to_text(IMAGEPATH,IMAGECONTENT)`
  11676. } else if (queue_value == 1) {
  11677. res = `gptInit.get_text_to_img(TextContent,textToImgModel)`
  11678. resModel = `gptInit.get_text_to_img(TextContent)`
  11679. }
  11680. else if (queue_value == 6) {
  11681. res = `gptInit.get_post_AI_Intelligence(AIAGENTCHATID,AIAGENTCHATMESSAGE,AIAGENTMODEL)`
  11682. resModel = `gptInit.get_post_AI_Intelligence(AIAGENTCHATID,AIAGENTCHATMESSAGE)`
  11683. }
  11684. Blockly.Python.definitions_["CocoPiGPTRESULTFUNC"+queue_value] = `def CocoPiGPTRESULTFUNC${queue_value}():
  11685. try:
  11686. CocoPiGPTRESULT = ${res}
  11687. except:
  11688. CocoPiGPTRESULT = ${resModel}
  11689. return CocoPiGPTRESULT
  11690. `
  11691. var code = `CocoPiGPTRESULTFUNC${queue_value}()`;
  11692. return [code, Blockly.Python.ORDER_ATOMIC];;
  11693. };
  11694. Blockly.Blocks["cocopi_chatGpt_AI_loading"] = {
  11695. init: function () {
  11696. this.appendDummyInput().appendField(Blockly.Msg.AIGC_select_model)
  11697. .appendField(new Blockly.FieldDropdown([
  11698. ["4o-mini", "gpt-4o-mini"],
  11699. ["4o", "gpt-4o"],
  11700. ]), "select_model");
  11701. this.appendValueInput("NAME")
  11702. .setCheck(null)
  11703. .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID);
  11704. this.appendValueInput("NAME1")
  11705. .setCheck(null)
  11706. .appendField(Blockly.Msg.ChatGpt_set_text_text_content);
  11707. this.setPreviousStatement(true, null);
  11708. this.setNextStatement(true, null);
  11709. this.setColour("#7e3cca");
  11710. this.setTooltip(Blockly.Msg.ChatGpt_set_text_path);
  11711. this.setHelpUrl("");
  11712. }
  11713. };
  11714. Blockly.Python['cocopi_chatGpt_AI_loading'] = function (block) {
  11715. var model = block.getFieldValue('select_model');
  11716. var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  11717. var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC);
  11718. Blockly.Python.addVariable("AIAGENTCHATID", `AIAGENTCHATID = ""`, true)
  11719. Blockly.Python.addVariable("AIAGENTCHATMESSAGE", `AIAGENTCHATMESSAGE = ""`, true)
  11720. Blockly.Python.addVariable("AIAGENTMODEL", `AIAGENTMODEL = ""`, true)
  11721. var code = `AIAGENTCHATID = ${text}
  11722. AIAGENTCHATMESSAGE = ${content}
  11723. AIAGENTMODEL = "${model}"
  11724. `
  11725. return code;
  11726. };
  11727. // 设置ai聊天机器人的url文件名
  11728. Blockly.Blocks["set_cocopi_agent_file_name"] = {
  11729. init: function () {
  11730. this.appendValueInput("fileName")
  11731. .setCheck(null)
  11732. .appendField(Blockly.Msg.set_cocopi_agent_file_name);
  11733. this.setPreviousStatement(true, null);
  11734. this.setNextStatement(true, null);
  11735. this.setColour("#7e3cca");
  11736. this.setTooltip(Blockly.Msg.set_cocopi_agent_file_name);
  11737. this.setHelpUrl("");
  11738. }
  11739. };
  11740. Blockly.Python['set_cocopi_agent_file_name'] = function (block) {
  11741. var text = Blockly.Python.valueToCode(block, 'fileName', Blockly.Python.ORDER_ATOMIC);
  11742. localStorage.setItem("cocopi_agent_file_name", text);
  11743. var code = `set_cocopi_agent_file_name = True \n`;
  11744. // TODO: Change ORDER_NONE to the correct strength.
  11745. return code;
  11746. };
  11747. // 获取aigent 代码并执行
  11748. Blockly.Blocks["get_cocopi_agent_exec"] = {
  11749. init: function () {
  11750. this.appendDummyInput()
  11751. .appendField(Blockly.Msg.get_cocopi_agent_exec_title);
  11752. this.appendValueInput("message")
  11753. .setCheck(null)
  11754. .appendField(Blockly.Msg.get_cocopi_agent_exec_message);
  11755. this.appendValueInput("packages")
  11756. .setCheck(null)
  11757. .appendField(Blockly.Msg.get_cocopi_agent_exec_packages);
  11758. this.setPreviousStatement(true, null);
  11759. this.setNextStatement(true, null);
  11760. this.setColour("#7e3cca");
  11761. this.setTooltip(Blockly.Msg.get_cocopi_agent_exec_title);
  11762. this.setHelpUrl("");
  11763. }
  11764. };
  11765. Blockly.Python['get_cocopi_agent_exec'] = function (block) {
  11766. var message = Blockly.Python.valueToCode(block, 'message', Blockly.Python.ORDER_ATOMIC);
  11767. var packages = Blockly.Python.valueToCode(block, 'packages', Blockly.Python.ORDER_ATOMIC);
  11768. let packagesArr = JSON.parse(packages)
  11769. console.log(packagesArr)
  11770. let packagesStr = ""
  11771. packagesArr.map((a) => {
  11772. packagesStr += `import ${a.toLowerCase()} \n`
  11773. })
  11774. Blockly.Python.definitions_['import_cocopi_requests'] = 'import requests';
  11775. Blockly.Python.definitions_['import_cocopi_os'] = 'import os';
  11776. var code = `import sys
  11777. sys.path.append("/root/user/app/")
  11778. ${packagesStr}
  11779. url = "http://gpt4.cocorobo.cn/mini_pi/gen_code"
  11780. cmd="cat /sys/class/sunxi_info/sys_info"
  11781. rec=os.popen(cmd).read()
  11782. hwMac=rec[rec.find("sunxi_serial : ")+20:rec.find("sunxi_serial : ")+52]
  11783. params = {
  11784. "sn":hwMac,
  11785. "message":${message},
  11786. "packages": ${packages}
  11787. }
  11788. try:
  11789. response = requests.post(url, data=params) # 确保替换为正确的URL
  11790. if response.status_code == 200:
  11791. try:
  11792. exec(response.text)
  11793. except Exception as e:
  11794. print(f"执行响应文本时发生错误: {e}")
  11795. else:
  11796. print(f"请求错误,状态码:{response.status_code}")
  11797. except requests.exceptions.RequestException as e:
  11798. print(f"网络请求错误: {e}")
  11799. `;
  11800. // TODO: Change ORDER_NONE to the correct strength.
  11801. return code;
  11802. };