/* _ ___ ____ _ / \ |_ _| | __ ) __ _ ___(_) ___ / _ \ | | | _ \ / _` / __| |/ __| / ___ \ | | | |_) | (_| \__ \ | (__ /_/ \_\___| |____/ \__,_|___/_|\___| */ Blockly.Blocks['ai_v831_button_read_pressed_canvas'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_button_when) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ai_basic_pressed) this.setOutput(true, null); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('button_type'); var TOOLTIPS = { '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"), '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"), '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"), '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"), }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_button_read_pressed_canvas'] = function (block) { var _type = block.getFieldValue('button_type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` var code = `key_${_type}.is_pressed()` return [code, Blockly.Python.ORDER_CONDITIONAL]; }; Blockly.Blocks['ai_v831_button_read_pressed'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.TOUCH_CASE) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ai_basic_pressed) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); // this.setOutput(true, null); this.setNextStatement(true); this.setPreviousStatement(true); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('button_type'); var TOOLTIPS = { '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"), '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"), '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"), '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"), }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_button_read_pressed'] = function (block) { var _type = block.getFieldValue('button_type'); var statements_input = Blockly.Python.statementToCode(block, 'input'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("BUTTON" + _type, `def BUTTON${_type}(): ${global ? 'global ' + global : ""} ${statements_input || " pass"}\n`, true) var code = `if key_${_type}.is_pressed(): BUTTON${_type}() ` return code; }; Blockly.Blocks['ai_v831_button_read_released'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.TOUCH_CASE) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ai_basic_pressed_one) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); // this.setOutput(true, null); this.setNextStatement(true); this.setPreviousStatement(true); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('button_type'); var TOOLTIPS = { '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"), '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"), '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"), '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"), }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_button_read_released'] = function (block) { var _type = block.getFieldValue('button_type'); var statements_input = Blockly.Python.statementToCode(block, 'input'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("BUTTONisPressed" + _type, `def BUTTONisPressed${_type}(): ${global ? 'global ' + global : ""} ${statements_input || " pass"}\n`, true) var code = `if key_${_type}.is_pressed(): while not (key_${_type}.is_pressed() == False): time.sleep(0.1) BUTTONisPressed${_type}() ` return code; }; Blockly.Blocks['ai_v831_button_loosen'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.TOUCH_CASE) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ESP32RELEASED) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); // this.setOutput(true, null); this.setNextStatement(true); this.setPreviousStatement(true); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('button_type'); var TOOLTIPS = { '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"), '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"), '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"), '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"), }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_button_loosen'] = function (block) { var _type = block.getFieldValue('button_type'); var statements_input = Blockly.Python.statementToCode(block, 'input'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("NOBUTTONisPressed" + _type, `def NOBUTTONisPressed${_type}(): ${global ? 'global ' + global : ""} ${statements_input || " pass"}\n`, true) var code = `if key_${_type}.is_pressed() == False: NOBUTTONisPressed${_type}() ` return code; }; Blockly.Blocks['ai_v831_button_del'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_button_when) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type_released") .appendField(Blockly.Msg.ai_basic_released) this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('button_type_released'); var TOOLTIPS = { '0': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"), '1': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"), '2': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"), '3': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"), }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_button_del'] = function (block) { var _type = block.getFieldValue('button_type_released'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` var code = `key_${_type}.button.release() del key_${_type} ` return code; }; Blockly.Blocks['ai_v831_led_light_up'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_led_set) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_basic_led_blue, "blue"], // [Blockly.Msg.ai_basic_led_red, "red"] ]), "type") .appendField(Blockly.Msg.ai_basic_led_on); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('type'); var TOOLTIPS = { 'blue': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue), 'red': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_led_light_up'] = function (block) { var dropdown_type = block.getFieldValue('type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED LED = LED() ` // TODO: Assemble Python into code variable. var code = `LED.out(1) `; return code; }; Blockly.Blocks['ai_v831_led_light_off'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_led_set) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_basic_led_blue, "blue"], // [Blockly.Msg.ai_basic_led_red, "red"] ]), "type") .appendField(Blockly.Msg.ai_basic_led_off); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('type'); var TOOLTIPS = { 'blue': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue), 'red': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_led_light_off'] = function (block) { var dropdown_type = block.getFieldValue('type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_CocoPi_LED'] = `from CocoPi import LED LED = LED() ` // TODO: Assemble Python into code variable. var code = `LED.out(0) `; return code; }; Blockly.Blocks['ai_v831_rgb_light_up'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_rgb_set_on) this.appendValueInput("rgb_value") .setCheck(null) .appendField(""); this.appendDummyInput() .appendField(Blockly.Msg.LED_BRTN).appendField(new Blockly.FieldNumber(50, 0, 255), "uart_bps"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#d42b03"); this.setTooltip(Blockly.Msg.ai_basic_rgb_set_on); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_rgb_light_up'] = function (block) { var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC); var content = block.getFieldValue('uart_bps'); console.log(value_name.slice(1, -1)) Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb singleRgb=singleRgb()`; var code = `singleRgb.setBrightness(${content}) singleRgb.setColor(${value_name.slice(1, -1)}) time.sleep(0.05) singleRgb.show() `; return code; }; Blockly.Blocks['ai_v831_rgb_light_off'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_rgb_set_off) this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#d42b03"); this.setTooltip(Blockly.Msg.ai_basic_rgb_set_off); this.setHelpUrl(""); } }; Blockly.Python['ai_v831_rgb_light_off'] = function (block) { var dropdown_type = block.getFieldValue('type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_smbus2'] = `import smbus2` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_CocoPi_RGB'] = `from CocoPi import singleRgb singleRgb=singleRgb()`; // TODO: Assemble Python into code variable. var code = `singleRgb.setColor(0,0,0) time.sleep(0.05) singleRgb.show() `; return code; }; Blockly.Blocks['ai_basic_light_up_led_analog'] = { init: function () { this.appendValueInput("brightness") .setCheck(null) .appendField(Blockly.Msg.ai_basic_led_analog_set) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_basic_led_analog_led1, "1"], [Blockly.Msg.ai_basic_led_analog_led2, "2"] ]), "type") .appendField(Blockly.Msg.ai_basic_led_analog_brightness_text); this.appendDummyInput() .appendField(Blockly.Msg.ai_basic_led_analog_range_text); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#d42b03"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('type'); var TOOLTIPS = { '1': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led1), '2': Blockly.Msg.ai_basic_light_up_led_analog_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_analog_led2) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_basic_light_up_led_analog'] = function (block) { var dropdown_type = block.getFieldValue('type'); var value_brightness = Blockly.Python.valueToCode(block, 'brightness', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['ai_basic_light_up_led_analog_def'] = '' + 'from machine import Timer,PWM\n' + '\n' + 'led_left_tim = Timer(Timer.TIMER2, Timer.CHANNEL0, mode=Timer.MODE_PWM)\n' + 'led_right_tim = Timer(Timer.TIMER2, Timer.CHANNEL1, mode=Timer.MODE_PWM)\n' + 'led_left_ctrl = PWM(led_left_tim, freq=500000, duty=50, pin=31)\n' + 'led_right_ctrl = PWM(led_right_tim, freq=500000, duty=50, pin=32)\n' + '\n' + 'def analog_light(which, brightness):\n' + ' if which == 1:\n' + ' led_left_ctrl.duty(brightness)\n' + ' if which == 2:\n' + ' led_right_ctrl.duty(brightness)\n' + ''; // TODO: Assemble Python into code variable. var code = 'analog_light(' + dropdown_type + ',' + value_brightness + ')\n'; return code; }; /* _ ___ ___ ____ / \ |_ _| |_ _|_ __ ___ __ _ __ _ ___ | _ \ _ __ ___ ___ ___ ___ ___ / _ \ | | | || '_ ` _ \ / _` |/ _` |/ _ \ | |_) | '__/ _ \ / __/ _ \/ __/ __| / ___ \ | | | || | | | | | (_| | (_| | __/ | __/| | | (_) | (_| __/\__ \__ \ /_/ \_\___| |___|_| |_| |_|\__,_|\__, |\___| |_| |_| \___/ \___\___||___/___/ |___/ */ Blockly.Blocks["ai_lcd_screeninit"] = { init: function () { // this.appendDummyInput() // .appendField(new Blockly.FieldImage("blockly/media/screen_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); // this.appendDummyInput() // .appendField(Blockly.Msg.image_process_lcd_init); this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_direction) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_lcd_landscape_screen, "False"], [Blockly.Msg.image_process_lcd_vertical_screen, "True"] ]), "isScreen") this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5cb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_screeninit_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_screeninit = function (block) { var isScreen = block.getFieldValue('isScreen'); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` // Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = ${isScreen}`, false) Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['v831_camera_set_ScreenOrientation'] = `ScreenOrientation = ${isScreen}` var _code = ``; return _code;; } Blockly.Blocks['ai_lcd_rotation'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.LCD_CANVAS + Blockly.Msg.image_process_set_lcd_rotation) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() .appendField(new Blockly.FieldDropdown([ ["0°", "0"], ["90°", "90"], ["180°", "180"], ["270°", "270"] ]), "DEGREE") .appendField(Blockly.Msg.CATEGORY_SHOW) this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_rotation_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_rotation = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_name = block.getFieldValue('DEGREE'); Blockly.Python.addFunction('v831_rotation_fun', `def screenShow(inputImg,rotationAngle): if rotationAngle==90 or rotationAngle == 270: screenCapture=inputImg.crop(0,0,240,320) else: screenCapture=inputImg.crop(0,0,320,240) canvas_screenShow = screenCapture.rotate(-rotationAngle,adjust=1) display.show(canvas_screenShow) `) let w = '' let h = '' if (dropdown_name == 90 || dropdown_name == 270) { w = 240 h = 320 } else { w = 320 h = 240 } var _code = `screenShow(canvas,${dropdown_name}) `; return _code;; } Blockly.Blocks['ai_lcd_font'] = { init: function () { this.appendDummyInput().appendField(Blockly.Msg.image_lcd_set_font) this.appendValueInput("save_path") .setCheck(null) this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.image_lcd_set_font); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_font = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var font_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC); var _code = `image.load_freetype(${font_path})\n`; return _code;; } Blockly.Blocks['ai_lcd_filp'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_set_lcd_mirror_flip) .appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox'); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_filp_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_filp = function (block) { var _tf = block.getFieldValue('TextCheckBox') == 'TRUE' ? "True" : "False"; var _code = "lcd.mirror(" + _tf + ")\n"; return _code; } Blockly.Blocks['ai_lcd_screen'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_set_filled_screen_color) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_set_filled_screen_color_red, "RED"], [Blockly.Msg.image_process_set_filled_screen_color_green, "GREEN"], [Blockly.Msg.image_process_set_filled_screen_color_blue, "BLUE"], [Blockly.Msg.image_process_set_filled_screen_color_purple, "PURPLE"], [Blockly.Msg.image_process_set_filled_screen_color_cyan, "CYAN"], [Blockly.Msg.image_process_set_filled_screen_color_orange, "ORANGE"], [Blockly.Msg.image_process_set_filled_screen_color_yellow, "YELLOW"], [Blockly.Msg.image_process_set_filled_screen_color_black, "BLACK"], [Blockly.Msg.image_process_set_filled_screen_color_white, "WHITE"] ]), "COLOR"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('COLOR'); var TOOLTIPS = { 'RED': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_red), 'GREEN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_green), 'BLUE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_blue), 'PURPLE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_purple), 'CYAN': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_cyan), 'ORANGE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_orange), 'YELLOW': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_yellow), 'BLACK': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_black), 'WHITE': Blockly.Msg.ai_lcd_screen_TOOLTIP.replace('%1', Blockly.Msg.image_process_set_filled_screen_color_white) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_screen = function (block) { var colour_name = block.getFieldValue('COLOR'); var _code = "lcd.clear(lcd." + colour_name + ")\n"; return _code; } Blockly.Blocks['ai_lcd_fill_screen_with_rgb'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color); this.appendValueInput("rgb_value") .setCheck(null) .appendField(""); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_fill_screen_with_rgb_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_lcd_fill_screen_with_rgb'] = function (block) { var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. if (value_name.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == value_name.length && (d = parseInt(value_name.substring(1, 3), 16), e = parseInt(value_name.substring(3, 5), 16), f = parseInt(value_name.substring(5, 7), 16)) } catch (g) { } // TODO: Assemble Python into code variable. value_name = "(" + d + "," + e + "," + f + ")"; } var code = `try: if ScreenOrientation: canvas = image.new(size = (240, 320), color = ${value_name}, mode = "RGB") else: canvas = image.new(size = (320, 240), color = ${value_name}, mode = "RGB") except: canvas = image.new(size = (320, 240), color = ${value_name}, mode = "RGB") `; return code; }; Blockly.Blocks['ai_lcd_clear'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_clear_lcd); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_clear_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_clear = function (block) { var _code = "lcd.clear(lcd.BLACK)\n"; return _code; } Blockly.Blocks['ai_lcd_rgb_value_input'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_rgb_r); this.appendValueInput("rgb_value_r") .setCheck(null) .appendField(""); this.appendDummyInput() .appendField(Blockly.Msg.image_process_rgb_g); this.appendValueInput("rgb_value_g") .setCheck(null) .appendField(""); this.appendDummyInput() .appendField(Blockly.Msg.image_process_rgb_b); this.appendValueInput("rgb_value_b") .setCheck(null) .appendField(""); this.setInputsInline(true); this.setOutput(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_rgb_value_input_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_lcd_rgb_value_input'] = function (block) { var value_rgb_value_r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC); var value_rgb_value_g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC); var value_rgb_value_b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = '' + value_rgb_value_r + ',' + value_rgb_value_g + ',' + value_rgb_value_b + ''; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks.ai_lcd_XY = { init: function () { var _input = this.appendDummyInput(); this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL); this.setTooltip(Blockly.Msg.ai_lcd_XY_TOOLTIP); this.setColour("#5bb2d6"); this.setOutput(!0, "Boolean"); _input.appendField(Blockly.Msg.image_process_xy_x); this.appendValueInput("A").setCheck("Number"); _input = this.appendDummyInput(); _input.appendField(Blockly.Msg.image_process_xy_y) this.appendValueInput("B").setCheck("Number"); this.setInputsInline(!0); } }; Blockly.Python.ai_lcd_XY = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC); var code = "" + _x + ", " + _y + ""; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks.ai_lcd_WH = { init: function () { var _input = this.appendDummyInput(); this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL); this.setTooltip(Blockly.Msg.ai_lcd_WH_TOOLTIP); this.setColour("#5bb2d6"); this.setOutput(!0, "Boolean"); _input.appendField(Blockly.Msg.image_process_wh_width); this.appendValueInput("A").setCheck("Number"); _input = this.appendDummyInput(); _input.appendField(Blockly.Msg.image_process_wh_height) this.appendValueInput("B").setCheck("Number"); this.setInputsInline(!0); } }; Blockly.Python.ai_lcd_WH = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC); var code = "" + _x + ", " + _y + ""; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_lcd_colortext'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_lcd_show_text); this.appendDummyInput() .appendField(Blockly.Msg.image_process_lcd_show_text_color) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"], [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"], [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"], [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"], [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"], [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"], [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"], [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"], [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"] ]), "COLOR"); this.appendDummyInput() .appendField(Blockly.Msg.image_process_lcd_show_text_bg_color) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"], [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"], [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"], [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"], [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"], [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"], [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"], [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"], [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"] ]), "BCOLOR"); this.appendValueInput("CONTENT") .setCheck("String") .appendField(Blockly.Msg.image_process_text_content); /* this.appendDummyInput() .appendField(Blockly.Msg.LCDDT); */ this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_text_start_coord); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python['ai_lcd_colortext'] = function (block) { var color = block.getFieldValue("COLOR"); var bcolor = block.getFieldValue("BCOLOR"); var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); //var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC); var _code = "lcd_draw_string(lcd," + xy + ", " + content + ", color=" + color + ")\n"; //, scale=" + size + " // return [_code, Blockly.Python.ORDER_ATOMIC] return _code; }; Blockly.Blocks["ai_lcd_createnonecarvas"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_create_blank_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem"); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.image_process_text_size); // this.appendDummyInput() // .appendField(Blockly.Msg.LCDDCC_F) // .appendField(new Blockly.FieldCheckbox("TRUE"), "check") // .appendField(Blockly.Msg.LCDDCC_I) // .appendField(new Blockly.FieldTextInput(""), "text"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5cb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_createnonecarvas_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_createnonecarvas = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); var _code = variable_name + " = image.new(size = (" + value_wh + "))\n"; return _code; } Blockly.Blocks["ai_lcd_fillcanvas"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem"); this.appendValueInput("color") .setCheck(null) .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5cb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_fillcanvas_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_fillcanvas = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC); var _code = variable_name + '.draw_rectangle(0,0, ' + variable_name + '.width(),' + variable_name + '.height(), color=' + value_color + ', thickness=1, fill=True)\n'; return _code; } Blockly.Blocks["ai_lcd_createcarvas"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_create_image_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem"); this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.image_process_create_image_canvas_path); this.setPreviousStatement(true, null); this.setNextStatement(true, null); // this.setInputsInline(true); this.setColour("#5cb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_createcarvas_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_createcarvas = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var checkbox_name = block.getFieldValue('check') == 'TRUE' ? "True" : "False"; var text_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var _code = variable_name + " = image.open(" + text_name + ")\n"; return _code; } Blockly.Blocks['ai_lcd_showcarvas_set_cord'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_set_canvas_setup) // .appendField(new Blockly.FieldVariable("canvas"), "varitem"); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.image_process_text_start_coord_as); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5cb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_cord_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_lcd_showcarvas_set_cord = function (block) { var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = "_canvas_x, _canvas_y = " + value_name + "\n"; return code; }; Blockly.Blocks['ai_lcd_showcarvas_set_display'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_show_canvas) // .appendField(new Blockly.FieldVariable("canvas"), "varitem"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5cb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_display_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_lcd_showcarvas_set_display = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg` Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.addVariable(`_canvas_x`, `_canvas_x = 0`, true) Blockly.Python.addVariable(`_canvas_y`, `_canvas_y = 0`, true) Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` Blockly.Python.definitions_[`v831_display_show_canvas`] = `def v831_display_show_canvas(displayShow,_canvas_x,_canvas_y): global ScreenOrientation,cameraSize try: if ScreenOrientation: displayShowCanvas = image.new(size = (240, 320)) displayShowCanvas.draw_rectangle(0,0,240,320, color=(0,0,0), thickness=-1) displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1) displayShowVER = displayShowCanvas.crop(0,0,240,320) displayShowVER = displayShowVER.rotate(-90, adjust=1) display.show(displayShowVER) else: displayShowCanvas = image.new(size = (320, 240)) displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1) displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1) display.show(displayShowCanvas) except: displayShowCanvas = image.new(size = (320, 240)) displayShowCanvas.draw_rectangle(0,0,320,240, color=(0,0,0), thickness=-1) displayShowCanvas.draw_image(displayShow,_canvas_x,_canvas_y,alpha=1) display.show(displayShowCanvas) ` var code = `v831_display_show_canvas(canvas,_canvas_x,_canvas_y) `; return code; }; Blockly.Blocks['ai_lcd_showcarvas'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_show_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem"); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.image_process_text_start_coord); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5cb2d6"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python.ai_lcd_showcarvas = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = "lcd.display(" + variable_name + ", oft=(" + value_name + "))\n"; return code; }; Blockly.Blocks['ai_lcd_clearcanvas'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_clear_canvas_1 + Blockly.Msg.image_process_clear_canvas_2) this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_clearcanvas_TOOLTIP); this.setHelpUrl(''); } } Blockly.Python.ai_lcd_clearcanvas = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var _code = "canvas.clear()\n"; return _code;; } Blockly.Blocks['lcd_set_position'] = { init: function () { this.appendValueInput("POSX") .setCheck("Number") .appendField("X:"); this.appendValueInput("POSY") .setCheck("Number") .appendField("Y:"); this.setOutput(true, "String"); this.setInputsInline(true); this.setColour("#5bb2d6"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['lcd_set_position'] = function (block) { // var reg = /^?[0-9]\d*$/ var pos_x = Blockly.Python.valueToCode(block, 'POSX', Blockly.Python.ORDER_ATOMIC); var pos_y = Blockly.Python.valueToCode(block, 'POSY', Blockly.Python.ORDER_ATOMIC); //var code = posConvert(pos_x, pos_y); var code = pos_x + "," + pos_y; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['lcd_set_color'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.COLOR) .appendField(new Blockly.FieldColour("#ff0000"), "COLOR"); this.setOutput(true, "String"); this.setColour("#5bb2d6"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['lcd_set_color'] = function (block) { var code = block.getFieldValue('COLOR'); return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['lcd_set_width_height'] = { init: function () { this.appendValueInput("WIDTH") .setCheck("Number") .appendField(Blockly.Msg.OLCD_WIDTH); this.appendValueInput("HEIGHT") .setCheck("Number") .appendField(Blockly.Msg.OLCD_HEIGHT); this.setOutput(true, "String"); this.setInputsInline(true); this.setColour("#5bb2d6"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['lcd_set_width_height'] = function (block) { var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC); var height = Blockly.Python.valueToCode(block, 'HEIGHT', Blockly.Python.ORDER_ATOMIC); var code = width + ', ' + height; return [code, Blockly.Python.ORDER_ATOMIC]; }; // ai_lcd_textcarvas_new_line Blockly.Blocks['ai_lcd_textcarvas_new_line'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_text_start_coord); this.appendValueInput("CONTENT") .setCheck("String") .appendField(Blockly.Msg.image_process_text_content); this.appendValueInput("dispalyStr") .setCheck("Number") .appendField(Blockly.Msg.image_process_text_dispalyStr); this.appendValueInput("buttonUp") .setCheck("String") .appendField(Blockly.Msg.image_process_text_buttonDown); this.appendValueInput("buttonDown") .setCheck("String") .appendField(Blockly.Msg.image_process_text_buttonUp); this.appendValueInput("COLOR") .setCheck("String") .appendField(Blockly.Msg.image_process_text_color); this.appendValueInput("Scale") .setCheck("Number") .appendField(Blockly.Msg.image_process_draw_text_font_size); this.appendValueInput("LineNum") .setCheck("Number") .appendField(Blockly.Msg.image_process_text_line_heigit); // this.appendDummyInput() // .appendField(Blockly.Msg.image_process_draw_text_if_monospace) // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool"); this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_textcarvas_new_line = function (block) { var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); var LineNum = Blockly.Python.valueToCode(block, 'LineNum', Blockly.Python.ORDER_ATOMIC); var dispalyStr = Blockly.Python.valueToCode(block, 'dispalyStr', Blockly.Python.ORDER_ATOMIC); var buttonUp = Blockly.Python.valueToCode(block, 'buttonUp', Blockly.Python.ORDER_ATOMIC); var buttonDown = Blockly.Python.valueToCode(block, 'buttonDown', Blockly.Python.ORDER_ATOMIC); // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` var _code = "" Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7)` Blockly.Python.definitions_["ai_lcd_textcarvas_new_line"] = `BUTTONNUMBER = 0 def textCanvasNewLine(canvasName,posax,posay,text,Num,buttonUp,buttonDown,Scale,Color,LineNum): global BUTTONNUMBER,ScreenOrientation numText = len(text)//Num + 1 lineHeight = 240 if ScreenOrientation: lineHeight = 320 if numText>(lineHeight//LineNum): if buttonUp: time.sleep(0.1) if BUTTONNUMBER0: BUTTONNUMBER = BUTTONNUMBER - 1 #BUTTONNUMBER = BUTTONNUMBER + (posay/LineNum) for i in range(numText): canvasName.draw_string(posax,posay+int(i*LineNum),text[int((i+BUTTONNUMBER)*Num):int((i+1+BUTTONNUMBER)*Num)], scale = Scale, color = Color, thickness = 1) # canvasName.draw_string(posax,posay,str(text), scale = Scale, color = Color, thickness = 1) ` if (color.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var bool = "False"; // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False"; // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False"; // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n" _code = `textCanvasNewLine(canvas,${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},(${d} ,${e}, ${f}),${LineNum})\n` // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world } else if (color.charAt(0) != '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } _code = `textCanvasNewLine(canvas,${xy},${content},${dispalyStr},${buttonUp},${buttonDown},${scale},${color},${LineNum})\n` // _code = variable_name + '.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world // ''; } return _code; } Blockly.Blocks['ai_lcd_textcarvas'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_text_start_coord); this.appendValueInput("CONTENT") .setCheck("String") .appendField(Blockly.Msg.image_process_text_content); this.appendValueInput("COLOR") .setCheck("String") .appendField(Blockly.Msg.image_process_text_color); this.appendValueInput("Scale") .setCheck("Number") .appendField(Blockly.Msg.image_process_draw_text_font_size); // this.appendDummyInput() // .appendField(Blockly.Msg.image_process_draw_text_if_monospace) // .appendField(new Blockly.FieldCheckbox("FALSE"), "bool"); this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_textcarvas = function (block) { var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` var _code = "" if (color.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var bool = "False"; // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False"; // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False"; var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n" _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world } else if (color.charAt(0) != '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var bool = "False"; // var bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False"; // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False"; var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world ''; } return _code; } Blockly.Blocks['ai_lcd_characterscarvas'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_hanzi_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_characters); this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_text_start_coord); this.appendValueInput("CONTENT") .setCheck("String") .appendField(Blockly.Msg.image_process_text_content); this.appendValueInput("COLOR") .setCheck("String") .appendField(Blockly.Msg.image_process_text_color); this.appendDummyInput() .appendField(Blockly.Msg.image_process_draw_text_font_size + ":") // .setCheck(null) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.SMALL, "1"], [Blockly.Msg.MIDDLE, "2"], [Blockly.Msg.LARGE, "3"] ]), "fonts"); // this.appendDummyInput() // .appendField(Blockly.Msg.Set_Auto_Wrap + ":") // // .setCheck(null) // .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.LED_SCROLL_YES, "True"], // [Blockly.Msg.LED_SCROLL_NO, "False"] // ]), "wraps"); this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_characterscarvas_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_characterscarvas = function (block) { var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); var _code = '' if (color.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False"; var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var size = block.getFieldValue('fonts');; // var wraps = block.getFieldValue('wraps'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"; } else if (color.charAt(0) != '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False"; var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var size = block.getFieldValue('fonts');; // var wraps = block.getFieldValue('wraps'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); _code = "lcd_draw_string(" + variable_name + ", " + xy + ", " + content + ", color=" + color + ", font_size=" + size + ")\n"; } return _code; } Blockly.Blocks['ai_lcd_linecarvas'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_line) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_text_start_coord); this.appendValueInput("POSB") .setCheck("String") .appendField(Blockly.Msg.image_process_text_end_coord); this.appendValueInput("COLOR") .setCheck("String") .appendField(Blockly.Msg.image_process_text_color); this.appendValueInput("Scale") .setCheck("Number") .appendField(Blockly.Msg.image_process_text_thick); this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_linecarvas_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_linecarvas = function (block) { var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` if (color.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC); var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=(" + d + "," + e + "," + f + "), thickness=" + size + ")\n"; } else if (color.charAt(0) != '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC); var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=" + color + ", thickness=" + size + ")\n"; } return _code; } Blockly.Blocks['ai_lcd_draw_rectangle'] = { init: function () { // this.appendDummyInput() // .appendField( // new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15")); this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_text_filled, "fillrect"], [Blockly.Msg.image_process_text_stroked, "rect"] ]), "rect_type") .appendField(Blockly.Msg.image_process_draw_rectangle_text); this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_text_start_coord); this.appendValueInput("POSB") .setCheck("String") .appendField(Blockly.Msg.image_process_text_size); this.appendValueInput("COLOR") .setCheck("String") .appendField(Blockly.Msg.image_process_text_color); // this.appendValueInput("Scale") // .setCheck("Number") // .appendField(Blockly.Msg.image_process_text_thick); this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5bb2d6"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('rect_type'); var TOOLTIPS = { 'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled), 'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_draw_rectangle = function (block) { var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1"; var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` // console.log(xy.split(','),size.split(',')) let a = xy.split(',') let b = size.split(',') // let w = Number(a[0])+Number(b[0]) // let h = Number(a[1])+Number(b[1]) // let wh = `${w},${h}` // let ai_lcd_fill_screen_with_rgb = text.includes('ai_lcd_fill_screen_with_rgb') var _code = '' if (color.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1"; // var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); // var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); // var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC); _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=(${d},${e},${f}), thickness=${type}) ` } else if (color.charAt(0) != '#') { _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=${color}, thickness=${type}) ` } return _code; } Blockly.Blocks['ai_lcd_drawcirclecarvas'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_text_on_draw) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_text_filled, "fillrect"], [Blockly.Msg.image_process_text_stroked, "rect"] ]), "rect_type") .appendField(Blockly.Msg.image_process_draw_circle_text); this.appendValueInput("POSA") .setCheck("String") .appendField(Blockly.Msg.image_process_draw_circle_text_start); this.appendValueInput("Scale") .setCheck("Number") .appendField(Blockly.Msg.image_process_text_radius); this.appendValueInput("COLOR") .setCheck("String") .appendField(Blockly.Msg.image_process_text_color); // this.appendValueInput("Scale_0") // .setCheck("Number") // .appendField(Blockly.Msg.image_process_text_thick); this.setInputsInline(false); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5bb2d6"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('rect_type'); var TOOLTIPS = { 'fillrect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled), 'rect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_lcd_drawcirclecarvas = function (block) { var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC); // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` if (color.charAt(0) == '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1"; var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC); var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + type + ")\n"; } else if (color.charAt(0) != '#') { var d = 0, e = 0, f = 0; try { 7 == color.length && (d = parseInt(color.substring(1, 3), 16), e = parseInt(color.substring(3, 5), 16), f = parseInt(color.substring(5, 7), 16)) } catch (g) { } var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1"; var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC); var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC); var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + type + ")\n"; } return _code; } Blockly.Blocks['ai_lcd_draw_image_on_canvas'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_image.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_on_canvas + Blockly.Msg.image_process_draw_image_title); // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("image_path") .setCheck(null) .appendField(Blockly.Msg.image_process_draw_sensor_image_path); this.appendValueInput("scale_y") .setCheck(null) .appendField(Blockly.Msg.OLCD_COORDINATE); this.appendValueInput("alpha") .setCheck(null) .appendField(Blockly.Msg.image_process_draw_image_alpha); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5bb2d6"); this.setTooltip(Blockly.Msg.ai_lcd_draw_image_on_canvas_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_lcd_draw_image_on_canvas'] = function (block) { var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC); var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC); var alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) try: if ScreenOrientation==True: canvas = image.new(size = (240, 320)) else: canvas = image.new(size = (320, 240)) except: canvas = image.new(size = (320, 240)) ScreenOrientation = False ` // let alpha = Blockly.Python.valueToCode(block, 'alpha', Blockly.Python.ORDER_ATOMIC) // TODO: Assemble Python into code variable. var code = 'canvas.draw_image(' + value_image_path + ',' + value_scale_y + ',alpha=' + alpha + ')\n'; return code; }; Blockly.Blocks['v831_img_save'] = { init: function () { this.appendValueInput("save_path") .setCheck(null) .appendField(Blockly.Msg.image_process_text_let_canvas) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.image_process_img_save) // .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.display_draw_vertical, "0", "img"], // [Blockly.Msg.display_draw_horizontal, "1", "img1"] // ]), "invert"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_img_save_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['v831_img_save'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC); // let invert = block.getFieldValue('invert'); // console.log(document.getElementById("img").value, invert) var code = 'canvas.save("/root/user/img/' + save_path_location.slice(1, -1) + '.jpg")\n'; if (save_path_location[0] != '"') { code = 'canvas.save(' + save_path_location + ')\n'; } return code; }; Blockly.Blocks.v831_img_text = { init: function () { this.appendValueInput("save_path") .setCheck(null) .appendField(Blockly.Msg.read_img_path_to) this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.read_img_path_to); this.setHelpUrl(""); } }; Blockly.Python.v831_img_text = function (block) { var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC); var code = 'image.open(' + save_path_location + ')'; return [code,Blockly.Python.ORDER_NONE]; } Blockly.Blocks['v831_img_open'] = { init: function () { this.appendValueInput("save_path") .setCheck(null) .appendField(Blockly.Msg.read_img_path_to) // .appendField(Blockly.Msg.image_process_img_save); // this.appendDummyInput() // .appendField(Blockly.Msg.image_process_img_save_quality) // .appendField(new Blockly.FieldNumber(90, 0, 100), "compression") // .appendField("%"); // this.setInputsInline(false); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.read_img_path_to); this.setHelpUrl(""); } }; Blockly.Python['v831_img_open'] = function (block) { var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC); var code = 'canvas = image.open(' + save_path_location + ')\n'; return code; }; // 翻转 Blockly.Blocks['v831_lcd_invert'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() .appendField(Blockly.Msg.image_process_pixtovec_text_first) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.display_draw_vertical, "0"], [Blockly.Msg.display_draw_horizontal, "1"] ]), "invert") .appendField(Blockly.Msg.MAIXDUINO_DISPLAY_ORIENTATION_ROTATE); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); // this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['v831_lcd_invert'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); let invert = block.getFieldValue('invert'); // TODO: Assemble Python into code variable. var code = `canvas = canvas.flip(${invert})\n` // TODO: Change ORDER_NONE to the correct strength. return code; }; // 旋转 Blockly.Blocks['v831_lcd_rotating'] = { init: function () { this.appendValueInput('spend') .setCheck(null) .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() .appendField(Blockly.Msg.image_process_pixtovec_text_first) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.x_motor_cw_ai, "0"], [Blockly.Msg.x_motor_acw_ai, "1"] ]), "rotating") .appendField(Blockly.Msg.x_motor_set_motor_turns_ai); this.appendDummyInput().appendField(Blockly.Msg.robot_dog_ag); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['v831_lcd_rotating'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); let rotating = block.getFieldValue('rotating'); let spend = (rotating != 0 ? '+' : '-') + Blockly.Python.valueToCode(block, 'spend', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. // Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg,rotationAngle): // from maix import image // imgRotationAim = image.new(size = (320, 240),color=(0,0,0)) // imageRotationBuffer = inputImg.crop(0, 0, 240, 320) // return imgRotationAim.draw_image(imageRotationBuffer.rotate(rotationAngle, adjust=1),0,0,alpha=1) // ` // console.log(rotating,spend) var code = `canvas = canvas.rotate(${spend}, adjust=1)\n` // variable_name+'.rotate('+ spend +', adjust=1)'; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['ai_lcd_invert_color'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_color_invert) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_lcd_invert_color_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_lcd_invert_color'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable. var code = 'canvas.invert()'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['v831_lcd_resizecanvas'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() .appendField(Blockly.Msg.image_process_resize_to); this.appendValueInput("wh") .setCheck(null); this.setInputsInline(true); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_lcd_resizecanvas_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['v831_lcd_resizecanvas'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. // Blockly.Python.definitions_['lcd_invert_init'] = `CANVASINVERT = image.new(size = (240, 320), color = (0,0,0), mode = 'RGB') // ` // var code = `CANVASINVERT.draw_image(${variable_name}.crop(0, 0, 240, 320).resize(${wh}),0,0,alpha=1)` // variable_name + '.resize(' + wh + ')'; // TODO: Change ORDER_NONE to the correct strength. var code = `canvas = canvas.resize(${wh}, padding = 0)\n` return code; }; Blockly.Blocks['ai_lcd_color_scheme'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.image_process_color_scheme_convert) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_color_scheme_bw, "to_grayscale(1)"], [Blockly.Msg.image_process_color_scheme_rgb, "to_rgb565(1)"] ]), "color_scheme"); this.setOutput(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('color_scheme'); var TOOLTIPS = { 'to_grayscale(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_bw), 'to_rgb565(1)': Blockly.Msg.ai_lcd_color_scheme_TOOLTIP.replace('%1', Blockly.Msg.image_process_color_scheme_rgb) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_lcd_color_scheme'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_vari = block.getFieldValue('color_scheme'); // TODO: Assemble Python into code variable. var code = variable_name + '.' + dropdown_vari; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_lcd_ai_pix'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.image_process_pixtovec_text_first) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_pixtovec_v2p, ".ai_to_pix()"], [Blockly.Msg.image_process_pixtovec_p2v, ".pix_to_ai()"] ]), "ai_pix_type") .appendField(Blockly.Msg.image_process_pixtovec_conversion); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#f0983e"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['ai_lcd_ai_pix'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_vari = block.getFieldValue('ai_pix_type'); // TODO: Assemble Python into code variable. var code = 'a = ' + variable_name + dropdown_vari + '\n'; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['v831_lcd_img_cut'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_text_let_canvas + Blockly.Msg.image_process_text_image_canvas + Blockly.Msg.image_process_imgcut_cutting) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField() // .appendField(); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.image_process_imgcut_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.image_process_imgcut_size); this.setInputsInline(false); this.setNextStatement(true, null); this.setPreviousStatement(true, null) this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_lcd_img_cut_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['v831_lcd_img_cut'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. // TODO: Change ORDER_NONE to the correct strength. var code = `canvas = canvas.crop(${xy},${wh})\n`; return code; }; Blockly.Blocks['ai_vision_get_statistics'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_get_statistics_to_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.image_process_get_statistics_get_analysis); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.image_process_get_statistics_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.image_process_get_statistics_size); this.appendValueInput("bins") .setCheck(null) .appendField(Blockly.Msg.image_process_get_statistics_boxes); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_statistics_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_get_statistics'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); var bins = Blockly.Python.valueToCode(block, 'bins', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = variable_name + '.get_statistics(bins=' + bins + ',roi=(' + xy + ',' + wh + '))'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_histogram'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_histogram_get) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.ai_vision_get_histogram_compute); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_histogram_region); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_get_histogram_region_xy); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_get_histogram_region_wh); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_histogram_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_get_histogram'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = variable_name + '.get_histogram(roi=(' + value_xy + ',' + value_wh + '))'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_histogram_percentile'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_histogram_details_1) .appendField(new Blockly.FieldVariable("hist"), "varitem") .appendField(Blockly.Msg.ai_vision_get_histogram_details_get); this.appendValueInput("perc") .setCheck(null); this.setInputsInline(true); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_histogram_percentile_TOOLTIP); this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3"); } }; Blockly.Python['ai_vision_get_histogram_percentile'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_perc = Blockly.Python.valueToCode(block, 'perc', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = variable_name + '.get_percentile(' + value_perc + ')'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_histogram_percentile_detail'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_1) .appendField(new Blockly.FieldVariable("percentile"), "varitem"); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_histogram_percentile_2) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_get_histogram_percentile_3, "value()"], [Blockly.Msg.ai_vision_get_histogram_percentile_4, "l_value()"], [Blockly.Msg.ai_vision_get_histogram_percentile_5, "a_value()"], [Blockly.Msg.ai_vision_get_histogram_percentile_6, "b_value()"] ]), "option"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('option'); var TOOLTIPS = { 'value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_3), 'l_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_4), 'a_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_5), 'b_value()': Blockly.Msg.ai_vision_get_histogram_percentile_detail_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_get_histogram_percentile_6) }; return TOOLTIPS[mode]; }); this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3"); } }; Blockly.Python['ai_vision_get_histogram_percentile_detail'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_option = block.getFieldValue('option'); var code = variable_name + '.' + dropdown_option; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_lab_rgb_conversion'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_lab_rgb_conversion_exec) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_lab_rgb_conversion_torgb, "lab_to_rgb"], [Blockly.Msg.image_process_lab_rgb_conversion_tolab, "rgb_to_lab"] ]), "rgblab"); this.appendValueInput("color_tuple") .setCheck(null) .appendField(Blockly.Msg.image_process_lab_rgb_conversion_tuple); this.setOutput(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('rgblab'); var TOOLTIPS = { 'lab_to_rgb': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_torgb), 'rgb_to_lab': Blockly.Msg.ai_vision_lab_rgb_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_lab_rgb_conversion_tolab) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_lab_rgb_conversion'] = function (block) { var type = block.getFieldValue('rgblab'); var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = 'image.' + type + '(' + tuple + ')'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_rgb_grayscale_conversion'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_exec) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.image_process_rgb_grayscale_conversion_torgb, "grayscale_to_rgb"], [Blockly.Msg.image_process_rgb_grayscale_conversion_togray, "rgb_to_grayscale"] ]), "rgb_g"); this.appendValueInput("color_tuple") .setCheck(null) .appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_set); this.setOutput(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('rgb_g'); var TOOLTIPS = { 'grayscale_to_rgb': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_torgb), 'rgb_to_grayscale': Blockly.Msg.ai_vision_rgb_grayscale_conversion_TOOLTIP.replace('%1', Blockly.Msg.image_process_rgb_grayscale_conversion_togray) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_rgb_grayscale_conversion'] = function (block) { var type = block.getFieldValue('rgb_g'); var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC); Blockly.Python.addVariable('rgb_tuple', "rgb_tuple = None", true); // TODO: Assemble Python into code variable. var code = 'image.' + type + '(' + tuple + ')'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; /* _ ___ ____ / \ |_ _| / ___|__ _ _ __ ___ ___ _ __ __ _ / _ \ | | | | / _` | '_ ` _ \ / _ \ '__/ _` | / ___ \ | | | |__| (_| | | | | | | __/ | | (_| | /_/ \_\___| \____\__,_|_| |_| |_|\___|_| \__,_| */ Blockly.Blocks.ai_camera_wh = { init: function () { var _input = this.appendDummyInput(); this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL); this.setColour("#60c1bb"); this.setOutput(!0, "Boolean"); _input.appendField(Blockly.Msg.W); this.appendValueInput("A").setCheck("Number"); _input = this.appendDummyInput(); _input.appendField(Blockly.Msg.H) this.appendValueInput("B").setCheck("Number"); this.setInputsInline(!0); } }; Blockly.Python.ai_camera_wh = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC); var code = "" + _x + ", " + _y + ""; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_camera_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/camera_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_camera_init); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_camera_camera_set_size) // .appendField(new Blockly.FieldDropdown([ // ["QVGA (320*240)", "QVGA"], // ["QQVGA (160*120)", "QQVGA"] // ]), "DEGREE"); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_camera_camera_color_mode) // .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.ai_camera_camera_color_mode_rgb, "RGB565"], // [Blockly.Msg.ai_camera_camera_color_mode_bw, "GRAYSCALE"] // ]), "DEGREE1"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_camera_init_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_init = function (block) { Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.addVariable("SETVFLIP", "SETVFLIP = False", true) Blockly.Python.addVariable("SETHMIRROT", "SETHMIRROT = False", true) var _code = ``; return _code; } Blockly.Blocks['ai_camera_windows'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_windowing_resize); this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_windowing_w) .appendField(new Blockly.FieldNumber(240), "window_w") .appendField(Blockly.Msg.ai_camera_windowing_h) .appendField(new Blockly.FieldNumber(320), "window_h") // .appendField(Blockly.Msg.ai_camera_windowing_unit); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_camera_windows_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_camera_windows'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var w = block.getFieldValue('window_w'); var h = block.getFieldValue('window_h'); // var code = 'sensor.set_windowing((' + w + ',' + h + '))\n'; var code = 'camera.camera.config(size=(' + w + ',' + h + '))\n'; return code; }; Blockly.Blocks['ai_camera_fit_to_screen_size'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_camera_fit_set + Blockly.Msg.ai_camera_camera_fit_to) .appendField(new Blockly.FieldDropdown([ ["320*240", "320"], ["224*224", "224"] ]), "size"); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_camera_fit_to_screen_size_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_camera_fit_to_screen_size'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_size = block.getFieldValue('size'); Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['lcd_invert_init'] = `def lcdRotation(inputImg): global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation imageRotationBuffer = inputImg.crop(0, 0, 240, 320) try: if ScreenOrientation: imgRotationAim = image.new(size = (240, 320)) rotationAngle = 180 else: imgRotationAim = image.new(size = (320, 240)) rotationAngle = 90 except: imgRotationAim = image.new(size = (320, 240)) rotationAngle = 90 GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1) GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1) return GETROTATION ` Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg): global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation imageRotationBuffer = inputImg.crop(0, 0, 320, 240) try: if ScreenOrientation: imgRotationAim = image.new(size = (240, 320)) rotationAngle = 90 GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1) else: imgRotationAim = image.new(size = (320, 240)) GETROTATION = imageRotationBuffer except: imgRotationAim = image.new(size = (320, 240)) GETROTATION = imageRotationBuffer GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1) return GETROTATION ` Blockly.Python.definitions_['lcd_invert_rotate_camera'] = `def getLcdRotation(cameraCapture): global cameraSize if cameraSize: return lcdRotationNew(cameraCapture) else: return lcdRotation(cameraCapture) ` // #从摄像头中获取一张图像 var code = `canvas = getLcdRotation(camera.capture())\n`; // TODO: Assemble Python into code variable. if (dropdown_size == "224") { code = `canvas = getLcdRotation(camera.capture()).crop(0,0,224,224)\n` } return code; }; Blockly.Blocks['ai_camera_snapshot'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_snapshot); this.setOutput(false, null); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_camera_snapshot_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_snapshot = function (block) { Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.definitions_['lcd_invert_init_new'] = `def lcdRotationNew(inputImg): global SETVFLIP,SETHMIRROT,cameraSize,ScreenOrientation imageRotationBuffer = inputImg.crop(0, 0, 320, 240) if ScreenOrientation: imgRotationAim = image.new(size = (240, 320)) rotationAngle = 90 GETROTATION = imageRotationBuffer.rotate(+rotationAngle, adjust=1) else: imgRotationAim = image.new(size = (320, 240)) GETROTATION = imageRotationBuffer GETROTATION = imgRotationAim.draw_image(GETROTATION,0,0,alpha=1) return GETROTATION ` Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = False`, true) // #从摄像头中获取一张图像 var _code = `canvas = lcdRotationNew(camera.capture())\n`; return _code; } // 图传 Blockly.Blocks['v831_camera_graph_transmission'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.v831_transmission_setup_show); // this.appendDummyInput() // .appendField(Blockly.Msg.v831_transmission_init_setup_source) // .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.v831_transmission_setup_show); this.setHelpUrl(''); } }; Blockly.Python.v831_camera_graph_transmission = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg` Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_time'] = `import time` // #从摄像头中获取一张图像 var _code = `jpg = utils.rgb2jpg(canvas.convert("RGB").tobytes(), canvas.width, canvas.height) img_base64 = base64.b64encode(jpg) img_base64_str = "data:image/jpg;base64," + str(img_base64)[2:-1] time.sleep(0.1) try: print(img_base64_str) pass except Exception as e: print(str(e)) pass `; return _code } Blockly.Blocks['v831_camera_internet_transmission'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.v831_internet_transmission_setup_show); // this.appendDummyInput() // .appendField(Blockly.Msg.v831_transmission_init_setup_source) // .appendField(new Blockly.FieldVariable("img_graphTransmission"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.v831_transmission_setup_show); this.setHelpUrl(''); } }; Blockly.Python.v831_camera_internet_transmission = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_['v831_import_mjpg'] = `from maix import mjpg` Blockly.Python.definitions_['v831_import_utils'] = `from maix import utils` Blockly.Python.definitions_['v831_import_queue'] = `queue = mjpg.Queue(maxsize=8) mjpg.MjpgServerThread("0.0.0.0", 18811, mjpg.BytesImageHandlerFactory(q=queue)).start()` // #从摄像头中获取一张图像 var _code = `jpg = utils.rgb2jpg(canvas.convert("RGB").tobytes(), 320, 240) queue.put(mjpg.BytesImage(jpg)) `; return _code } Blockly.Blocks['ai_camera_lens_corr'] = { init: function () { this.appendValueInput("lens_corr") .setCheck(null) .appendField(Blockly.Msg.ai_camera_set_lens_corr); this.setInputsInline(true); this.setOutput(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_camera_lens_corr_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_camera_lens_corr'] = function (block) { var value_lens_corr = Blockly.Python.valueToCode(block, 'lens_corr', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = value_lens_corr + '.lens_corr(strength = 1.8, zoom = 1.0)'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_camera_image_property_change'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_bcs_set_text_2) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_bcs_vflip, "set_vflip"], [Blockly.Msg.ai_camera_bcs_hmirror, "set_hmirror"], // [Blockly.Msg.ai_camera_bcs_wb, "set_auto_whitebal"], // [Blockly.Msg.ai_camera_bcs_g, "set_auto_gain"], // [Blockly.Msg.ai_camera_bcs_e, "set_auto_exposure"] ]), "image_property") .appendField(Blockly.Msg.ai_camera_bcs_as_2) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_enable + Blockly.Msg.ai_camera_bcs_status, "True"], [Blockly.Msg.ai_camera_disable + Blockly.Msg.ai_camera_bcs_status, "False"] ]), "DEGREE"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('image_property'); var TOOLTIPS = { 'set_vflip': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_vflip), 'set_hmirror': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_hmirror), 'set_auto_whitebal': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_wb), 'set_auto_gain': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_g), 'set_auto_exposure': Blockly.Msg.ai_camera_image_property_change_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_e) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_image_property_change = function (block) { var degee = block.getFieldValue('DEGREE'); var dropdown_image_property = block.getFieldValue('image_property'); var _code = ``; if (dropdown_image_property == "set_vflip") { _code = `SETVFLIP = ${degee} ` } else if (dropdown_image_property == "set_hmirror") { _code = `SETHMIRROT = ${degee} ` } return _code; } Blockly.Blocks['ai_camera_vflip'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_vflip) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"] ]), "DEGREE") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_vflip = function (block) { var degee = block.getFieldValue('DEGREE'); var _code = "sensor.set_vflip(" + degee + ")\n"; return _code; } Blockly.Blocks['ai_camera_hmirror'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_hmirror) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"] ]), "DEGREE") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_hmirror = function (block) { var degee = block.getFieldValue('DEGREE'); var _code = "sensor.set_hmirror(" + degee + ")\n" return _code; } Blockly.Blocks['ai_camera_auto_whitebal'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_auto_whitebal) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"] ]), "DEGREE") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_auto_whitebal = function (block) { var degee = block.getFieldValue('DEGREE'); var _code = "sensor.set_auto_whitebal(" + degee + ")\n" return _code; } Blockly.Blocks['ai_camera_auto_gain'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_auto_gain) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"] ]), "DEGREE") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_auto_gain = function (block) { var degee = block.getFieldValue('DEGREE'); var _code = "sensor.set_auto_gain(" + degee + ")\n" return _code; } Blockly.Blocks['ai_camera_auto_exposure'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_auto_exposure) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"] ]), "DEGREE") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_auto_exposure = function (block) { var degee = block.getFieldValue('DEGREE'); var _code = "sensor.set_auto_exposure(" + degee + ")\n" return _code; } Blockly.Blocks['ai_camera_bcs_operation'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_bcs_set_text) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_camera_bcs_contrast, "contrast"], [Blockly.Msg.ai_camera_bcs_brightness, "brightness"], [Blockly.Msg.ai_camera_bcs_saturation, "saturation"] ]), "image_property") .appendField(Blockly.Msg.ai_camera_bcs_as); this.appendValueInput("A").setCheck("Number"); this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_range); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setInputsInline(!0); this.setColour("#60c1bb"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('image_property'); var TOOLTIPS = { 'contrast': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_contrast), 'brightness': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_brightness), 'saturation': Blockly.Msg.ai_camera_bcs_operation_TOOLTIP.replace('%1', Blockly.Msg.ai_camera_bcs_saturation) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_bcs_operation = function (block) { var dropdown_image_property = block.getFieldValue('image_property'); var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _code = "sensor.set_" + dropdown_image_property + "(" + _x + ")\n" return _code; } Blockly.Blocks['ai_camera_contrast'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_contrast_to_value); this.appendValueInput("A").setCheck("Number"); this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_range); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setInputsInline(!0); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_contrast = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _code = "sensor.set_contrast(" + _x + ")\n" return _code; } Blockly.Blocks['ai_camera_brightness'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_brightness_to_value); this.appendValueInput("A").setCheck("Number"); this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_range); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setInputsInline(!0); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_brightness = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _code = "sensor.set_brightness(" + _x + ")\n" return _code; } Blockly.Blocks['ai_camera_saturation'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_saturation_value); this.appendValueInput("A").setCheck("Number"); this.appendDummyInput() .appendField(Blockly.Msg.ai_camera_set_range); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setInputsInline(!0); this.setColour("#60c1bb"); this.setTooltip(''); this.setHelpUrl(''); } }; Blockly.Python.ai_camera_saturation = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _code = "sensor.set_saturation(" + _x + ")\n" return _code; } /* _ ___ __ ___ _ / \ |_ _| \ \ / (_)___(_) ___ _ __ / _ \ | | \ \ / /| / __| |/ _ \| '_ \ / ___ \ | | \ V / | \__ \ | (_) | | | | /_/ \_\___| \_/ |_|___/_|\___/|_| |_| */ Blockly.Blocks.ai_lcd_XY_vision = { init: function () { var _input = this.appendDummyInput(); this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL); this.setColour("#f0983e"); this.setOutput(!0, "Boolean"); _input.appendField(Blockly.Msg.X); this.appendValueInput("A").setCheck("Number"); _input = this.appendDummyInput(); _input.appendField(Blockly.Msg.Y) this.appendValueInput("B").setCheck("Number"); this.setInputsInline(!0); } }; Blockly.Python.ai_lcd_XY_vision = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC); var code = "" + _x + ", " + _y + ""; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks.ai_lcd_WH_vision = { init: function () { var _input = this.appendDummyInput(); this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL); this.setColour("#f0983e"); this.setOutput(!0, "Boolean"); _input.appendField(Blockly.Msg.W); this.appendValueInput("A").setCheck("Number"); _input = this.appendDummyInput(); _input.appendField(Blockly.Msg.H) this.appendValueInput("B").setCheck("Number"); this.setInputsInline(!0); } }; Blockly.Python.ai_lcd_WH_vision = function (block) { var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC); var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC); var code = "" + _x + ", " + _y + ""; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_canvas_area_tuple'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_canvas_area_tuple); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_xy); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_canvas_area_tuple_wh); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_canvas_area_tuple_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_canvas_area_tuple'] = function (block) { var value_coordinate = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var value_size = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = value_coordinate + ',' + value_size; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_lane_tracking_run'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_lane_tracking_run) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("rgb_value") .setCheck(null) .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_threshold); this.setHelpUrl(""); } }; Blockly.Python['ai_lane_tracking_run'] = function (block) { var value_color = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC) // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var code = '' + 'line = canvas.find_line()\n' + 'canvas.draw_line(line["rect"][0], line["rect"][1], line["rect"][2],line["rect"][3], color=' + value_color + ', thickness=1)\n' + 'canvas.draw_line(line["rect"][2], line["rect"][3], line["rect"][4],line["rect"][5], color=' + value_color + ', thickness=1)\n' + 'canvas.draw_line(line["rect"][4], line["rect"][5], line["rect"][6],line["rect"][7], color=' + value_color + ', thickness=1)\n' + 'canvas.draw_line(line["rect"][6], line["rect"][7], line["rect"][0],line["rect"][1], color=' + value_color + ', thickness=1)\n' + 'canvas.draw_circle(line["cx"], line["cy"], 4,color=' + value_color + ', thickness=1)\n'; return code; }; Blockly.Blocks['ai_vision_find_lines'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_line.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.ai_vision_find_line); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_line_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_line_size); /*this.appendValueInput("threshold") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_line_hoffman_threshold); this.appendValueInput("theta_margin") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_line_merge_theta); this.appendValueInput("rho_margin") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_line_merge_rho);*/ this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_lines_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_find_lines'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); //var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC); //var theta_margin = Blockly.Python.valueToCode(block, 'theta_margin', Blockly.Python.ORDER_ATOMIC); //var rho_margin = Blockly.Python.valueToCode(block, 'rho_margin', Blockly.Python.ORDER_ATOMIC); var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = variable_name + '.find_lines(roi=(' + xy + ',' + wh + '), threshold = 1000, theta_margin = 25, rho_margin = 25)'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_find_rects'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_rect.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.ai_vision_find_rect); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_rect_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_rect_region_size); /*this.appendValueInput("threshold") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_rect_bounding_threshold);*/ this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_rects_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_find_rects'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = variable_name + '.find_rects(roi=(' + xy + ',' + wh + '), threshold = 10000)'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_find_lines'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_find_blobs_color_region) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("color") .setCheck(null) .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_blobs_size); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_find_lines'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC); var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_[''] = ` def v831_find_blob_fun(lane_trackingimg,region1,COLOR): IMGBLOB = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3]) blobsCANVAS = IMGBLOB.find_blobs(COLOR, merge=True) return blobsCANVAS `; var code = `v831_find_blob_fun(canvas,(${value_xy},${value_wh}),${value_color}) `; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_find_blobs'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_find_lines_color_region) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("color") .setCheck(null) .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_blobs_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_find_blobs_size); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_blobs_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_find_blobs'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC); var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); Blockly.Python.addVariable('lane_trackingline', "lane_trackingline1 = {}", true); Blockly.Python.definitions_['ai_vision_find_blobs_color'] = `_ld_color_detection_threshold = ${value_color} def v831_lane_tracking_setup_one(lane_trackingimg,region1): global lane_trackingline lane_trackingcanvas = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3]) lane_trackingline = lane_trackingcanvas.find_line() lane_trackingcanvas.draw_circle(lane_trackingline["cx"], lane_trackingline["cy"], 2,color=(0,255,0), thickness=1) lane_trackingimg.draw_image(lane_trackingcanvas,region1[0],region1[1]) lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1) lane_trackingline["cx"] = lane_trackingline["cx"] + region1[0] lane_trackingline["cy"] = lane_trackingline["cy"] + region1[1] return lane_trackingline `; var code = `v831_lane_tracking_setup_one(canvas,(${value_xy},${value_wh})) `; return [code, Blockly.Python.ORDER_NONE]; }; // Blockly.Blocks['ai_vision_find_blobs_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.OLCD_LINE_START) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_vision_find_lines_color_region_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_object_model_x_center, "cx"], [Blockly.Msg.ai_models_object_model_y_center, "cy"] ]), "value"); // this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_lines_color_region_result); } }; Blockly.Python['ai_vision_find_blobs_result'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var property = block.getFieldValue('value'); var code = `${variable_name}.get("${property}")`; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_lane_tracking_setup'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/lane_tracking_header.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas + Blockly.Msg.ai_vision_lane_tracking_setup) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("color") .setCheck(null) .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_threshold); this.appendValueInput("lsize") .setCheck(null) .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_l); this.appendValueInput("rsize") .setCheck(null) .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_r); // this.appendValueInput("axis") // .setCheck(null) // .appendField(Blockly.Msg.ai_vision_lane_tracking_setup_axis); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_setup_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_lane_tracking_setup'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC); var value_lsize = Blockly.Python.valueToCode(block, 'lsize', Blockly.Python.ORDER_ATOMIC); var value_rsize = Blockly.Python.valueToCode(block, 'rsize', Blockly.Python.ORDER_ATOMIC); var value_axis = Blockly.Python.valueToCode(block, 'axis', Blockly.Python.ORDER_ATOMIC); console.log(value_lsize[0]) Blockly.Python.addVariable('lane_trackingline1', "lane_trackingline1 = {}", true); Blockly.Python.addVariable('lane_trackingline2', "lane_trackingline2 = {}", true); Blockly.Python.definitions_['ai_lane_tracking_setup'] = `_ld_color_detection_threshold = ${value_color} def v831_lane_tracking_setup(lane_trackingimg,region1,region2): global lane_trackingline1,lane_trackingline2 lane_trackingcanvas1 = lane_trackingimg.crop(region1[0],region1[1],region1[2],region1[3]) lane_trackingcanvas2 = lane_trackingimg.crop(region2[0],region2[1],region2[2],region2[3]) lane_trackingline1 = lane_trackingcanvas1.find_line() lane_trackingline2 = lane_trackingcanvas2.find_line() lane_trackingcanvas1.draw_circle(lane_trackingline1["cx"], lane_trackingline1["cy"], 2,color=(0,255,0), thickness=1) lane_trackingcanvas2.draw_circle(lane_trackingline2["cx"], lane_trackingline2["cy"], 2,color=(0,255,0), thickness=1) lane_trackingimg.draw_image(lane_trackingcanvas1,region1[0],region1[1]) lane_trackingimg.draw_image(lane_trackingcanvas2,region2[0],region2[1]) lane_trackingimg.draw_rectangle(region1[0],region1[1],region1[0]+region1[2],region1[1]+region1[3], color=(255,0,0), thickness=1) lane_trackingimg.draw_rectangle(region2[0],region2[1],region2[0]+region2[2],region2[1]+region2[3], color=(255,0,0), thickness=1) ` let code = `v831_lane_tracking_setup(canvas,${value_lsize},${value_rsize}) ` return code } Blockly.Blocks['ai_lane_tracking_get'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_lane_tracking_run_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_lane_tracking_run_ld, "left_check"], [Blockly.Msg.ai_vision_lane_tracking_run_lv, "left_value"], [Blockly.Msg.ai_vision_lane_tracking_run_rd, "right_check"], [Blockly.Msg.ai_vision_lane_tracking_run_rv, "right_value"] ]), "return"); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_lane_tracking_run_get_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_lane_tracking_get'] = function (block) { var dropdown_return = block.getFieldValue('return'); // TODO: Assemble Python into code variable. var code = '_ld_return["' + dropdown_return + '"]'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_color_analyze'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_analyze_color.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_color_analyze_get_result) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.appendValueInput("xy") .setCheck(null) .appendField(Blockly.Msg.ai_vision_color_analyze_start_coord); this.appendValueInput("wh") .setCheck(null) .appendField(Blockly.Msg.ai_vision_color_analyze_size); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_color_analyze_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_color_analyze'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = 'canvas.get_blob_color((' + xy + ', ' + wh + '), 0, 0)'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_blobs'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_vision_get_blobs_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_detection_box_x, "x"], [Blockly.Msg.ai_vision_detection_box_y, "y"], [Blockly.Msg.ai_models_face_model_ws, "w"], [Blockly.Msg.ai_models_face_model_hs, "h"], // [Blockly.Msg.ai_vision_detection_box_pixels, "pixels()"], [Blockly.Msg.ai_vision_detection_box_cx, "cx"], [Blockly.Msg.ai_vision_detection_box_cy, "cy"] // [Blockly.Msg.ai_vision_detection_box_degree, "rotation()"], // [Blockly.Msg.ai_vision_detection_box_total, "count()"] ]), "blob_type"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_blobs_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_get_blobs'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var type = block.getFieldValue('blob_type'); // TODO: Assemble Python into code variable. var code = `${variable_name}["${type}"]`; if (type == "cx") { code = `int((${variable_name}["w"] + ${variable_name}["x"] + ${variable_name}["x"])/2)` } else if (type == "cy") { code = `int((${variable_name}["h"] + ${variable_name}["y"] + ${variable_name}["y"])/2)` } // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_threshold_default'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_detection_color_threshold_set) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_detection_color_threshold_set_black, "black"], [Blockly.Msg.ai_vision_detection_color_threshold_set_white, "white"], [Blockly.Msg.ai_vision_detection_color_threshold_set_red, "red"], [Blockly.Msg.ai_vision_detection_color_threshold_set_green, "green"], [Blockly.Msg.ai_vision_detection_color_threshold_set_blue, "blue"], [Blockly.Msg.ai_vision_detection_color_threshold_set_orange, "orange"] ]), "color"); this.setOutput(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('color'); var TOOLTIPS = { 'black': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_black), 'white': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_white), 'red': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_red), 'green': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_green), 'blue': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_blue), 'orange': Blockly.Msg.ai_vision_get_threshold_default_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_detection_color_threshold_set_orange) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_get_threshold_default'] = function (block) { var dropdown_color = block.getFieldValue('color'); // TODO: Assemble Python into code variable. if (dropdown_color == "black") { var code = '[(0,40)]'; } else if (dropdown_color == "white") { var code = '[(64,100)]'; } else if (dropdown_color == "red") { var code = '[(45, 65, 40, 80, 40, 60)]'; } else if (dropdown_color == "green") { var code = '[(45, 65, -50, -30, 0, 40)]'; } else if (dropdown_color == "blue") { var code = '[(45, 65, -20, 30, -60, -20)]'; } else if (dropdown_color == "orange") { var code = '[(77, 55, 19, 61, 14, 108)]'; } // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_find_qrcode'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_qrcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField("开始识别二维码") // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.setOutput(false, null); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_find_qrcode'] = function (block) { // TODO: Assemble Python into code variable. var code = 'findQrcode = canvas.find_qrcodes() \n'; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['ai_vision_find_qrcode_result'] = { init: function () { this.appendDummyInput() .appendField("屏幕显示二维码"). appendField(new Blockly.FieldDropdown([ ["源文本", "SourceText"], ["检测框", "CheckBox"], ]), "qrcode_result") // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.setOutput(false, null); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_qrcode_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_find_qrcode_result'] = function (block) { let qrcode_result = block.getFieldValue('qrcode_result'); let qrcodeResultAllBlock = getBlocksByTypeName("ai_vision_find_qrcode_result") // console.log("qrcode_result",qrcodeResultAllBlock[0].innerText) let findQrcodeStr = qrcodeResultAllBlock[0].innerText let Source = findQrcodeStr.indexOf("Source") != -1 ? "True" : "False" let CheckBox = findQrcodeStr.indexOf("CheckBox") != -1 ? "True" : "False" Blockly.Python.addFunction("showQRcodeResult", `def showQRcodeResult(Source,CheckBox): global findQrcode for i in findQrcode: if Source: canvas.draw_string((i["x"]),(i["y"]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1) if CheckBox: canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1) `) // TODO: Assemble Python into code variable. let code = "" if (qrcodeResultAllBlock[0].id == block.id) { code = `showQRcodeResult(${Source},${CheckBox}) ` } // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['ai_vision_qrcode_get_info'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_qrcode_get_result + Blockly.Msg.ai_vision_pattern_detection_content) this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_qrcode_get_result + Blockly.Msg.ai_vision_pattern_detection_content); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_qrcode_get_info'] = function (block) { Blockly.Python.addFunction("getQRcodeResult", `def getQRcodeResult(): global findQrcode qrCodeList = [] for i in findQrcode: qrCodeList.append({i["payload"]}) return qrCodeList `) let code = "getQRcodeResult()" return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_find_apriltag'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_apriltag_.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_apriltag_detected_result) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); // this.setOutput(true, null); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_apriltag_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_find_apriltag'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable. var code = 'findApriltags = canvas.find_apriltags(families = 16,fx = (6/5.76)*320,fy = (6/3.24)*240,cx = 160,cy = 120)'; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['ai_vision_apriltag_get_info'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_apriltag_get_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_pattern_detection_content, "ApriltagId"], // [Blockly.Msg.ai_vision_pattern_detection_type_id, "id"], [Blockly.Msg.ai_vision_pattern_detection_type_family, "ApriltagCheckout"] ]), "get_info"); this.setInputsInline(false); // this.setOutput(true, null); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('get_info'); var TOOLTIPS = { 'payload': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content), 'id': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content), 'family': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_type_family), 'x': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x), 'y': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y), 'w': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w), 'h': Blockly.Msg.ai_vision_apriltag_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_apriltag_get_info'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_name = block.getFieldValue('get_info'); let apriltagAllBlock = getBlocksByTypeName("ai_vision_apriltag_get_info") let findQrcodeStr = apriltagAllBlock[0].innerText let ApriltagId = findQrcodeStr.indexOf("ApriltagId") != -1 ? "True" : "False" let ApriltagCheckout = findQrcodeStr.indexOf("ApriltagCheckout") != -1 ? "True" : "False" Blockly.Python.addFunction("getApriltagCanvasResult", `def getApriltagCanvasResult(ApriltagId,ApriltagCheckout): global findApriltags for i in findApriltags: if apriltagId: canvas.draw_string((i["x"]),(i["y"]), (i["id"]), scale = 1, color = (255,0,0) , thickness = 1) if ApriltagCheckout: canvas.draw_rectangle((i["x"]),(i["y"]), (i["x"])+(i["w"]),(i["y"])+ (i["h"]), color=(255,0,0), thickness=1) )`) // TODO: Assemble Python into code variable. var code = `getApriltagCanvasResult(${ApriltagId},${ApriltagCheckout})`; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['ai_vision_find_datamatrices'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_apriltag_detected_result); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_datamatrices_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_find_datamatrices'] = function (block) { Blockly.Python.addFunction("getApriltagResult", `def getApriltagResult(): global findApriltags if len(findApriltags): return findApriltags[0]["id"] else: return "" )`) var code = `getApriltagResult()`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_datamatrices_get_info'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_vision_data_matrices_get_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_pattern_detection_content, "payload"], [Blockly.Msg.ai_vision_pattern_detection_rows, "rows"], [Blockly.Msg.ai_vision_pattern_detection_cols, "columns"], [Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count, "capacity"], [Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count, "padding"], [Blockly.Msg.ai_vision_pattern_detection_x, "x"], [Blockly.Msg.ai_vision_pattern_detection_y, "y"], [Blockly.Msg.ai_vision_pattern_detection_w, "w"], [Blockly.Msg.ai_vision_pattern_detection_h, "h"] ]), "get_info"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('get_info'); var TOOLTIPS = { 'payload': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content), 'rows': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_rows), 'columns': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_cols), 'capacity': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count), 'padding': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count), 'x': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x), 'y': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y), 'w': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w), 'h': Blockly.Msg.ai_vision_datamatrices_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_datamatrices_get_info'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_name = block.getFieldValue('get_info'); // TODO: Assemble Python into code variable. var code = variable_name + '.' + dropdown_name + '()'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_find_barcodes'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_vision_barcode_.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_get_canvas + Blockly.Msg.ai_vision_barcode_detected_result) // .appendField(new Blockly.FieldVariable("canvas"), "varitem") // .appendField(); this.setNextStatement(true); this.setPreviousStatement(true); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_find_barcodes_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_find_barcodes'] = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable. var code = 'findBarcodes = canvas.find_barcodes() \n'; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['ai_vision_barcodes_get_info'] = { init: function () { this.appendDummyInput() .appendField("屏幕显示条形码") .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_pattern_detection_content, "barcodesPayload"], [Blockly.Msg.ai_models_face_model_rect, "barcodesCorners"] ]), "get_info"); this.setInputsInline(false); this.setOutput(false, null); this.setNextStatement(true); this.setPreviousStatement(true); this.setColour("#f0983e"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('get_info'); var TOOLTIPS = { 'payload': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_content), 'corners': Blockly.Msg.ai_models_face_model_rect.replace('%1', Blockly.Msg.ai_models_face_model_rect), 'x': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_x), 'y': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_y), 'w': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_w), 'h': Blockly.Msg.ai_vision_barcodes_get_info_TOOLTIP.replace('%1', Blockly.Msg.ai_vision_pattern_detection_h) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_vision_barcodes_get_info'] = function (block) { var dropdown_name = block.getFieldValue('get_info'); let qrcodeResultAllBlock = getBlocksByTypeName("ai_vision_barcodes_get_info") // console.log("qrcode_result",qrcodeResultAllBlock[0].innerText) let findQrcodeStr = qrcodeResultAllBlock[0].innerText let barcodesPayload = findQrcodeStr.indexOf("barcodesPayload") != -1 ? "True" : "False" let barcodesCorners = findQrcodeStr.indexOf("barcodesCorners") != -1 ? "True" : "False" Blockly.Python.addFunction("showBarcodesResult", `def showBarcodesResult(type1,type2): global findBarcodes for i in findBarcodes: if type1: canvas.draw_string((i["corners"][0][0]),(i["corners"][0][1]), (i["payload"]), scale = 1, color = (255,0,0) , thickness = 1) if type2: x1,y1 = i['corners'][0] #访问字典的列表 x2,y2 = i['corners'][1] x3,y3 = i['corners'][2] x4,y4 = i['corners'][3] canvas.draw_line(x1, y1, x2, y2, color = (0, 255, 0), thickness = 3) canvas.draw_line(x2, y2, x3, y3, color = (0, 255, 0), thickness = 3) canvas.draw_line(x3, y3, x4, y4, color = (0, 255, 0), thickness = 3) canvas.draw_line(x4, y4, x1, y1, color = (0, 255, 0), thickness = 3) `) // TODO: Assemble Python into code variable. let code = "" if (qrcodeResultAllBlock[0].id == block.id) { code = `showBarcodesResult(${barcodesPayload},${barcodesCorners}) ` } return code }; Blockly.Blocks['ai_vision_barcodes_get_info_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.uav_bar_code) this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.uav_bar_code); } }; Blockly.Python['ai_vision_barcodes_get_info_result'] = function (block) { Blockly.Python.addFunction("getBarcodesResult", `def getBarcodesResult(): global findBarcodes if len(findBarcodes)>0: return findBarcodes[0]["payload"] else: return "" `) var code = `getBarcodesResult()`; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_circles'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_vision_find_circle_detected_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_find_circle_detected_x, "x()"], [Blockly.Msg.ai_vision_find_circle_detected_y, "y()"], [Blockly.Msg.ai_vision_find_circle_detected_radius, "r()"] ]), "blob_type"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_circles_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_get_circles'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var type = block.getFieldValue('blob_type'); var code = variable_name + '.' + type; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_rects'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_vision_find_rect_detected_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_find_rect_detected_x, "x()"], [Blockly.Msg.ai_vision_find_rect_detected_y, "y()"], [Blockly.Msg.ai_vision_find_rect_detected_w, "w()"], [Blockly.Msg.ai_vision_find_rect_detected_h, "h()"], [Blockly.Msg.ai_vision_find_rect_detected_tuple, "rect()"], [Blockly.Msg.ai_vision_find_rect_detected_corners, "corners()"] ]), "blob_type"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_rects_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_get_rects'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var type = block.getFieldValue('blob_type'); // TODO: Assemble Python into code variable. var code = variable_name + '.' + type; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_vision_get_lines'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_vision_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_vision_find_line_detected_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_vision_find_line_detected_start_x, "x1()"], [Blockly.Msg.ai_vision_find_line_detected_start_y, "y1()"], [Blockly.Msg.ai_vision_find_line_detected_end_x, "x2()"], [Blockly.Msg.ai_vision_find_line_detected_end_y, "y2()"], [Blockly.Msg.ai_vision_find_line_detected_length, "length()"], [Blockly.Msg.ai_vision_find_line_detected_angle, "theta()"] ]), "blob_type"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#f0983e"); this.setTooltip(Blockly.Msg.ai_vision_get_lines_TOOLTIP); this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles"); } }; Blockly.Python['ai_vision_get_lines'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var type = block.getFieldValue('blob_type'); // TODO: Assemble Python into code variable. var code = variable_name + '.' + type; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; /* _ ___ __ __ _ _ / \ |_ _| | \/ (_) ___ _ __ ___ _ __ | |__ ___ _ __ ___ / _ \ | | | |\/| | |/ __| '__/ _ \| '_ \| '_ \ / _ \| '_ \ / _ \ / ___ \ | | | | | | | (__| | | (_) | |_) | | | | (_) | | | | __/ /_/ \_\___| |_| |_|_|\___|_| \___/| .__/|_| |_|\___/|_| |_|\___| |_| */ Blockly.Blocks['ai_mphone_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_microphone_init); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_mphone_init_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_mphone_init = function (block) { Blockly.Python.definitions_.import_all_mphone = "" + "from Maix import GPIO, I2S, FFT\n" + "from board import board_info\n" + "from fpioa_manager import fm\n" + "\n" + "sample_rate = 38640\n" + "sample_points = 1024\n" + "fft_points = 512\n" + "hist_x_num = 50\n" + "\n" + "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" + "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" + "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" + "\n" + "_recorder_rx = I2S(I2S.DEVICE_0)\n" + "_recorder_rx.channel_config(_recorder_rx.CHANNEL_0, _recorder_rx.RECEIVER, align_mode = I2S.STANDARD_MODE)\n" + "_recorder_rx.set_sample_rate(sample_rate)\n" + "def _microphone_read_average(lst): \n" + " return int((sum(lst)/len(lst))*100)\n" + ""; // Blockly.Python.addVariable('sample_rate', "sample_rate = 38640", true); // Blockly.Python.addVariable('sample_points', "sample_points = 1024", true); // Blockly.Python.addVariable('fft_points', "fft_points = 512", true); // Blockly.Python.addVariable('hist_x_num', "hist_x_num = 50", true); // Blockly.Python.addVariable('_recorder_rx', "_recorder_rx = None", true); // Blockly.Python.addVariable('fft_res', "fft_res = None", true); // Blockly.Python.addVariable('fft_amp', "fft_amp = None", true); Blockly.Python.addVariable('read_all_channel', "read_all_channel = [0, 0, 0, 0, 0, 0, 0, 0]", true); // Blockly.Python.addVariable('_recorder_rx', "", true); var _code = "" + ""; return _code; } Blockly.Blocks['mphone_audio_spectrum_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/ai_audio_spectrum.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_microphone_start_spectrum_analyze); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.mphone_audio_spectrum_init_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['mphone_audio_spectrum_init'] = function (block) { // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` var code = "" + "time.sleep_ms(10)\n" + "_audio = _recorder_rx.record(sample_points)\n" + "fft_res = FFT.run(_audio.to_bytes(),fft_points)\n" + "fft_amp = FFT.amplitude(fft_res)\n\n" + "read_all_channel[0] = int(_microphone_read_average(fft_amp[0:63]))\n" + "read_all_channel[1] = int(_microphone_read_average(fft_amp[64:127]))\n" + "read_all_channel[2] = int(_microphone_read_average(fft_amp[127:191]))\n" + "read_all_channel[3] = int(_microphone_read_average(fft_amp[192:255]))\n" + "read_all_channel[4] = int(_microphone_read_average(fft_amp[256:319]))\n" + "read_all_channel[5] = int(_microphone_read_average(fft_amp[320:383]))\n" + "read_all_channel[6] = int(_microphone_read_average(fft_amp[384:447]))\n" + "read_all_channel[7] = int(_microphone_read_average(fft_amp[448:514]))\n" + ""; return code; }; Blockly.Blocks['ai_mphone_read_sound_sensitivity'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_microphone_get_spectrum_analyze_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_1, "0"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_2, "1"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_3, "2"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_4, "3"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_5, "4"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_6, "5"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_7, "6"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_8, "7"] ]), "level"); this.setOutput(true, null); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_mphone_read_sound_sensitivity_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_mphone_read_sound_sensitivity'] = function (block) { var dropdown_level = block.getFieldValue('level'); // TODO: Assemble Python into code variable. var code = 'read_all_channel[' + dropdown_level + ']'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_mphone_Record_audio_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_mphone_Record_audio_init); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_init_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_mphone_Record_audio_init = function (block) { Blockly.Python.definitions_.import_ai_mphone_Record_audio_init = "" + "from Maix import GPIO, I2S\n" + "from fpioa_manager import fm\n" + 'import audio\n' + "\n" + '# user setting\n' + "sample_rate = 16000\n" + "# default seting\n" + "sample_points = 2048\n" + "wav_ch = 2\n" + "\n" + 'fm.register(8, fm.fpioa.GPIO0, force=True)\n' + 'wifi_en = GPIO(GPIO.GPIO0, GPIO.OUT)\n' + 'wifi_en.value(0)\n' + "\n" + "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" + "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" + "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" + "\n" + "rx = I2S(I2S.DEVICE_0)\n" + "rx.channel_config(rx.CHANNEL_0, rx.RECEIVER, align_mode=I2S.STANDARD_MODE)\n" + "rx.set_sample_rate(sample_rate)\n" + "print(rx)\n" + ""; var _code = "" + ""; return _code; } Blockly.Blocks['ai_mphone_record_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_microphone_init); this.setPreviousStatement(true); this.setNextStatement(true, null); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_microphone_init); this.setHelpUrl(""); } } Blockly.Python['ai_mphone_record_init'] = function (block) { Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_os'] = `import os` let code = '' return code; } Blockly.Blocks['ai_mphone_record_setting'] = { init: function () { this.appendValueInput("record_time").setCheck(null) .appendField(Blockly.Msg.ai_mphone_Record_audio_start_time) this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.ai_mphone_Record_audio_start_path); this.appendDummyInput() .appendField(Blockly.Msg.ai_mphone_Record_audio_start); this.setPreviousStatement(true); this.setNextStatement(true, null); this.setInputsInline(false); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start); this.setHelpUrl(""); } } Blockly.Python['ai_mphone_record_setting'] = function (block) { var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var record_time = Blockly.Python.valueToCode(block, 'record_time', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_os'] = `import os` let code = `if(os.path.exists(${value_path})): os.system("rm ${value_path.slice(1, value_path.length - 1)}") CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 RECORD_SECONDS = ${Number(record_time) + 1} WAVE_OUTPUT_FILENAME = ${value_path} p = pyaudio.PyAudio() stream = p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK) print("* recording") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK,exception_on_overflow = False) frames.append(data) print("* done recording") stream.stop_stream() stream.close() p.terminate() wf = wave.open(WAVE_OUTPUT_FILENAME, "wb") wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b"".join(frames)) wf.close() ` return code; } Blockly.Blocks['ai_mphone_Record_audio_start'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_mphone_Record_audio_start); this.setPreviousStatement(true); this.setNextStatement(true, null); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_mphone_Record_audio_start_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_mphone_Record_audio_start'] = function (block) { var code = ` print("* recording") frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK,exception_on_overflow = False) frames.append(data) print("* done recording") stream.stop_stream() stream.close() p.terminate() wf = wave.open(WAVE_OUTPUT_FILENAME, "wb") wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b"".join(frames)) wf.close() `; return code; }; Blockly.Blocks['ai_audio_start_recording'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_play_music_file); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5fcd8e"); this.setTooltip(Blockly.Msg.ai_audio_stop_recording_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_start_recording'] = function (block) { // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` var code = ` CHUNK = 1024 wf = wave.open(r"test.wav", "rb")#(sys.argv[1], "rb" p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(CHUNK) while len(data) > 0: stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate() `; return code; }; /* _ ___ _ _ _ / \ |_ _| / \ _ _ __| (_) ___ / _ \ | | / _ \| | | |/ _` | |/ _ \ / ___ \ | | / ___ \ |_| | (_| | | (_) | /_/ \_\___| /_/ \_\__,_|\__,_|_|\___/ */ Blockly.Blocks['ai_audio_play_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.AUDIO_S); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#603ea0"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_init'] = function (block) { Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.addVariable("VOICESTATE", "VOICESTATE = 0", true) Blockly.Python.addVariable("VOICEDATA", "", true) Blockly.Python.addVariable("VOICESTREAM", 'VOICESTREAM = ""', true) Blockly.Python.addVariable("VOICEPYAUDIO", "VOICEPYAUDIO = pyaudio.PyAudio()", true) Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true) Blockly.Python.addVariable("VOICEPPATH", "", true) Blockly.Python.addVariable("VOICEPLAYSTATE", 'VOICEPLAYSTATE = True', true) Blockly.Python.addVariable("VOICEWF", 'VOICEWF = ""', true) var _code = ``; return _code; }; Blockly.Blocks['ai_audio_play_volume'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol) .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol") .appendField("(0~100)"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#603ea0"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_volume'] = function (block) { var number_play_vol = block.getFieldValue('play_vol'); Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value): valueScaled = float(value - 0) / float(100) return int(valueScaled * 31) ` var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol})) time.sleep(0.01) SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+"" `; return _code; }; Blockly.Blocks['ai_audio_play_song'] = { init: function () { this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path) this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol) .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol") .appendField("(0~100)"); this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_start_play); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#603ea0"); this.setTooltip(Blockly.Msg.ai_audio_start_play); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_song'] = function (block) { var path_to_video = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var number_play_vol = block.getFieldValue('play_vol'); Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.addVariable("CHUNK", "CHUNK = 1024", true) Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value): valueScaled = float(value - 0) / float(100) return int(valueScaled * 31) VOICENUMP = str(voice_numberMap(${number_play_vol})) time.sleep(0.01) SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+"" os.system(SYSTEMVOICE) ` // Blockly.Python.addVariable("VOICEPPATH","",false) var _code = ` wf = wave.open(${path_to_video}, "rb")#(sys.argv[1], "rb" p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True) data = wf.readframes(CHUNK) while len(data) > 0: stream.write(data) data = wf.readframes(CHUNK) stream.stop_stream() stream.close() p.terminate() `; return _code; }; Blockly.Blocks['ai_audio_play_start'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_start_play); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#603ea0"); this.setTooltip(Blockly.Msg.ai_audio_start_play); this.setHelpUrl(""); } } Blockly.Python['ai_audio_play_start'] = function (block) { Blockly.Python.definitions_["VoicePlayState"] = `def VoicePlayState(): global VOICESTATE,VOICEDATA,CHUNK,VOICESTREAM,VOICEPYAUDIO,VOICEWF,VOICEPPATH if VOICESTATE == 0: VOICEWF = wave.open(VOICEPPATH, "rb")#(sys.argv[1], "rb" VOICEPYAUDIO = pyaudio.PyAudio() VOICESTREAM = VOICEPYAUDIO.open(format=VOICEPYAUDIO.get_format_from_width(VOICEWF.getsampwidth()),channels=VOICEWF.getnchannels(),rate=VOICEWF.getframerate(),output=True) VOICEDATA = VOICEWF.readframes(CHUNK) VOICESTATE = 1 return True else: if len(VOICEDATA) > 0: try: VOICESTREAM.write(VOICEDATA) VOICEDATA = VOICEWF.readframes(CHUNK) return True except: VOICESTATE = 0 else: VOICESTREAM.stop_stream() VOICESTREAM.close() VOICEPYAUDIO.terminate() VOICESTATE = 0 return False ` let code = `VOICEPLAYSTATE = VoicePlayState() ` return code; } Blockly.Blocks['ai_audio_play_finish'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_end_play); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#603ea0"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_finish'] = function (block) { // TODO: Assemble Python into code variable. var code = `try: VOICESTREAM.stop_stream() VOICESTREAM.close() VOICEPYAUDIO.terminate() VOICESTATE = 0 except: pass `; return code; }; Blockly.Blocks['ai_audio_get_play_status'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_get_play_status); this.setOutput(true, null); this.setColour("#603ea0"); this.setTooltip(Blockly.Msg.ai_audio_play_state_speaker_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_get_play_status'] = function (block) { // TODO: Assemble Python into code variable. var code = 'VOICEPLAYSTATE'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; // 在线语音识别 Blockly.Blocks['ai_online_voice_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_voice_init); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_voice_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_voice_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_websocket'] = `import websocket` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_ssl'] = `import ssl` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread` Blockly.Python.definitions_.ai_online_voice_init = ` STATUS_FIRST_FRAME = 0 # 第一帧的标识 STATUS_CONTINUE_FRAME = 1 # 中间帧标识 STATUS_LAST_FRAME = 2 # 最后一帧的标识 class Ws_Param_voice(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): self.APPID_voice = APPID self.APIKey_voice = APIKey self.APISecret_voice = APISecret self.AudioFile_voice = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID_voice} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000} # 生成url def create_url_voice(self): url = "wss://ws-api.xfyun.cn/v2/iat" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n" signature_origin += "date: " + date + "\\n" signature_origin += "GET " + "/v2/iat " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" } # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url # 收到websocket消息的处理 def on_message_voice(ws, message): global asr_result,txt_result try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: data = json.loads(message)["data"]["result"]["ws"] # print(json.loads(message)) result = "" for i in data: for w in i["cw"]: result += w["w"] print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False))) print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False))) asr_result.append(eval(json.dumps(data, ensure_ascii=False))) txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1])) except Exception as e: print("receive msg,but parse exception:", e) # 收到websocket错误的处理 def on_error_voice(ws, error): print("### error:", error) # 收到websocket关闭的处理 def on_close_voice(ws): print("### closed ###") # 收到websocket连接建立的处理 def on_open_voice(ws): def run_voice(*args): global wsParam_voice frameSize = 8000 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(wsParam_voice.AudioFile_voice, "rb") as fp: while True: buf = fp.read(frameSize) # 文件结束 if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business 参数 # appid 必须带上,只需第一帧发送 if status == STATUS_FIRST_FRAME: d = {"common": wsParam_voice.CommonArgs, "business": wsParam_voice.BusinessArgs, "data": {"status": 0, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw"}} d = json.dumps(d) ws.send(d) status = STATUS_CONTINUE_FRAME # 中间帧处理 elif status == STATUS_CONTINUE_FRAME: d = {"data": {"status": 1, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw"}} ws.send(json.dumps(d)) # 最后一帧处理 elif status == STATUS_LAST_FRAME: d = {"data": {"status": 2, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw"}} ws.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run_voice, ()) asr_result=[] txt_result=[] APPId_voice = ${APPId} APISecret_voice = ${APISecret} APIKey_voice = ${APIKey} ` var code = ''; return code; }; // 在线语音识别加载 Blockly.Blocks['ai_online_voice_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_voice_loading); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_voice_init_path); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_voice_loading); this.setHelpUrl(""); } }; Blockly.Python['ai_online_voice_loading'] = function (block) { var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_websocket'] = `import websocket` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_ssl'] = `import ssl` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread` Blockly.Python.definitions_.ai_online_voice_init = ` STATUS_FIRST_FRAME = 0 # 第一帧的标识 STATUS_CONTINUE_FRAME = 1 # 中间帧标识 STATUS_LAST_FRAME = 2 # 最后一帧的标识 class Ws_Param_voice(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): self.APPID_voice = APPID self.APIKey_voice = APIKey self.APISecret_voice = APISecret self.AudioFile_voice = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID_voice} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo":1,"vad_eos":10000} # 生成url def create_url_voice(self): url = "wss://ws-api.xfyun.cn/v2/iat" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n" signature_origin += "date: " + date + "\\n" signature_origin += "GET " + "/v2/iat " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret_voice .encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey_voice , "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" } # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url # 收到websocket消息的处理 def on_message_voice(ws, message): global asr_result,txt_result try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: data = json.loads(message)["data"]["result"]["ws"] # print(json.loads(message)) result = "" for i in data: for w in i["cw"]: result += w["w"] print("sid:%s call success!,data is:%s" % (sid, json.dumps(data, ensure_ascii=False))) print("json.dumps(data, ensure_ascii=False)",eval(json.dumps(data, ensure_ascii=False))) asr_result.append(eval(json.dumps(data, ensure_ascii=False))) txt_result.append(eval(json.dumps(data, ensure_ascii=False)[1])) except Exception as e: print("receive msg,but parse exception:", e) # 收到websocket错误的处理 def on_error_voice(ws, error): print("### error:", error) # 收到websocket关闭的处理 def on_close_voice(ws): print("### closed ###") # 收到websocket连接建立的处理 def on_open_voice(ws): def run_voice(*args): global wsParam_voice frameSize = 8000 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(wsParam_voice.AudioFile_voice, "rb") as fp: while True: buf = fp.read(frameSize) # 文件结束 if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business 参数 # appid 必须带上,只需第一帧发送 if status == STATUS_FIRST_FRAME: d = {"common": wsParam_voice.CommonArgs, "business": wsParam_voice.BusinessArgs, "data": {"status": 0, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw"}} d = json.dumps(d) ws.send(d) status = STATUS_CONTINUE_FRAME # 中间帧处理 elif status == STATUS_CONTINUE_FRAME: d = {"data": {"status": 1, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw"}} ws.send(json.dumps(d)) # 最后一帧处理 elif status == STATUS_LAST_FRAME: d = {"data": {"status": 2, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), "utf-8"), "encoding": "raw"}} ws.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run_voice, ()) asr_result=[] txt_result=[] APPId_voice = ${APPId} APISecret_voice = ${APISecret} APIKey_voice = ${APIKey} ` Blockly.Python.definitions_['get_online_voice_data'] = `asr_string="" def getVoiceData(): global wsParam_voice,asr_string,txt_result,asr_result # 测试时候在此处正确填写相关信息即可运行 asr_string = "" txt_result = [] asr_result = [] time1 = datetime.now() wsParam_voice = Ws_Param_voice(APPID=APPId_voice, APISecret=APISecret_voice, APIKey=APIKey_voice, AudioFile=${AudioFile}) websocket.enableTrace(False) wsUrl = wsParam_voice.create_url_voice() ws = websocket.WebSocketApp(wsUrl, on_message=on_message_voice, on_error=on_error_voice) ws.on_open = on_open_voice ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) time2 = datetime.now() for i in range(len(asr_result)): for j in range(len(asr_result[i])): txt_result.append(asr_result[i][j]["cw"][0]["w"]) print("txt_result:", txt_result) for i in range(len(txt_result)): asr_string=asr_string+txt_result[i] print("asr_string:", asr_string) return asr_string ` let code = `VoiceResult = getVoiceData() `; return code; }; Blockly.Blocks['ai_online_voice_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_voice_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_voice_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_voice_result'] = function (block) { let code = `VoiceResult`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 在线人脸识别 Blockly.Blocks['ai_online_ident_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_face_init); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_face_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_ident_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_traceback'] = `import traceback` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_.ai_online_ident_init = ` class AssembleHeaderException(Exception): def __init__(self, msg): self.message = msg class Url: def __init__(this, host, path, schema): this.host = host this.path = path this.schema = schema pass # 进行sha256加密和base64编码 def sha256base64(data): sha256 = hashlib.sha256() sha256.update(data) digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8") return digest def parse_url_face(requset_url): stidx = requset_url.index("://") host = requset_url[stidx + 3:] schema = requset_url[:stidx + 3] edidx = host.index("/") if edidx <= 0: raise AssembleHeaderException("invalid request url:" + requset_url) path = host[edidx:] host = host[:edidx] u = Url(host, path, schema) return u def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""): u = parse_url_face(requset_url) host = u.host path = u.path now = datetime.now() date = format_date_time(mktime(now.timetuple())) print(date) # date = "Thu, 12 Dec 2019 01:57:27 GMT" signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path) print(signature_origin) signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % ( api_key, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") print(authorization_origin) values = { "host": host, "date": date, "authorization": authorization } return requset_url + "?" + urlencode(values) def gen_body_face(appid, img_path, server_id): with open(img_path, "rb") as f: img_data = f.read() body = { "header": { "app_id": appid, "status": 3 }, "parameter": { server_id: { "service_kind": "face_detect", #"detect_points": "1", #检测特征点 #"detect_property": "1", #检测人脸属性 "face_detect_result": { "encoding": "utf8", "compress": "raw", "format": "json" } } }, "payload": { "input1": { "encoding": "jpg", "status": 3, "image": str(base64.b64encode(img_data), "utf-8") } } } return json.dumps(body) APPId_face = ${APPId} APISecret_face = ${APISecret} APIKey_face = ${APIKey} `; let code = '' return code; }; // 在线人脸识别加载 Blockly.Blocks['ai_online_ident_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_face_loading); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.online_face_init_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_face_loading); this.setHelpUrl(""); } }; Blockly.Python['ai_online_ident_loading'] = function (block) { var path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_traceback'] = `import traceback` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_.ai_online_ident_init = ` class AssembleHeaderException(Exception): def __init__(self, msg): self.message = msg class Url: def __init__(this, host, path, schema): this.host = host this.path = path this.schema = schema pass # 进行sha256加密和base64编码 def sha256base64(data): sha256 = hashlib.sha256() sha256.update(data) digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8") return digest def parse_url_face(requset_url): stidx = requset_url.index("://") host = requset_url[stidx + 3:] schema = requset_url[:stidx + 3] edidx = host.index("/") if edidx <= 0: raise AssembleHeaderException("invalid request url:" + requset_url) path = host[edidx:] host = host[:edidx] u = Url(host, path, schema) return u def assemble_ws_auth_url_face(requset_url, method="GET", api_key="", api_secret=""): u = parse_url_face(requset_url) host = u.host path = u.path now = datetime.now() date = format_date_time(mktime(now.timetuple())) print(date) # date = "Thu, 12 Dec 2019 01:57:27 GMT" signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path) print(signature_origin) signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % ( api_key, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") print(authorization_origin) values = { "host": host, "date": date, "authorization": authorization } return requset_url + "?" + urlencode(values) def gen_body_face(appid, img_path, server_id): with open(img_path, "rb") as f: img_data = f.read() body = { "header": { "app_id": appid, "status": 3 }, "parameter": { server_id: { "service_kind": "face_detect", #"detect_points": "1", #检测特征点 #"detect_property": "1", #检测人脸属性 "face_detect_result": { "encoding": "utf8", "compress": "raw", "format": "json" } } }, "payload": { "input1": { "encoding": "jpg", "status": 3, "image": str(base64.b64encode(img_data), "utf-8") } } } return json.dumps(body) APPId_face = ${APPId} APISecret_face = ${APISecret} APIKey_face = ${APIKey} `; Blockly.Python.definitions_.online_ident = ` ONLINE_IDENT_DATA = "" def run_face(appid, apikey, apisecret, img_path, server_id="s67c9c78c"): url = "http://api.xf-yun.com/v1/private/{}".format(server_id) request_url = assemble_ws_auth_url_face(url, "POST", apikey, apisecret) headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid} print(request_url) response = requests.post(request_url, data=gen_body_face(appid, img_path, server_id), headers=headers) resp_data = json.loads(response.content.decode("utf-8")) print(resp_data) picRes=base64.b64decode(resp_data["payload"]["face_detect_result"]["text"]).decode() print(picRes) with open("/root/pic0.txt","w") as f: f.write(picRes) return eval(picRes) ` let code = ` if __name__ == "__main__": img_path_face = ${path} ONLINE_IDENT_DATA = run_face(appid=APPId_face,apisecret=APISecret_face,apikey=APIKey_face,img_path=img_path_face,) `; return code; }; // 在线人脸识别结果 Blockly.Blocks['ai_online_ident_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_face_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_face_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_ident_result'] = function (block) { let code = `ONLINE_IDENT_DATA["face_num"]`; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_online_ident_result_people'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.serialcomm_write_item_first) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.face_information) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_object_model_x, "x"], [Blockly.Msg.ai_models_object_model_y, "y"], [Blockly.Msg.ai_models_object_model_w, "w"], [Blockly.Msg.ai_models_object_model_h, "h"], // ['人脸属性信息', "property"], [Blockly.Msg.ai_models_object_model_confidence, "score"] ]), "TYPE"); this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(''); this.setHelpUrl(""); } } Blockly.Python['ai_online_ident_result_people'] = function (block) { var type = block.getFieldValue('TYPE'); var i = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); let code = ''; if (type == "w") { code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('x')` } else if (type == "h") { code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}') + ONLINE_IDENT_DATA.get('face_'+str(${i})).get('y')` } else { code = `ONLINE_IDENT_DATA.get('face_'+str(${i})).get('${type}')` } return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_audio_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.Text_to_speech_initialization); // this.appendValueInput("A") .setCheck(null) .appendField('APP ID'); this.appendValueInput("B") .setCheck(null) .appendField('API Secret'); this.appendValueInput("C") .setCheck(null) .appendField('API Key'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.Text_to_speech_initialization); this.setHelpUrl(""); } }; // 在线文本转语音初始化 Blockly.Python.ai_audio_init = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime` Blockly.Python.definitions_['v831_import_websocket'] = `import websocket` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_ssl'] = `import ssl` Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread` Blockly.Python.definitions_.ai_audio_init_function = ` STATUS_FIRST_FRAME = 0 # 第一帧的标识 STATUS_CONTINUE_FRAME = 1 # 中间帧标识 STATUS_LAST_FRAME = 2 # 最后一帧的标识 class Ws_Param_Audio(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, Text): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.Text = Text # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"} self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")} #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"” #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")} # 生成url def create_url(self): url = "wss://tts-api.xfyun.cn/v2/tts" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n" signature_origin += "date: " + date + "\\n" signature_origin += "GET " + "/v2/tts " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" } # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url APPId_Audio = ${APPId} APISecret_Audio = ${APISecret} APIKey_Audio = ${APIKey} `; var _code = ""; return _code; } Blockly.Blocks['ai_audio_play_state'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.text_conversion_voice); // this.appendValueInput("A") .setCheck(null) .appendField('APP ID'); this.appendValueInput("B") .setCheck(null) .appendField('API Secret'); this.appendValueInput("C") .setCheck(null) .appendField('API Key'); this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.Content_of_text); // this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.Voice_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.text_conversion_voice); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_state'] = function (block) { // TODO: Assemble Python into code variable. let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC) let url = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) let path = `${url.slice(1, url.length - 1)}` var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_wave'] = `import wave` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` // Blockly.Python.definitions_['v831_import_datetime'] = `import datetime` Blockly.Python.definitions_['v831_import_websocket'] = `import websocket` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_ssl'] = `import ssl` Blockly.Python.definitions_['v831_import_thread_as_thread'] = `import _thread as thread` Blockly.Python.definitions_.ai_audio_init_function = ` STATUS_FIRST_FRAME = 0 # 第一帧的标识 STATUS_CONTINUE_FRAME = 1 # 中间帧标识 STATUS_LAST_FRAME = 2 # 最后一帧的标识 class Ws_Param_Audio(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, Text): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.Text = Text # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"} self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode("utf-8")), "UTF8")} #使用小语种须使用以下方式,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"” #self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")} # 生成url def create_url(self): url = "wss://tts-api.xfyun.cn/v2/tts" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\\n" signature_origin += "date: " + date + "\\n" signature_origin += "GET " + "/v2/tts " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret.encode("utf-8"), signature_origin.encode("utf-8"),digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % (self.APIKey, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" } # 拼接鉴权参数,生成url url = url + "?" + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url APPId_Audio = ${APPId} APISecret_Audio = ${APISecret} APIKey_Audio = ${APIKey} `; Blockly.Python.definitions_.on_message = ` def on_message(ws, message): try: message =json.loads(message) code = message["code"] sid = message["sid"] audio = message["data"]["audio"] audio = base64.b64decode(audio) status = message["data"]["status"] #print(message) if status == 2: print("ws is closed") ws.close() if code != 0: errMsg = message["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: pcm_path = "${path}" with open(pcm_path, "ab") as f: f.write(audio) print("tts") with open(pcm_path, "rb") as pcmfile: pcmdata = pcmfile.read() with wave.open(pcm_path + ".wav", "wb") as wavfile: wavfile.setparams((1, 2, 16000, 0, "NONE", "NONE")) wavfile.writeframes(pcmdata) except Exception as e: print("receive msg,but parse exception:", e) # 收到websocket错误的处理 def on_error(ws, error): print("### error:", error) # 收到websocket关闭的处理 def on_close(ws): print("### closed ###") # 收到websocket连接建立的处理 def on_open(ws): def run(*args): global wsParam_Audio d = {"common": wsParam_Audio.CommonArgs,"business": wsParam_Audio.BusinessArgs,"data": wsParam_Audio.Data,} d = json.dumps(d) print("------>开始发送文本数据") ws.send(d) if os.path.exists(${url}): os.remove(${url}) thread.start_new_thread(run, ()) ` Blockly.Python.addVariable('wsParam_Audio', 'wsParam_Audio = ""', true); let code = `if __name__ == "__main__": #with open('word.txt', 'r',encoding="UTF-8")as f:#txt= f.read() txt_Audio=${text} if os.path.exists(${url}): os.remove(${url}) # 测试时候在此处正确填写相关信息即可运行 wsParam_Audio = Ws_Param_Audio(APPID=APPId_Audio, APISecret=APISecret_Audio,APIKey=APIKey_Audio,Text=txt_Audio) websocket.enableTrace(False) wsUrl = wsParam_Audio.create_url() ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) ` // TODO: Change ORDER_NONE to the correct strength. return code }; // 在线物体识别 Blockly.Blocks['ai_online_object_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_object_init); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); // this.appendValueInput("B").setCheck(null).appendField('APISecret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_object_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_object_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_.ai_online_object_init = ` API_KEY = ${APIKey} APPID = ${APPId} def objectGetHeader(APPID, image_url, API_KEY): with open(image_url, "rb") as f: img_data = f.read() curTime = str(int(time.time())) paramBase64 = base64.b64encode(img_data) tmp = str(paramBase64, "utf-8") m2 = hashlib.md5() m2.update((API_KEY + curTime + tmp).encode("utf-8")) checkSum = m2.hexdigest() header = { 'X-CurTime': curTime, 'X-Param': paramBase64, 'X-Appid': APPID, 'X-CheckSum': checkSum, } return header ` var code = ''; return code; }; Blockly.Blocks['ai_online_object_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_object_load); // this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_object_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_object_loading = function (block) { var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); let code = `ImageUrl = ${AudioFile} OBJECTRESULT = requests.post("http://tupapi.xfyun.cn/v1/currency", headers=objectGetHeader(APPID, ImageUrl,API_KEY)) ` return code } Blockly.Blocks['ai_online_object_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_object_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_object_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_object_result'] = function (block) { let code = `OBJECTRESULT.content`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 在线车牌识别 Blockly.Blocks['ai_online_card_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_card_init); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); //Blockly.Msg.online_voice_init_path this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_card_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_card_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_traceback'] = `import traceback` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_.ai_online_card_init = ` APPId_Card = ${APPId} APISecret_Card = ${APISecret} APIKey_Card = ${APIKey} class AssembleHeaderException_Card(Exception): def __init__(self, msg): self.message = msg class Url_Card: def __init__(this, host, path, schema): this.host = host this.path = path this.schema = schema pass # 进行sha256加密和base64编码 def sha256base64_Card(data): sha256 = hashlib.sha256() sha256.update(data) digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8") return digest def parse_url_Card(requset_url): stidx = requset_url.index("://") host = requset_url[stidx + 3:] schema = requset_url[:stidx + 3] edidx = host.index("/") if edidx <= 0: raise AssembleHeaderException_Card("invalid request url:" + requset_url) path = host[edidx:] host = host[:edidx] u = Url_Card(host, path, schema) return u def assemble_ws_auth_url_Card(requset_url, method="GET", api_key="", api_secret=""): u = parse_url_Card(requset_url) host = u.host path = u.path now = datetime.now() date = format_date_time(mktime(now.timetuple())) print(date) # date = "Thu, 12 Dec 2019 01:57:27 GMT" signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path) print(signature_origin) signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % ( api_key, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") print(authorization_origin) values = { "host": host, "date": date, "authorization": authorization } return requset_url + "?" + urlencode(values) def gen_body_Card(appid, img_path, server_id): with open(img_path, "rb") as f: img_data = f.read() body = { "header": { "app_id": appid, "status": 3 }, "parameter": { server_id: { "carLicenseRes": { "encoding": "utf8", "compress": "raw", "format": "json" } } }, "payload": { "carImgBase64Str": { "encoding": "jpg", "status": 3, "image": str(base64.b64encode(img_data), "utf-8") } } } return json.dumps(body) ` var code = ''; return code; }; Blockly.Blocks['ai_online_card_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_card_load); // this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.online_face_init_path); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_card_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_card_loading = function (block) { var AudioFile = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_.ai_online_card_load = `def run_Card(appid, apikey, apisecret, img_path, server_id="jd_ocr_car"): url = "http://api.xf-yun.com/v1/private/{}".format(server_id) request_url = assemble_ws_auth_url_Card(url, "POST", apikey, apisecret) headers = {"content-type": "application/json", "host": "api.xf-yun.com", "app_id": appid} #print(request_url) response = requests.post(request_url, data=gen_body_Card(appid, img_path, server_id), headers=headers) resp_data = json.loads(response.content.decode("utf-8")) print(resp_data) resultCard = base64.b64decode(resp_data["payload"]["carLicenseRes"]["text"]).decode("utf-8") return json.loads(resultCard) CARDRESULT = "" ` let code = `if __name__ == "__main__": img_path_Card = ${AudioFile} CARDRESULT = run_Card(appid=APPId_Card,apisecret=APISecret_Card,apikey=APIKey_Card,img_path=img_path_Card,) ` return code } Blockly.Blocks['ai_online_card_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.online_card_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.online_card_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_card_result'] = function (block) { let code = `CARDRESULT`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 机器翻译 Blockly.Blocks['ai_online_machine_translation_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.machine_translation_init); // this.appendDummyInput() .appendField(Blockly.Msg.BLYNK_GET_DATANAME) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"], [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"], ]), "from") .appendField(Blockly.Msg.machine_translation_to) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"], [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"], ]), "to"); this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.machine_translation_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_machine_translation_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); let FROM = block.getFieldValue('from') let TO = block.getFieldValue('to') // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_.ai_online_machine_translation_init = ` APPId_machine = ${APPId} APISecret_machine = ${APISecret} APIKey_machine = ${APIKey} TRANSLATIONTEXT = "" class get_result_machine(object): def __init__(self,host,TRANSLATIONTEXT): # 应用ID(到控制台获取) self.APPID_machine = ${APPId} # 接口APISercet(到控制台机器翻译服务页面获取) self.Secret_machine = ${APISecret} # 接口APIKey(到控制台机器翻译服务页面获取) self.APIKey_machine= ${APIKey} # 以下为POST请求 self.Host = "itrans.xfyun.cn" self.RequestUri = "/v2/its" # 设置url # print(host) self.url="https://"+host+self.RequestUri self.HttpMethod = "POST" self.Algorithm = "hmac-sha256" self.HttpProto = "HTTP/1.1" # 设置当前时间 curTime_utc = datetime.utcnow() self.Date = self.httpdate_machine(curTime_utc) # 设置业务参数 # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html self.Text=TRANSLATIONTEXT self.BusinessArgs={ "from": "${FROM}", "to": "${TO}", } def hashlib_256_machine(self, res): m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest() result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8") return result def httpdate_machine(self, dt): """ Return a string representation of a date according to RFC 1123 (HTTP/1.1). The supplied date must be in UTC. """ weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()] month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month - 1] return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second) def generateSignature_machine(self, digest): signatureStr = "host: " + self.Host + "\\n" signatureStr += "date: " + self.Date + "\\n" signatureStr += self.HttpMethod + " " + self.RequestUri \\ + " " + self.HttpProto + "\\n" signatureStr += "digest: " + digest signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")), bytes(signatureStr.encode(encoding="utf-8")), digestmod=hashlib.sha256).digest() result = base64.b64encode(signature) return result.decode(encoding="utf-8") def init_header_machine(self, data): digest = self.hashlib_256_machine(data) #print(digest) sign = self.generateSignature_machine(digest) authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\"" #print(authHeader) headers = { "Content-Type": "application/json", "Accept": "application/json", "Method": "POST", "Host": self.Host, "Date": self.Date, "Digest": digest, "Authorization": authHeader } return headers def get_body_machine(self): content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8") postdata = { "common": {"app_id": self.APPID_machine}, "business": self.BusinessArgs, "data": { "text": content, } } body = json.dumps(postdata) #print(body) return body def call_url_machine(self): if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "": print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。") else: code = 0 body=self.get_body_machine() headers=self.init_header_machine(body) #print(self.url) response = requests.post(self.url, data=body, headers=headers,timeout=8) status_code = response.status_code #print(response.content) if status_code!=200: # 鉴权失败 print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text) print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html") else: # 鉴权成功 respData = json.loads(response.text) #print('result',respData["data"]['result']['trans_result']['dst']) # return # 以下仅用于调试 code = str(respData["code"]) if code=="0": return respData["data"]["result"]["trans_result"]["dst"] else: print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法") ` var code = ''; return code; }; Blockly.Blocks['ai_online_machine_translation_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.machine_translation_load); // this.appendDummyInput() .appendField(Blockly.Msg.BLYNK_GET_DATANAME) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"], [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"], ]), "from") .appendField(Blockly.Msg.machine_translation_to) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_speech_recognition_setup_set_english, "en"], [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "cn"], ]), "to"); this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.Content_of_text); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.machine_translation_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_machine_translation_loading = function (block) { let text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC) var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); let FROM = block.getFieldValue('from') let TO = block.getFieldValue('to') // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_.ai_online_machine_translation_init = ` APPId_machine = ${APPId} APISecret_machine = ${APISecret} APIKey_machine = ${APIKey} TRANSLATIONTEXT = "" class get_result_machine(object): def __init__(self,host,TRANSLATIONTEXT): # 应用ID(到控制台获取) self.APPID_machine = ${APPId} # 接口APISercet(到控制台机器翻译服务页面获取) self.Secret_machine = ${APISecret} # 接口APIKey(到控制台机器翻译服务页面获取) self.APIKey_machine= ${APIKey} # 以下为POST请求 self.Host = "itrans.xfyun.cn" self.RequestUri = "/v2/its" # 设置url # print(host) self.url="https://"+host+self.RequestUri self.HttpMethod = "POST" self.Algorithm = "hmac-sha256" self.HttpProto = "HTTP/1.1" # 设置当前时间 curTime_utc = datetime.utcnow() self.Date = self.httpdate_machine(curTime_utc) # 设置业务参数 # 语种列表参数值请参照接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html self.Text=TRANSLATIONTEXT self.BusinessArgs={ "from": "${FROM}", "to": "${TO}", } def hashlib_256_machine(self, res): m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest() result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8") return result def httpdate_machine(self, dt): """ Return a string representation of a date according to RFC 1123 (HTTP/1.1). The supplied date must be in UTC. """ weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()] month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month - 1] return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second) def generateSignature_machine(self, digest): signatureStr = "host: " + self.Host + "\\n" signatureStr += "date: " + self.Date + "\\n" signatureStr += self.HttpMethod + " " + self.RequestUri \\ + " " + self.HttpProto + "\\n" signatureStr += "digest: " + digest signature = hmac.new(bytes(self.Secret_machine.encode(encoding="utf-8")), bytes(signatureStr.encode(encoding="utf-8")), digestmod=hashlib.sha256).digest() result = base64.b64encode(signature) return result.decode(encoding="utf-8") def init_header_machine(self, data): digest = self.hashlib_256_machine(data) #print(digest) sign = self.generateSignature_machine(digest) authHeader = "api_key=\\""+self.APIKey_machine+"\\", algorithm=\\""+self.Algorithm+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\"" #print(authHeader) headers = { "Content-Type": "application/json", "Accept": "application/json", "Method": "POST", "Host": self.Host, "Date": self.Date, "Digest": digest, "Authorization": authHeader } return headers def get_body_machine(self): content = str(base64.b64encode(self.Text.encode("utf-8")), "utf-8") postdata = { "common": {"app_id": self.APPID_machine}, "business": self.BusinessArgs, "data": { "text": content, } } body = json.dumps(postdata) #print(body) return body def call_url_machine(self): if self.APPID_machine == "" or self.APIKey_machine == "" or self.Secret_machine == "": print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。") else: code = 0 body=self.get_body_machine() headers=self.init_header_machine(body) #print(self.url) response = requests.post(self.url, data=body, headers=headers,timeout=8) status_code = response.status_code #print(response.content) if status_code!=200: # 鉴权失败 print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text) print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/nlp/xftrans/API.html") else: # 鉴权成功 respData = json.loads(response.text) #print('result',respData["data"]['result']['trans_result']['dst']) # return # 以下仅用于调试 code = str(respData["code"]) if code=="0": return respData["data"]["result"]["trans_result"]["dst"] else: print("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法") ` let code = `TRANSLATIONTEXT = ${text} machinehost = "itrans.xfyun.cn" #初始化类 gClass=get_result_machine(host=machinehost,TRANSLATIONTEXT=TRANSLATIONTEXT) TRANSLATIONRESULT = gClass.call_url_machine() ` return code } Blockly.Blocks['ai_online_machine_translation_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.machine_translation_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.machine_translation_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_machine_translation_result'] = function (block) { let code = `TRANSLATIONRESULT`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 手写文字识别 Blockly.Blocks['ai_online_handwritten_text_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.handwritten_text_init); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); // this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.handwritten_text_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_handwritten_text_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse` Blockly.Python.definitions_.ai_online_handwritten_text_init = ` URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting" APPId_handwritten_text = ${APPId} APIKey_handwritten_text = ${APIKey} def textGetHeader_handwritten_text(language, location): curTime = str(int(time.time())) param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}" paramBase64 = base64.b64encode(param.encode("utf-8")) m2 = hashlib.md5() str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8") m2.update(str1.encode("utf-8")) checkSum = m2.hexdigest() # 组装http请求头 header = { "X-CurTime": curTime, "X-Param": paramBase64, "X-Appid": APPId_handwritten_text, "X-CheckSum": checkSum, "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", } return header def getBody_handwritten_text(filepath): with open(filepath, "rb") as f: imgfile = f.read() data = {"image": str(base64.b64encode(imgfile), "utf-8")} return data ` var code = ''; return code; }; Blockly.Blocks['ai_online_handwritten_text_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.handwritten_text_load); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); // this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.online_face_init_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.handwritten_text_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_handwritten_text_loading = function (block) { let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); // var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse` Blockly.Python.definitions_.ai_online_handwritten_text_init = ` URL_handwritten_text = "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting" APPId_handwritten_text = ${APPId} APIKey_handwritten_text = ${APIKey} def textGetHeader_handwritten_text(language, location): curTime = str(int(time.time())) param = "{\\"language\\":\\""+language+"\\",\\"location\\":\\""+location+"\\"}" paramBase64 = base64.b64encode(param.encode("utf-8")) m2 = hashlib.md5() str1 = APIKey_handwritten_text + curTime + str(paramBase64, "utf-8") m2.update(str1.encode("utf-8")) checkSum = m2.hexdigest() # 组装http请求头 header = { "X-CurTime": curTime, "X-Param": paramBase64, "X-Appid": APPId_handwritten_text, "X-CheckSum": checkSum, "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", } return header def getBody_handwritten_text(filepath): with open(filepath, "rb") as f: imgfile = f.read() data = {"image": str(base64.b64encode(imgfile), "utf-8")} return data ` let code = `# 语种设置 textLanguage = "cn|en" # 是否返回文本位置信息 textLocation = "false" # 图片上传接口地址 picFilePath_handwritten_text = ${text} HandwrittenTextData = requests.post(URL_handwritten_text, headers=textGetHeader_handwritten_text(textLanguage, textLocation), data=getBody_handwritten_text(picFilePath_handwritten_text)) ` return code } Blockly.Blocks['ai_online_handwritten_text_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.handwritten_text_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.handwritten_text_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_handwritten_text_result'] = function (block) { Blockly.Python.definitions_.ai_online_handwritten_text_result = `def handwrittenTextDatas_handwritten_text(r): my_json_data = r.content.decode("utf8") # print(type(my_json)) loadsData = json.loads(my_json_data) # s = json.dumps(data, indent=4, sort_keys=True) print("data",my_json_data) deal_data = "" if loadsData["code"] == "0" : t = loadsData["data"]["block"][0]["line"] for i in t: print(i) for j in i["word"]: print(j["content"]) deal_data = deal_data + j["content"] + " " #print('deal_data',deal_data) return deal_data ` let code = `handwrittenTextDatas_handwritten_text(HandwrittenTextData)`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 公式识别 Blockly.Blocks['ai_online_formula_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.formula_init); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.formula_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_formula_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object): def __init__(self,host,path): # 应用ID(到控制台获取) self.APPID_formula = ${APPId} # 接口APISercet(到控制台公式识别服务页面获取) self.Secret_formula = ${APISecret} # 接口APIKey(到控制台公式识别服务页面获取) self.APIKey_formula = ${APIKey} # 以下为POST请求 self.Host_formula = host self.RequestUri_formula = "/v2/itr" # 设置url # print(host) self.url_formula="https://"+host+self.RequestUri_formula self.HttpMethod_formula = "POST" self.Algorithm_formula = "hmac-sha256" self.HttpProto_formula = "HTTP/1.1" # 设置当前时间 curTime_utc = datetime.utcnow() self.Date_formula = self.httpdate_formula(curTime_utc) #设置测试图片文件 self.AudioPath_formula = path self.BusinessArgs_formula={ "ent": "teach-photo-print", "aue": "raw", } def imgRead_formula(self, path): with open(path, "rb") as fo: return fo.read() def hashlib_256_formula(self, res): m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest() result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8") return result def httpdate_formula(self, dt): """ Return a string representation of a date according to RFC 1123 (HTTP/1.1). The supplied date must be in UTC. """ weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()] month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month - 1] return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second) def generateSignature_formula(self, digest): signatureStr = "host: " + self.Host_formula + "\\n" signatureStr += "date: " + self.Date_formula + "\\n" signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\ + " " + self.HttpProto_formula + "\\n" signatureStr += "digest: " + digest signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")), bytes(signatureStr.encode(encoding="utf-8")), digestmod=hashlib.sha256).digest() result = base64.b64encode(signature) return result.decode(encoding="utf-8") def init_header_formula(self, data): digest = self.hashlib_256_formula(data) #print(digest) sign = self.generateSignature_formula(digest) authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\"" #print(authHeader) headers = { "Content-Type": "application/json", "Accept": "application/json", "Method": "POST", "Host": self.Host_formula, "Date": self.Date_formula, "Digest": digest, "Authorization": authHeader } return headers def get_body_formula(self): audioData = self.imgRead_formula(self.AudioPath_formula) content = base64.b64encode(audioData).decode(encoding="utf-8") postdata = { "common": {"app_id": self.APPID_formula}, "business": self.BusinessArgs_formula, "data": { "image": content, } } body = json.dumps(postdata) #print(body) return body def call_url_formula(self): if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "": print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。") else: code = 0 body=self.get_body_formula() headers=self.init_header_formula(body) #print(self.url_formula) response = requests.post(self.url_formula, data=body, headers=headers,timeout=8) status_code = response.status_code #print(response.content) if status_code!=200: # 鉴权失败 print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text) print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html") else: # 鉴权成功 respData = json.loads(response.text) dataCotent = "" try: for i in respData["data"]["region"]: dataCotent += i["recog"]["content"] except: dataCotent = "Failure" return dataCotent FORMULARESULT = "" ` var code = ''; return code; }; Blockly.Blocks['ai_online_formula_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.formula_load); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.online_face_init_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.formula_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_formula_loading = function (block) { let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_.ai_online_formula_init = `class get_result_formula(object): def __init__(self,host,path): # 应用ID(到控制台获取) self.APPID_formula = ${APPId} # 接口APISercet(到控制台公式识别服务页面获取) self.Secret_formula = ${APISecret} # 接口APIKey(到控制台公式识别服务页面获取) self.APIKey_formula = ${APIKey} # 以下为POST请求 self.Host_formula = host self.RequestUri_formula = "/v2/itr" # 设置url # print(host) self.url_formula="https://"+host+self.RequestUri_formula self.HttpMethod_formula = "POST" self.Algorithm_formula = "hmac-sha256" self.HttpProto_formula = "HTTP/1.1" # 设置当前时间 curTime_utc = datetime.utcnow() self.Date_formula = self.httpdate_formula(curTime_utc) #设置测试图片文件 self.AudioPath_formula = path self.BusinessArgs_formula={ "ent": "teach-photo-print", "aue": "raw", } def imgRead_formula(self, path): with open(path, "rb") as fo: return fo.read() def hashlib_256_formula(self, res): m = hashlib.sha256(bytes(res.encode(encoding="utf-8"))).digest() result = "SHA-256=" + base64.b64encode(m).decode(encoding="utf-8") return result def httpdate_formula(self, dt): """ Return a string representation of a date according to RFC 1123 (HTTP/1.1). The supplied date must be in UTC. """ weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()] month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month - 1] return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second) def generateSignature_formula(self, digest): signatureStr = "host: " + self.Host_formula + "\\n" signatureStr += "date: " + self.Date_formula + "\\n" signatureStr += self.HttpMethod_formula + " " + self.RequestUri_formula \\ + " " + self.HttpProto_formula + "\\n" signatureStr += "digest: " + digest signature = hmac.new(bytes(self.Secret_formula.encode(encoding="utf-8")), bytes(signatureStr.encode(encoding="utf-8")), digestmod=hashlib.sha256).digest() result = base64.b64encode(signature) return result.decode(encoding="utf-8") def init_header_formula(self, data): digest = self.hashlib_256_formula(data) #print(digest) sign = self.generateSignature_formula(digest) authHeader = "api_key=\\""+self.APIKey_formula+"\\", algorithm=\\""+self.Algorithm_formula+"\\", headers=\\"host date request-line digest\\", signature=\\""+sign+"\\"" #print(authHeader) headers = { "Content-Type": "application/json", "Accept": "application/json", "Method": "POST", "Host": self.Host_formula, "Date": self.Date_formula, "Digest": digest, "Authorization": authHeader } return headers def get_body_formula(self): audioData = self.imgRead_formula(self.AudioPath_formula) content = base64.b64encode(audioData).decode(encoding="utf-8") postdata = { "common": {"app_id": self.APPID_formula}, "business": self.BusinessArgs_formula, "data": { "image": content, } } body = json.dumps(postdata) #print(body) return body def call_url_formula(self): if self.APPID_formula == "" or self.APIKey_formula == "" or self.Secret_formula == "": print("Appid 或APIKey 或APISecret 为空!请打开demo代码,填写相关信息。") else: code = 0 body=self.get_body_formula() headers=self.init_header_formula(body) #print(self.url_formula) response = requests.post(self.url_formula, data=body, headers=headers,timeout=8) status_code = response.status_code #print(response.content) if status_code!=200: # 鉴权失败 print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text) print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html") else: # 鉴权成功 respData = json.loads(response.text) dataCotent = "" try: for i in respData["data"]["region"]: dataCotent += i["recog"]["content"] except: dataCotent = "Failure" return dataCotent FORMULARESULT = "" ` let code = ` if __name__ == "__main__": formulaUrlPath_formula = ${text} ##示例: host="rest-api.xfyun.cn"域名形式 host = "rest-api.xfyun.cn" #初始化类 gClass=get_result_formula(host,path=formulaUrlPath_formula) FORMULARESULT = gClass.call_url_formula() ` return code } Blockly.Blocks['ai_online_formula_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.formula_result); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.formula_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_formula_result'] = function (block) { let code = `FORMULARESULT`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 身份证识别 Blockly.Blocks['ai_online_ID_card_init'] = { init: function () { this.appendDummyInput() .appendField('身份证识别初始化'); // this.appendValueInput("A").setCheck(null).appendField('APP ID'); this.appendValueInput("B").setCheck(null).appendField('API Secret'); this.appendValueInput("C").setCheck(null).appendField('API Key'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.handwritten_text_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_ID_card_init'] = function (block) { var APPId = Blockly.Python.valueToCode(block, 'A', Blockly.Python.ORDER_ATOMIC); var APISecret = Blockly.Python.valueToCode(block, 'B', Blockly.Python.ORDER_ATOMIC); var APIKey = Blockly.Python.valueToCode(block, 'C', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_hashlib'] = `import hashlib` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_hmac'] = `import hmac` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['v831_import_from_time_mktime'] = `from time import mktime` Blockly.Python.definitions_['v831_import_datetime_datetime'] = `from datetime import datetime` Blockly.Python.definitions_['v831_import_from_urllib_parse'] = `from urllib import parse` Blockly.Python.definitions_['v831_import_format_date_time'] = `from wsgiref.handlers import format_date_time` Blockly.Python.definitions_['v831_import_urlencode'] = `from urllib.parse import urlencode` Blockly.Python.definitions_.ai_online_formula_init = `class AssembleHeaderException(Exception): def __init__(self, msg): self.message = msg class Url: def __init__(this, host, path, schema): this.host = host this.path = path this.schema = schema pass # calculate sha256 and encode to base64 def sha256base64(data): sha256 = hashlib.sha256() sha256.update(data) digest = base64.b64encode(sha256.digest()).decode(encoding="utf-8") return digest def parse_url(requset_url): stidx = requset_url.index("://") host = requset_url[stidx + 3:] schema = requset_url[:stidx + 3] edidx = host.index("/") if edidx <= 0: raise AssembleHeaderException("invalid request url:" + requset_url) path = host[edidx:] host = host[:edidx] u = Url(host, path, schema) return u # build websocket auth request url def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""): u = parse_url(requset_url) host = u.host path = u.path now = datetime.now() date = format_date_time(mktime(now.timetuple())) #print(date) # date = "Thu, 12 Dec 2019 01:57:27 GMT" signature_origin = "host: {}\\ndate: {}\\n{} {} HTTP/1.1".format(host, date, method, path) #print(signature_origin) signature_sha = hmac.new(api_secret.encode("utf-8"), signature_origin.encode("utf-8"), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") authorization_origin = "api_key=\\"%s\\", algorithm=\\"%s\\", headers=\\"%s\\", signature=\\"%s\\"" % ( api_key, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(encoding="utf-8") #print(authorization_origin) values = { "host": host, "date": date, "authorization": authorization } return requset_url + "?" + urlencode(values) # 控制台获取以下信息 APPId = ${APPId} APISecret = ${APISecret} APIKey = ${APIKey} ` var code = ''; return code; }; Blockly.Blocks['ai_online_ID_card_loading'] = { init: function () { this.appendDummyInput() .appendField('身份证识别加载'); // // this.appendDummyInput() // .appendField('设置识别语种') // .appendField(new Blockly.FieldDropdown([ // ["en", "en"], // ["cn|en", "cn|en"], // ]), "language"); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.online_face_init_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.handwritten_text_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_ID_card_loading = function (block) { let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC); let code = `with open(${text}, "rb") as f: imageBytes = f.read() url = 'http://api.xf-yun.com/v1/private/s5ccecfce' body = { "header": { "app_id": APPId, "status": 3, }, "parameter": { "s5ccecfce": { "template_list": "id_card", "result": { "encoding": "utf8", "compress": "raw", "format": "json" } } }, "payload": { "s5ccecfce_data_1": { "encoding": "jpg", "image": str(base64.b64encode(imageBytes), 'UTF-8'), "status": 3 } } } request_Id_card_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret) headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId} #print(request_url) Id_card_response = requests.post(request_Id_card_url, data=json.dumps(body), headers=headers) IDCardtempResult = json.loads(Id_card_response.content.decode()) IDCardfinalResult = base64.b64decode(IDCard['payload']['result']['text']).decode() IDCardfinalResult = IDCardfinalResult.replace(" ", "").replace("\n", "").replace("\t", "").strip() ` return code } Blockly.Blocks['ai_online_ID_card_result'] = { init: function () { this.appendDummyInput() .appendField('身份证识别结果'); // this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.handwritten_text_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_ID_card_result'] = function (block) { let code = `IDCardfinalResult`; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 情绪识别 Blockly.Blocks['ai_online_emotion_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.emotion_init); // this.appendValueInput("path") // .setCheck(null).appendField(Blockly.Msg.set_dictionary) // .appendField(new Blockly.FieldVariable("emotion_recognize_result"), "varitem"); // this.appendDummyInput().appendField(Blockly.Msg.dictionary_contain); this.setInputsInline(false) this.setPreviousStatement(true, null); this.setNextStatement(true, null);; // this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.emotion_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_emotion_init'] = function (block) { // let = [] // let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true); Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path): with open(single_image_path, "rb") as fp: imgbase64 = base64.b64encode(fp.read()) return imgbase64.decode() url = "https://ai-api.cocorobo.hk/face" ` // ${variable_name} =${text} var code = ``; return code; }; Blockly.Blocks['ai_online_emotion_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.emotion_load); // this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.online_face_init_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.emotion_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_emotion_loading = function (block) { let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.addVariable("EMOTION_SEND_REQUEST", "EMOTION_SEND_REQUEST = {}", true); Blockly.Python.definitions_['emotion_init'] = `def get_img_base64str(single_image_path): with open(single_image_path, "rb") as fp: imgbase64 = base64.b64encode(fp.read()) return imgbase64.decode() url = "https://ai-api.cocorobo.cn/face" ` // let language = Blockly.Python.valueToCode(block, 'language', Blockly.Python.ORDER_ATOMIC); let code = `imageEmotionURLbase64 = str(get_img_base64str(${text})) # print(imageURLbase64) data = "{\\"image\\":\\"" + str(imageEmotionURLbase64) + "\\"}" try: EMOTION_SEND_REQUEST = requests.post(url, data = data , headers = { "Ocp-Apim-Subscription-Key": "6baf787532ef4eec8bc93c88518b8916", "Content-type": "application/json" }, timeout = 10000) EMOTION_SEND_REQUEST = json.loads(EMOTION_SEND_REQUEST.content)["data"]["result"]["face_list"][0] # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content)) except BaseException as e: EMOTION_SEND_REQUEST = "no result" pass ` return code } Blockly.Blocks['ai_online_emotion_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.emotion_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.emotion_result_age, "age"], [Blockly.Msg.emotion_result_emotion, "emotion"], [Blockly.Msg.emotion_result_gender, "gender"], [Blockly.Msg.emotion_result_expression, "expression"] ]), "emotion_type"); this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.emotion_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_emotion_result'] = function (block) { var type = block.getFieldValue('emotion_type'); let code = "" // console.log(type) if (type == "age") { code = `EMOTION_SEND_REQUEST["age"]` } else { code = `EMOTION_SEND_REQUEST["${type}"]["type"]` } return [code, Blockly.Python.ORDER_ATOMIC]; }; // 手势识别 Blockly.Blocks['ai_online_gesture_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.gesture_init); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.gesture_init); this.setHelpUrl(""); } }; Blockly.Python['ai_online_gesture_init'] = function (block) { // let = [] // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['emotion_init'] = ` def getImgData(single_image_path): imgGesture = Image.open(single_image_path).convert("RGB") imgGesture.save(single_image_path.split(".")[0] + ".png", "png") with open(single_image_path.split(".")[0] + ".png", "rb") as fp: return fp.read() url = "https://ai-api.cocorobo.hk/gesture" ` var code = ''; return code; }; Blockly.Blocks['ai_online_gesture_loading'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.gesture_load); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.online_face_init_path); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.gesture_load); this.setHelpUrl(""); } } Blockly.Python.ai_online_gesture_loading = function (block) { let text = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC) Blockly.Python.definitions_['v831_import_fromPIL_Image'] = `from PIL import Image` Blockly.Python.definitions_['v831_import_base64'] = `import base64` Blockly.Python.definitions_['v831_import_requests'] = `import requests` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['emotion_init'] = ` def getImgData(single_image_path): imgGesture = Image.open(single_image_path).convert("RGB") imgGesture.save(single_image_path.split(".")[0] + ".png", "png") with open(single_image_path.split(".")[0] + ".png", "rb") as fp: return fp.read() url = "https://ai-api.cocorobo.cn/gesture" ` let code = `try: payload={} files=[("image",("filename.png", getImgData(${text}),"image/png"))] headers = {} GESTURE_SEND_REQUEST = requests.post(url, headers=headers, data=payload, files=files, timeout = 10000) GESTURE_SEND_REQUEST = json.loads(GESTURE_SEND_REQUEST.content)["data"]["result"][0]["classname"] # print(str(_COCOCLOUD_SEND_REQUEST.status_code)+", "+str(_COCOCLOUD_SEND_REQUEST.content)) except BaseException as e: GESTURE_SEND_REQUEST = "no result" pass ` return code } Blockly.Blocks['ai_online_gesture_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.gesture_result); this.setOutput(true, null); this.setColour("#0000ff"); this.setTooltip(Blockly.Msg.gesture_result); this.setHelpUrl(""); } }; Blockly.Python['ai_online_gesture_result'] = function (block) { let code = `GESTURE_SEND_REQUEST` return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_audio_set'] = { init: function () { this.appendValueInput("Num") .setCheck(null) .appendField(Blockly.Msg.ai_audio_set_music_vol); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#603ea0"); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Python.ai_audio_set = function (block) { var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC); var _code = "_player.volume(" + _num + ")\n" return _code; } var SPEECH_RECOGNITION_BLOCK_COLOR = "230"; Blockly.Blocks['speech_recognition_new_setup'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_setup); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_new_setup_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_new_setup'] = function (block) { Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc` Blockly.Python.definitions_["v831_import_time"] = `import time` Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`; Blockly.Python.addVariable("RecordState", "RecordState = 0", true); Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true); Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true); let code = "" return code; }; Blockly.Blocks['speech_recognition_clear'] = { init: function () { // this.appendDummyInput() // .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_new.png", 70, 70, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_Clean_up_the_last_study_result); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_clear'] = function (block) { Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc` Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`; var code = `mfcc.clear() `; return code; }; Blockly.Blocks['speech_recognition_record_start_result'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recording_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_start_recording); this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_start_recording_clip_text) .appendField(new Blockly.FieldNumber(2, 1, 6, 1), "clip") // .appendField(Blockly.Msg.ai_speech_recognition_start_recording_take_note); this.appendDummyInput() .appendField(Blockly.Msg.image_process_interface) .appendField(new Blockly.FieldVariable("recordCanvas"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_speech_recognition_start_recording); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_record_start_result'] = function (block) { var number_take = block.getFieldValue('clip'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc` Blockly.Python.definitions_["v831_import_time"] = `import time` Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`; Blockly.Python.addVariable("RecordState", "RecordState = 0", true); Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true); Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true); Blockly.Python.addVariable('number_take', `number_take = ${number_take}`, true) Blockly.Python.definitions_["v831_mfcc_clear"] = `mfcc.clear() ` Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_camera_set'] = `cameraSize = True def CAMERATYPE(): global cameraSize try: if os.path.exists("/etc/cameraSize.cfg"): cameraSize = True else: cameraSize = False except: cameraSize = False CAMERATYPE() ` Blockly.Python.addVariable("ScreenOrientation", `ScreenOrientation = False`, true) Blockly.Python.addVariable(variable_name, `${variable_name} = image.new(size = (320, 240))`, true) Blockly.Python.definitions_['import_image'] = `image.load_freetype("/root/preset/fonts/simhei.ttf") if cameraSize==True: camera.camera.config(size=(320,240)) else: camera.camera.config(size=(240,320)) ` let idenSuccess = "录制成功"; let speek = "说第"; let SpeechFragment = "语音片段"; if (localStorage.getItem('handPyLanguage') == "zh-hant") { idenSuccess = "錄製成功"; speek = "說第 "; SpeechFragment = "語音片段"; } else if (localStorage.getItem('handPyLanguage') == "en") { idenSuccess = "Recorded successfully"; speek = "Speek "; SpeechFragment = "Speech fragment"; } var code = `if RecordState == 0: mfcc.recording(recordFrequency) recordFrequency = recordFrequency + 1 time.sleep(1) RecordState = 1 if RecordState == 1: recordData = mfcc.state() if recordData == mfcc._mfcc_result: ${variable_name}.draw_string(0,80,"${idenSuccess}", scale = 2, color = (0,204,204) , thickness = 1) time.sleep(1) if recordFrequency < number_take: RecordState = 0 else: ${variable_name}.draw_string(0,80, "${speek} "+str(recordFrequency)+" ${SpeechFragment}", scale = 2, color = (0,204,204) , thickness = 1) ` return code }; Blockly.Blocks['speech_recognition_new_start_recognition'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_start_recognizing); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_new_start_recognition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_new_start_recognition'] = function (block) { Blockly.Python.definitions_["v831_import_coco_mfcc"] = `import _coco_mfcc` Blockly.Python.definitions_["v831_import_time"] = `import time` Blockly.Python.definitions_["v831_coco_mfcc_init"] = `mfcc = _coco_mfcc.MFCC(is_reply=False)`; Blockly.Python.addVariable("RecordState", "RecordState = 0", true); Blockly.Python.addVariable("recordFrequency", "recordFrequency = 0", true); Blockly.Python.addVariable("recordResultData", `recordResultData = None`, true); var code = `if RecordState == 0: mfcc.recognize() recordResultData = None time.sleep(1) RecordState = 1 ` return code }; Blockly.Blocks['speech_recognition_new_recognition_get_any_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_any_result_text); this.appendStatementInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_any_result_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_new_recognition_get_any_result'] = function (block) { var statements_name = Blockly.Python.statementToCode(block, 'NAME'); // TODO: Assemble Python into code variable. var code = `if RecordState == 1: recordData = mfcc.state() if recordData == mfcc._mfcc_result: recordResultData = mfcc.result() time.sleep(1) RecordState = 0 ${statements_name} `; return code; }; Blockly.Blocks['speech_recognition_new_recognition_get_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_get_result) .appendField(new Blockly.FieldNumber(1, 1, 6, 1), "index") .appendField(Blockly.Msg.ai_speech_recognition_get_result_after); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_new_recognition_get_result_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_new_recognition_get_result'] = function (block) { var number_index = block.getFieldValue('index'); // TODO: Assemble Python into code variable. var code = `recordResultData == ${number_index - 1}`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; /* _ ___ ____ _ / \ |_ _| / ___| _ __ ___ __ _| | _____ _ __ / _ \ | | \___ \| '_ \ / _ \/ _` | |/ / _ \ '__| / ___ \ _ | | _ ___) | |_) | __/ (_| | < __/ | /_/ \_(_)___(_) |____/| .__/ \___|\__,_|_|\_\___|_| |_| */ Blockly.Blocks['ai_audio_init_speaker'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_init); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_init_speaker_TOOLTIP); this.setHelpUrl(""); this.setPreviousStatement(true); this.setNextStatement(true); } }; Blockly.Python.ai_audio_init_speaker = function (block) { Blockly.Python.definitions_.import_Maix = "from Maix import I2S, GPIO"; Blockly.Python.definitions_.import_fpioa_manager = "from fpioa_manager import *"; Blockly.Python.definitions_.import_audio = "import audio"; var _code = ""; return _code; } Blockly.Blocks['ai_audio_play_song_speaker'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_play_music_file); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol) // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol"); this.appendValueInput("volume") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_song_speaker'] = function (block) { // var number_play_vol = block.getFieldValue('play_vol'); var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC); var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var _in = "" + "_audio_rx = I2S(I2S.DEVICE_1)\n" + "\n" + "def _speaker_play_song(path, volume):\n" + " global _audio_play_state,_player\n" + " _player = audio.Audio(path = path)\n" + " _player.volume(volume)\n" + " try:\n" + " _wav_info = _player.play_process(_audio_rx)\n" + " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" + " _audio_rx.set_sample_rate(_wav_info[1])\n" + " _audio_play_state = 0\n" + "\n" + " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" + " fm.register(35,fm.fpioa.I2S1_SCLK)\n" + " fm.register(33,fm.fpioa.I2S1_WS)\n" + "\n" + " while True:\n" + " _audio_play_state = _player.play()\n" + " if (_audio_play_state) == True:\n" + " print(\"Playing.\")\n" + " elif (_audio_play_state) == False:\n" + " print(\"Done.\")\n" + " break\n" + "\n" + " except:\n" + " pass\n" + "\n"; // Blockly.Python.definitions_.import_audio = _in; Blockly.Python.addVariable('_audio_play_state', _in, true); // Blockly.Python.addSetup("ai_audio_read", _in); var _code = "_speaker_play_song(path=" + value_name + ", volume=" + number_play_vol + ")\n"; return _code; }; Blockly.Blocks['ai_audio_play_finish_speaker'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_end_play); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_play_finish_speaker_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_finish_speaker'] = function (block) { // TODO: Assemble Python into code variable. var code = '_player.finish()\n'; return code; }; Blockly.Blocks['ai_audio_set_speaker'] = { init: function () { this.appendValueInput("Num") .setCheck(null) .appendField(Blockly.Msg.ai_audio_set_music_vol); this.setInputsInline(true); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_set_speaker_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_audio_set_speaker = function (block) { var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC); var _code = "_player.volume(" + _num + ")\n" return _code; } Blockly.Blocks['ai_audio_files_list'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_files_list); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.ai_audio_files_list_set_file_path); this.setOutput(true, null); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_files_list_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_audio_files_list = function (block) { var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_.import_ai_audio_files_list = '' + 'def getRawFileList(path):\n' + ' files = []\n' + ' for f in os.listdir(path):\n' + ' if (not f.endswith("~") or not f == "") and f.split(".")[1] == "wav":\n' + ' files.append(path + "/" + f)\n' + ' return files\n' + '\n'; var code = 'getRawFileList(' + value_name + ')'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_audio_play_song_list_loop_speaker'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_play_music_file_list_loop); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol) // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol"); this.appendValueInput("volume") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol); // this.appendValueInput("path") // .setCheck(null) // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path); this.appendValueInput("my_list") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list); this.appendValueInput("firstIndex") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_play_song_speaker_list_loop_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_song_list_loop_speaker'] = function (block) { // var number_play_vol = block.getFieldValue('play_vol'); var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC); // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC); var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC); var _in = "" + "_audio_rx = I2S(I2S.DEVICE_1)\n" + "direction = 0\n" + "firstIndex = " + firstIndex + "\n" + "\n" + "# 上一首\n" + "def previous_song(index,my_list):\n" + " global direction\n" + " index = index - 1\n" + " direction = 1\n" + " if index == -1:\n" + " index = len(my_list) - 1\n" + " return index\n" + "\n" + "# 切换上一首\n" + "def change_previous_song(index):\n" + " global _audio_play_state,direction,firstIndex,_player\n" + " _player.finish()\n" + " _audio_play_state = 0\n" + " firstIndex = index\n" + " direction = 1\n" + "\n" + "# 下一首\n" + "def next_song(index,my_list):\n" + " global direction\n" + " index = index + 1\n" + " direction = 2\n" + " if index == len(my_list):\n" + " index = 0\n" + " return index\n" + "\n" + "# 切换下一首\n" + "def change_next_song(index):\n" + " global _audio_play_state,direction,firstIndex,_player\n" + " _player.finish()\n" + " _audio_play_state = 0\n" + " firstIndex = index\n" + " direction = 2\n" + "\n" + "def _speaker_play_song_list_loop(volume, my_list):\n" + " global _audio_play_state,_player,firstIndex,play_again,direction\n" + " _player = audio.Audio(path = my_list[firstIndex])\n" + " _player.volume(volume)\n" + " try:\n" + // " firstIndex = index\n" + " _wav_info = _player.play_process(_audio_rx)\n" + " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" + " _audio_rx.set_sample_rate(_wav_info[1])\n" + " _audio_play_state = 0\n" + "\n" + " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" + " fm.register(35,fm.fpioa.I2S1_SCLK)\n" + " fm.register(33,fm.fpioa.I2S1_WS)\n" + "\n" + " button_a_state = False\n" + " button_b_state = False\n" + " while True:\n" + " _audio_play_state = _player.play()\n" + " if (_audio_play_state) == True:\n" + " #print(\"Playing.\")\n" + " if (_gp_side_a.value() == 1) and button_a_state == False:\n" + " index = previous_song(firstIndex,my_list)\n" + " button_a_state = True\n" + " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" + " button_a_state = False\n" + " change_previous_song(index)\n" + " break\n" + " if (_gp_side_b.value() == 1) and button_b_state == False:\n" + " index = next_song(firstIndex,my_list)\n" + " button_b_state = True\n" + " elif (_gp_side_b.value() == 0) and button_b_state == True:\n" + " button_b_state = False\n" + " change_next_song(index)\n" + " break\n" + "\n" + " elif (_audio_play_state) == False:\n" + " #print(\"Done.\")\n" + " index = firstIndex + 1\n" + " if index == len(my_list):\n" + " index = 0\n" + " firstIndex = index\n" + " break\n" + "\n" + " except:\n" + " play_again = True\n" + " if direction == 0:\n" + " direction = 3\n" + " return\n" + "\n"; // Blockly.Python.definitions_.import_audio = _in; Blockly.Python.addVariable('_audio_play_list_loop_state', _in, true); Blockly.Python.definitions_['import_define_x_ai_button'] = '' + 'from fpioa_manager import *\n' + 'from Maix import FPIOA, GPIO\n' + '\n' + '_gp_side_buttons = [9, 10, 11]\n' + '\n' + 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' + 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' + 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' + '\n' + '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' + '\n'; // Blockly.Python.addSetup("ai_audio_read", _in); var _code = "_speaker_play_song_list_loop(volume=" + number_play_vol + ", my_list=" + my_list + ")\n"; return _code; }; Blockly.Blocks['ai_audio_play_song_list_random_speaker'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_audio_play_music_file_list_random); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol) // .appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol"); this.appendValueInput("volume") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_vol); // this.appendValueInput("path") // .setCheck(null) // .appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path); this.appendValueInput("my_list") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_files_list); this.appendValueInput("firstIndex") .setCheck(null) .appendField(Blockly.Msg.ai_audio_play_music_file_set_first_index); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#5f7fc1"); this.setTooltip(Blockly.Msg.ai_audio_play_music_file_list_random_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_audio_play_song_list_random_speaker'] = function (block) { // var number_play_vol = block.getFieldValue('play_vol'); var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC); // var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var my_list = Blockly.Python.valueToCode(block, 'my_list', Blockly.Python.ORDER_ATOMIC); var firstIndex = Blockly.Python.valueToCode(block, 'firstIndex', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_random'] = `import random` var _in = "" + "random.seed(time.ticks_cpu())\n" + "\n" + "_audio_rx = I2S(I2S.DEVICE_1)\n" + "firstIndex = " + firstIndex + "\n" + "\n" + "# 随机一首\n" + "def random_song(index,my_list):\n" + " index = random.randrange(0, len(my_list), 1)\n" + " return index\n" + "\n" + "# 切换歌曲\n" + "def change_random_song(index):\n" + " global _audio_play_state,firstIndex,_player\n" + " _player.finish()\n" + " _audio_play_state = 0\n" + " firstIndex = index\n" + "\n" + "def _speaker_play_song_list_random(volume, my_list):\n" + " global _audio_play_state,_player,firstIndex,play_again\n" + " _player = audio.Audio(path = my_list[firstIndex])\n" + " _player.volume(volume)\n" + " try:\n" + // " firstIndex = index\n" + " _wav_info = _player.play_process(_audio_rx)\n" + " _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" + " _audio_rx.set_sample_rate(_wav_info[1])\n" + " _audio_play_state = 0\n" + "\n" + " fm.register(34,fm.fpioa.I2S1_OUT_D1)\n" + " fm.register(35,fm.fpioa.I2S1_SCLK)\n" + " fm.register(33,fm.fpioa.I2S1_WS)\n" + "\n" + " button_a_state = False\n" + " while True:\n" + " _audio_play_state = _player.play()\n" + " if (_audio_play_state) == True:\n" + " #print(\"Playing.\")\n" + " if (_gp_side_a.value() == 1) and button_a_state == False:\n" + " index = random_song(firstIndex,my_list)\n" + " button_a_state = True\n" + " elif (_gp_side_a.value() == 0) and button_a_state == True:\n" + " button_a_state = False\n" + " change_random_song(index)\n" + " break\n" + "\n" + " elif (_audio_play_state) == False:\n" + " #print(\"Done.\")\n" + " index = random_song(firstIndex,my_list)\n" + " firstIndex = index\n" + " break\n" + "\n" + " except:\n" + " play_again = True\n" + " return\n" + "\n"; // Blockly.Python.definitions_.import_audio = _in; Blockly.Python.addVariable('_audio_play_list_random_state', _in, true); Blockly.Python.definitions_['import_define_x_ai_button'] = '' + 'from fpioa_manager import *\n' + 'from Maix import FPIOA, GPIO\n' + '\n' + '_gp_side_buttons = [9, 10, 11]\n' + '\n' + 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' + 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' + 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' + '\n' + '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' + '\n'; // Blockly.Python.addSetup("ai_audio_read", _in); var _code = "_speaker_play_song_list_random(volume=" + number_play_vol + ", my_list=" + my_list + ")\n"; return _code; }; /* _ ___ __ ___ _ / \ |_ _| \ \ / (_) __| | ___ ___ / _ \ | | \ \ / /| |/ _` |/ _ \/ _ \ / ___ \ | | \ V / | | (_| | __/ (_) | /_/ \_\___| \_/ |_|\__,_|\___|\___/ */ Blockly.Blocks['ai_video_record_setup'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_video_start_recording); this.appendValueInput("save_path") .setCheck(null) .appendField(Blockly.Msg.ai_video_start_recording_file_path); this.appendValueInput("w") .setCheck(null) .appendField(Blockly.Msg.ai_video_start_recording_width); this.appendValueInput("h") .setCheck(null) .appendField(Blockly.Msg.ai_video_start_recording_height); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_video_record_setup'] = function (block) { var value_save_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC); var value_w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC); var value_h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_.import_video = "import video"; Blockly.Python.definitions_.import_Maix = "from Maix import GPIO"; Blockly.Python.addVariable('record_vid', 'record_vid = None', true); // TODO: Assemble Python into code variable. var code = "_record_vid = video.open(" + value_save_path + ", record=1, width=" + value_w + ", height=" + value_h + ", interval=20000, quality=80)\n"; return code; }; Blockly.Blocks['ai_video_get'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_to_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.ai_video_record); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_video_get = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var _code = "_record_vid.record(" + variable_name + ")\n" return _code; } Blockly.Blocks['ai_video_stop'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_stop_recording); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#60c1bb"); this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_video_stop = function (block) { var _code = "_record_vid.record_finish()\n" return _code; } Blockly.Blocks['ai_video_set_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_video_set_play_init); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_set_play_init); this.setHelpUrl(""); } } Blockly.Python['ai_video_set_init'] = function (block) { Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_av'] = `import av` Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display` Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera` Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image` // Blockly.Python.addVariable("VIDEOPLAY",`VIDEOPLAY = False`,true) let code = `` return code; } Blockly.Blocks['ai_video_set'] = { init: function () { // this.appendDummyInput() // .appendField(Blockly.Msg.ai_video_play_video); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.ai_video_play_video_file_path); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_video_play_video_2); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_play_video); this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi"); } }; Blockly.Python['ai_video_set'] = function (block) { // Blockly.Python.definitions_.import_Maix = "from maix import display, camera, image"; var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); var code = `pathToVideo = ${value_path} containerVideo = av.open(pathToVideo) streamVideo = containerVideo.streams.video[0] ` return code; }; Blockly.Blocks['ai_video_set_stats'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_set_play_stats); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_video_play_video_2); this.setOutput(true, null) this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_set_play_stats); this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi"); } }; Blockly.Python['ai_video_set_stats'] = function (block) { var code = `containerVideo.decode(video=0)` return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_video_set_play'] = { init: function () { this.appendDummyInput().appendField(Blockly.Msg.ai_models_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_video_set_play); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_set_play); this.setHelpUrl(""); } } Blockly.Python['ai_video_set_play'] = function (block) { var value = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); let code = `if "Video" in repr(${value}): VideoImg = image.load(bytes(${value}.to_rgb().planes[0]), (streamVideo.width, streamVideo.height)) display.show(VideoImg) ` return code; } Blockly.Blocks['ai_video_stop_play'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_stop_video_playing); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_stop_play_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_video_stop_play'] = function (block) { // TODO: Assemble Python into code variable. var code = `break `; return code; }; Blockly.Blocks['ai_video_record_init'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_video_start_recording); this.appendValueInput("save_path") .setCheck(null) .appendField(Blockly.Msg.ai_video_start_recording_file_path); this.appendValueInput("w") .setCheck(null) .appendField(Blockly.Msg.ai_video_start_recording_width); this.appendValueInput("h") .setCheck(null) .appendField(Blockly.Msg.ai_video_start_recording_height); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_record_setup_TOOLTIP); // this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi"); } }; Blockly.Python['ai_video_record_init'] = function (block) { Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_av'] = `import av` Blockly.Python.definitions_['v831_import_from_maix_display'] = `from maix import display` Blockly.Python.definitions_['v831_import_from_maix_camera'] = `from maix import camera` Blockly.Python.definitions_['v831_import_from_maix_image'] = `from maix import image` var value_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC); var w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC); var h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC); var code = `path_to_video = ${value_path} fps = 10 container = av.open(path_to_video, mode='w') stream = container.add_stream('h264', rate=fps) # h264 or mpeg4 stream.width = ${w} stream.height = ${h} stream.pix_fmt = 'yuv420p' ` return code; }; Blockly.Blocks['ai_video_record_get'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_to_canvas) .appendField(new Blockly.FieldVariable("canvas"), "varitem") .appendField(Blockly.Msg.ai_video_record); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_get_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_video_record_get = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var _code = `frame = av.VideoFrame(${variable_name}.width, ${variable_name}.height, 'rgb24') frame.planes[0].update(${variable_name}.tobytes()) for packet in stream.encode(frame): container.mux(packet) ` return _code; } Blockly.Blocks['ai_video_record_stop'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_stop_recording); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_stop_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_video_record_stop = function (block) { var _code = ` #Flush stream for packet in stream.encode(): container.mux(packet) #Close the file container.close() ` return _code; } // 视频录制 Blockly.Blocks['ai_video_record'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_video_recording_and_save); this.appendValueInput("path") .setCheck(null) .appendField(Blockly.Msg.VIDEO_SET_P); this.appendDummyInput() .appendField(Blockly.Msg.ai_video_play_video_2); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_set_TOOLTIP); this.setHelpUrl("https://cn.maixpy.sipeed.com/maixpy/zh/api_reference/media/video.html#1-avi"); } }; Blockly.Python['ai_video_record'] = function (block) { var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_pyaudio'] = `import pyaudio` Blockly.Python.definitions_['v831_import_av'] = `import av` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_from_maix_display'] = `import display` Blockly.Python.definitions_['v831_import_from_maix_camera'] = `import camera` Blockly.Python.definitions_['v831_import_from_maix_image'] = `import image` var code = `path_to_video = ${value_path}; duration, fps = 4, 10 total_frames = duration * fps container = av.open(path_to_video, mode='w') stream = container.add_stream('h264', rate=fps) # h264 or mpeg4 stream.width = 320 stream.height = 240 stream.pix_fmt = 'yuv420p' for frame_i in range(total_frames): img = image.new(size=(stream.width, stream.height), mode='RGB') img.draw_string(0, 0, str(time.time()), 2) frame = av.VideoFrame(img.width, img.height, 'rgb24') frame.planes[0].update(img.tobytes()) for packet in stream.encode(frame): container.mux(packet) #Flush stream for packet in stream.encode(): container.mux(packet) #Close the file container.close() #Play the video container = av.open(path_to_video) stream = container.streams.video[0] for frame in container.decode(video=0): if 'Video' in repr(frame): img = image.load(bytes(frame.to_rgb().planes[0]), (stream.width, stream.height)) display.show(img)` return code; }; Blockly.Blocks['ai_video_status'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_video_get_video_playing_status); this.setOutput(true, null); this.setColour("#4d9994"); this.setTooltip(Blockly.Msg.ai_video_status_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_video_status = function (block) { var code = "_video_play.play()"; return [code, Blockly.Python.ORDER_NONE]; } /* _ ___ __ __ _ _ / \ |_ _| | \/ | ___ __| | ___| |___ / _ \ | | | |\/| |/ _ \ / _` |/ _ \ / __| / ___ \ | | | | | | (_) | (_| | __/ \__ \ /_/ \_\___| |_| |_|\___/ \__,_|\___|_|___/ */ Blockly.Blocks['ai_model_allinit'] = { init: function () { // let types = getLocalStorage("isQiehuan"); // if (!types) { // saveLocalStorage("isQiehuan", 0); // } this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"], [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"], [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"] ]), "DEGREE"); this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"], [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"], [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"] ]), "interface") // this.appendDummyInput() // .appendField(Blockly.Msg.ai_camera_camera_fit_set1) // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem"); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Single Digit Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model), 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model), 'Human Face Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_allinit = function (block) { Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; var degee = block.getFieldValue('DEGREE'); var _code = ""; if (degee == "Single Digit Recognition") { Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true); } else if (degee == "Common Object Recognition") { var language = localStorage.getItem("handPyLanguage"); Blockly.Python.addVariable('task_objectrecognition', 'task_objectrecognition = None', true); if (language == "en") { _code = '' + 'classes_objectrecognition = [\'aeroplane\', \'bicycle\', \'bird\', \'boat\', \'bottle\', \'bus\', \'car\', \'cat\', \'chair\', \'cow\', \'diningtable\', \'dog\', \'horse\', \'motorbike\', \'person\', \'pottedplant\', \'sheep\', \'sofa\', \'train\', \'tvmonitor\']\n' + 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' + 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' + 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' + ''; } else if (language == "zh-hans") { _code = '' + 'classes_objectrecognition = [\'飞机\', \'自行车\', \'鸟\', \'船\', \'瓶子\', \'公共汽车\', \'汽车\', \'猫\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'马\', \'摩托车\', \'人\', \'盆栽\', \'羊\', \'沙发\', \'火车\', \'电视监视器\']\n' + 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' + 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' + 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' + ''; } else { _code = '' + 'classes_objectrecognition = [\'飛機\', \'自行車\', \'鳥\', \'船\', \'瓶子\', \'公共汽車\', \'汽車\', \'貓\', \'椅子\', \'牛\', \'餐桌\', \'狗\', \'馬\', \'摩托車\', \'人\', \'盆栽\', \'羊\', \'沙發\', \'火車\', \'電視監視器\']\n' + 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' + 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' + 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' + ''; } } else { Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true); _code = "" + "task_facerecognition = kpu.load(\"/sd/preset/models/preset/face-recognition.kmodel\")\n" + "anchor_face = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n" + "a = kpu.init_yolo2(task_facerecognition, 0.5, 0.3, 5, anchor_face)\n" + "\n"; } return _code; } // 边缘检测 Blockly.Blocks['ai_model_edge_init'] = { init: function () { // let types = getLocalStorage("isQiehuan"); // if (!types) { // saveLocalStorage("isQiehuan", 0); // } this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(Blockly.Msg.ai_models_edge_detection_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_edge_detection_model); this.setHelpUrl(''); } }; Blockly.Python.ai_model_edge_init = function (block) { Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np` Blockly.Python.definitions_.import_KPU = ` class Edge: model = { "param": "/root/preset/model/sobel_int8.param", "bin": "/root/preset/model/sobel_int8.bin" } input_size = (224, 224, 3) output_size = (222, 222, 3) options = { "model_type": "awnn", "inputs": { "input0": input_size }, "outputs": { "output0": output_size }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } def __init__(self): from maix import nn print("-- load model:", self.model) self.model = nn.load(self.model, opt=self.options) print("-- load ok") def __del__(self): del self.model m = Edge()`; // var degee = block.getFieldValue('DEGREE'); var _code = ""; return _code; } // 加载边缘检测模型 Blockly.Blocks['ai_model_edge_loading'] = { init: function () { // let types = getLocalStorage("isQiehuan"); // if (!types) { // saveLocalStorage("isQiehuan", 0); // } this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_edge_detection_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_edgedetection"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); // var thisBlock = this; this.setTooltip(Blockly.Msg.ai_models_load_edge_detection_model); this.setHelpUrl(''); } }; Blockly.Python.ai_model_edge_loading = function (block) { // var degee = block.getFieldValue('varitem'); Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np` Blockly.Python.definitions_.import_KPU = ` class Edge: model = { "param": "/root/preset/model/sobel_int8.param", "bin": "/root/preset/model/sobel_int8.bin" } input_size = (224, 224, 3) output_size = (222, 222, 3) options = { "model_type": "awnn", "inputs": { "input0": input_size }, "outputs": { "output0": output_size }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } def __init__(self): from maix import nn print("-- load model:", self.model) self.model = nn.load(self.model, opt=self.options) print("-- load ok") def __del__(self): del self.model m = Edge()`; // ${degee} = camera.capture().resize(224,224) var _code = `canvas = canvas.resize(224, 224, padding = 0) out = m.model.forward(canvas, quantize=True, layout="hwc") out = out.astype(np.float32).reshape(m.output_size) out = (np.ndarray.__abs__(out) * 255 / out.max()).astype(np.uint8) data = out.tobytes() canvas = canvas.load(data,(222, 222), mode="RGB") `; return _code; } // 获取边缘测试模型结果 Blockly.Blocks['ai_model_edge_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_get_edge_detection_result); this.setOutput(true, null); // this.setNextStatement(true, null); this.setColour("#ee783a"); // var thisBlock = this; this.setTooltip(Blockly.Msg.ai_models_get_edge_detection_result); this.setHelpUrl(''); } }; Blockly.Python.ai_model_edge_result = function (block) { var degee = block.getFieldValue('varitem'); var _code = "edgeModel"; return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_allload'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"], [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"], [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"] ]), "DEGREE"); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_camera_camera_fit_set1) // .appendField(new Blockly.FieldVariable("img_mnist"), "camera_varitem"); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_source) .appendField(new Blockly.FieldVariable("img_mnist"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model), 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model), 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_allload = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; var degee = block.getFieldValue('DEGREE'); var _code = "" if (degee == "Single Digit Recognition") { // Blockly.Python.addVariable('img_mnist_resized', '', true); _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n"; _code += "img_mnist_resized=img_mnist1.resize(28,28)\n"; _code += "a=img_mnist_resized.invert()\n"; _code += "a=img_mnist_resized.strech_char(1)\n"; _code += "a=img_mnist_resized.pix_to_ai()\n"; _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n"; _code += "plist_mnist=fmap_mnist[:]\n"; _code += "pmax_mnist=max(plist_mnist)\n"; _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n"; } else if (degee == "Common Object Recognition") { // Blockly.Python.addVariable('code_objectrecognition', '', true); _code += "code_objectrecognition = kpu.run_yolo2(task_objectrecognition, " + variable_name + ")\n"; _code += variable_name + ".ai_to_pix()\n"; } else { // Blockly.Python.addVariable('code_facerecognition', '', true); _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n"; _code += variable_name + ".ai_to_pix()\n"; } return _code; } Blockly.Blocks['ai_model_index_init'] = { init: function () { this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_models_init_title) // .appendField("DEGREE"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_init_title); this.setHelpUrl(''); } }; Blockly.Python.ai_model_index_init = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; console.log('value_class_input', value_class_input) var _code = value_class_input; // Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true); return _code; } // 手写数字识别 Blockly.Blocks['ai_model_look_written_model'] = { init: function () { // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_title) // .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"] // ]), "DEGREE"); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_hand_written_model); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model); this.setHelpUrl(""); } }; Blockly.Python.ai_model_look_written_model = function (block) { // Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n"; return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_look_written_model_old'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_init_hand_written_model, "Human Face Recognition"] ]), "DEGREE"); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_hand_written_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model); this.setHelpUrl(""); } }; Blockly.Python.ai_model_look_written_model_old = function (block) { Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; var _code = "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n"; return _code; } Blockly.Blocks['ai_model_index_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"] ]), "DEGREE"); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_source) .appendField(new Blockly.FieldVariable("img_mnist"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_index_load = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; var degee = block.getFieldValue('DEGREE'); var _code = "" if (degee == "Single Digit Recognition") { // Blockly.Python.addVariable('img_mnist_resized', '', true); _code += "img_mnist1=" + variable_name + ".to_grayscale(1)\n"; _code += "img_mnist_resized=img_mnist1.resize(28,28)\n"; _code += "a=img_mnist_resized.invert()\n"; _code += "a=img_mnist_resized.strech_char(1)\n"; _code += "a=img_mnist_resized.pix_to_ai()\n"; _code += "fmap_mnist=kpu.forward(task_mnist, img_mnist_resized)\n"; _code += "plist_mnist=fmap_mnist[:]\n"; _code += "pmax_mnist=max(plist_mnist)\n"; _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n"; } return _code; } Blockly.Blocks['ai_model_index_mnist'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_hand_written_model_result); this.appendDummyInput() .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_hand_written_model_number, "c"], [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"] ]), "value"); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_index_mnist_TOOLTIP); this.setHelpUrl(''); } }; Blockly.Python.ai_model_index_mnist = function (block) { var value = block.getFieldValue('value'); var _code = "max_index_mnist"; if (value == "confidence") { _code = "int(pmax_mnist*100)"; } return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_digital_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(Blockly.Msg.ai_models_init_hand_written_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_hand_written_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_hand_written_model); this.setHelpUrl(""); } }; Blockly.Python.ai_model_digital_init = function (block) { // Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` var _code = ` class Number_recognition: mdsc_path = "/root/preset/model/Number.mud" labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38] def __init__(self): self.model = nn.load(self.mdsc_path) self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7)) def __del__(self): del self.model del self.decoder def cal_fps(self ,start , end): one_second = 1 one_flash = end - start fps = one_second / one_flash return fps number_recognition = Number_recognition() `; return _code; } Blockly.Blocks['ai_model_digital_init_loding'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_hand_written_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_mnist"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Single Digit Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_hand_written_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_digital_init_loding = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE); Blockly.Python.definitions_.import_KPU = ``; Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.definitions_['v831_import_from_Number_recognition'] = ` class Number_recognition: mdsc_path = "/root/preset/model/Number.mud" labels = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] anchors = [1.0, 5.0, 1.35, 5.42, 0.49, 2.55, 0.86, 3.75, 0.65, 4.38] def __init__(self): self.model = nn.load(self.mdsc_path) self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7)) self.NumberRecognition = [] def __del__(self): del self.model del self.decoder def cal_fps(self ,start , end): one_second = 1 one_flash = end - start fps = one_second / one_flash return fps def digitalShowCanvas(self,canvas): out = number_recognition.model.forward(canvas, quantize=1, layout = "hwc") BOXES, PROBS = number_recognition.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224)) if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string(0,0, (str(number_recognition.labels[PROBS[BOXESI][0]]) + str(str(":") + str(round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1) canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) BOXES[BOXESI].append(PROBS[BOXESI]) #self.NumberRecognition = BOXES else: BOXES = [] return BOXES number_recognition = Number_recognition() `; var _code = `canvas = canvas.crop(48,8,224,224) BOXES = number_recognition.digitalShowCanvas(canvas) ` return _code; } // ai_model_digital_new Blockly.Blocks['ai_model_digital_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_digital_new_text) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_model_digital_new_text); this.setHelpUrl(""); } }; Blockly.Python.ai_model_digital_new = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("digitalStatements", `def digitalStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if (len(BOXES)): for BOXESI in BOXES: digitalStatements(BOXESI) else: ${statements_input1} ` return code; } Blockly.Blocks['ai_model_digital_result'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_from) // .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_models_hand_written_model_result); this.appendDummyInput() .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_hand_written_model_number, "c"], [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"], [Blockly.Msg.ai_models_object_model_x, "X"], [Blockly.Msg.ai_models_object_model_y, "Y"], [Blockly.Msg.ai_models_object_model_w, "W"], [Blockly.Msg.ai_models_object_model_h, "H"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"] ]), "value"); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_hand_written_model_result); this.setHelpUrl(''); } }; Blockly.Python.ai_model_digital_result = function (block) { var value = "BOXESI" var type = block.getFieldValue('value'); // var _code = `"{}:{:.2f}%".format(number_recognition.labels[probs[${value}][0]], probs[${value}][1][probs[${value}][0]]*100)`; if (type == "confidence") { _code = `${value}[4][1][${value}[4][0]]*100`; } else if (type == "X") { _code = `${value}[0]`; } else if (type == "Y") { _code = `${value}[1]`; } else if (type == "W") { _code = `int(${value}[0] + ${value}[2])`; } else if (type == "H") { _code = `int(${value}[1] + ${value}[3])`; } else if (type == "c") { _code = `number_recognition.labels[${value}[4][0]]`; } else if (type == "CX") { _code = `int((${value}[0] +${value}[0] + ${value}[2])/2)`; } else if (type == "CY") { _code = `int((${value}[1] + ${value}[1] + ${value}[3])/2)`; } else { _code = `${value}[${type}]`; } return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_digital'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_digital); // this.appendDummyInput() // .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.ai_models_hand_written_model_number, "digitalResult"], // [Blockly.Msg.ai_models_hand_written_model_confidence, "digitalConfidence"], // ["检测框", "digitalCheckout"] // ]), "digital"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(); this.setHelpUrl(""); } }; Blockly.Python.ai_model_digital = function (block) { Blockly.Python.addVariable("getDigitalResult", `getDigitalResult = []`) Blockly.Python.addFunction("digitalShowCanvas", `def digitalShowCanvas(): global BOXES,getDigitalResult getDigitalResult = [] if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string(0,0, (str(number_recognition.labels[PROBS[BOXESI][0]]) + str(str(":") + str(round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1) canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) getDigitalResult.append({"digitalResult":number_recognition.labels[PROBS[BOXESI][0]],"digitalConfidence":round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)}) `) var _code = "digitalShowCanvas()\n"; return _code; } Blockly.Blocks['ai_model_digital_attribute'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_digital_attribute); this.setOutput(false, null); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_digital_attribute); this.setHelpUrl(""); } }; Blockly.Python['ai_model_digital_attribute'] = function (block) { Blockly.Python.addFunction("", `def ai_model_digital_attribute():`) var code = 'len(BOXES)'; return code; }; Blockly.Blocks['ai_model_object_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(Blockly.Msg.ai_models_init_object_model); // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"], // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"], // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"] // ]), "interface") // this.appendValueInput("class_input") // .setCheck(null) // .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_object_init = function (block) { var language = localStorage.getItem("handPyLanguage"); let a = '' if (language == "en") { a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]' } else if (language == "zh-hans") { a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]' } else { a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]' } console.log(language) Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.definitions_.import_object = ` model = { "param": "/root/preset/model/yolo2_20class_awnn.param", "bin": "/root/preset/model/yolo2_20class_awnn.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "output0": (7, 7, (1+4+20)*5) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } labels = ${a} anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8] m = nn.load(model, opt=options) yolo2_decoder = decoder.Yolo2(len(labels), anchors, net_in_size=(options["inputs"]["input0"][0], options["inputs"]["input0"][1]), net_out_size=(7, 7)) `; var _code = ""; return _code; } Blockly.Blocks['ai_model_object_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(Blockly.Msg.ai_models_init_object_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_objectrecognition"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_object_load = function (block) { // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var degee = block.getFieldValue('DEGREE'); var language = localStorage.getItem("handPyLanguage"); let a = '' if (language == "en") { a = '["aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"]' } else if (language == "zh-hans") { a = '["飞机", "自行车", "鸟", "船", "瓶子", "公共汽车", "汽车", "猫", "椅子", "牛", "餐桌", "狗", "马", "摩托车", "人", "盆栽", "羊", "沙发", "火车", "电视监视器"]' } else { a = '["飛機", "自行車", "鳥", "船", "瓶子", "公共汽車", "汽車", "貓", "椅子", "牛", "餐桌", "狗", "馬", "摩托車", "人", "盆栽", "羊", "沙發", "火車", "電視監視器"]' } Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.definitions_.import_object = `class ObjectRecognition: def __init__(self): model = { "param": "/root/preset/model/yolo2_20class_awnn.param", "bin": "/root/preset/model/yolo2_20class_awnn.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "output0": (7, 7, (1+4+20)*5) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } self.labels = ${a} anchors = [5.4, 5.38, 1.65, 2.09, 0.8, 1.83, 2.45, 4.14, 0.46, 0.8] self.m = nn.load(model, opt=options) self.yolo2_decoder = decoder.Yolo2(len(self.labels), anchors, net_in_size=(224,224), net_out_size=(7, 7)) self.OBJECTS = { "OBJECT_START_X": [], "OBJECT_START_Y": [], "OBJECT_CONFIDENCE": [], "OBJECT_WIDTH": [], "OBJECT_HEIGHT": [], "OBJECT_CENTER_X": [], "OBJECT_CENTER_Y": [], "OBJECT_RESULT": [], } def objectRecognize(self, canvas): self.OBJECTS = { "OBJECT_START_X": [], "OBJECT_START_Y": [], "OBJECT_CONFIDENCE": [], "OBJECT_WIDTH": [], "OBJECT_HEIGHT": [], "OBJECT_CENTER_X": [], "OBJECT_CENTER_Y": [], "OBJECT_RESULT": [], } out = self.m.forward(canvas.tobytes(), quantize=True, layout="hwc") BOXES, PROBS = self.yolo2_decoder.run(out, nms=0.3, threshold=0.3, img_size=(224,224)) if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string(BOXOBJ[0],(BOXOBJ[1]), ("".join([str(x) for x in [str(self.labels[PROBS[BOXESI][0]]), ",", round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)]])), scale = 1, color = (51,102,255) , thickness = 1) canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) BOXES[BOXESI].append(PROBS[BOXESI]) else: BOXES = [] return BOXES ObjectRecognition = ObjectRecognition() `; var _code = `canvas = canvas.crop(48,8,224,224) BOXES = ObjectRecognition.objectRecognize(canvas) ` return _code; } // ai_model_look_new Blockly.Blocks['ai_model_look_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_object_model_if) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_models_object_model_if); this.setHelpUrl(""); } }; Blockly.Python.ai_model_look_new = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("modelStatements", `def modelStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if len(BOXES): for BOXESI in BOXES: modelStatements(BOXESI) else: ${statements_input1} ` return code; } Blockly.Blocks['ai_model_get'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(Blockly.Msg.ai_models_object_model_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_object_model_name, "Object"], [Blockly.Msg.ai_models_object_model_x, "X"], [Blockly.Msg.ai_models_object_model_y, "Y"], // [Blockly.Msg.ai_models_object_model_w, "W"], // [Blockly.Msg.ai_models_object_model_h, "H"], // [Blockly.Msg.ai_models_object_model_x_center, "CX"], // [Blockly.Msg.ai_models_object_model_y_center, "CY"], // [Blockly.Msg.ai_models_object_model_count, "Number"], // [Blockly.Msg.ai_models_object_model_index, "Serial"], [Blockly.Msg.ai_models_object_model_confidence, "Confidence"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"] ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('TYPE'); var TOOLTIPS = { 'Object': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_name), 'X': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x), 'Y': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y), 'W': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_w), 'H': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_h), // 'CX': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_x_center), // 'CY': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_y_center), // 'Number': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_count), // 'Serial': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_index), // 'Confidence': Blockly.Msg.ai_model_get_TOOLTIP.replace('%1', Blockly.Msg.ai_models_object_model_confidence) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python.ai_model_get = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = "BOXESI"; var _code = ""; if (type == "Object") { _code = `labels[${variable_name}[4][0]]` // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)` } else if (type == "X") { _code = '' + variable_name + '[0]'; } else if (type == "Y") { _code = '' + variable_name + '[1]'; } else if (type == "W") { _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])'; } else if (type == "H") { _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])'; } else if (type == "Confidence") { _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`; } else if (type == "CX") { _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`; } else if (type == "CY") { _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`; } else { _code = `${variable_name}[${type}]`; } return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_look'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_object_model_if); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_look_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_model_look = function (block) { var _code = "len(boxes)"; return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_look_attribute'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_look_attribute); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_look_attribute); this.setHelpUrl(""); } }; Blockly.Python['ai_model_look_attribute'] = function (block) { Blockly.Python.addFunction("objectRecognize", `def objectRecognize(): global BOXES if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string(BOXOBJ[0],(BOXOBJ[1]), ("".join([str(x) for x in [str(labels[PROBS[BOXESI][0]]), ",", round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)]])), scale = 1, color = (51,102,255) , thickness = 1) canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) `) var code = 'objectRecognize()\n'; return code; }; // 猜拳识别 Blockly.Blocks['ai_model_Guesswork_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(Blockly.Msg.ai_models_init_guesswork_model); // this.appendDummyInput().appendField(Blockly.Msg.ai_model_allinit_language).appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.ai_speech_recognition_setup_set_english, "English"], // [Blockly.Msg.ai_speech_recognition_setup_set_simplified_chinese, "Simplified Chinese"], // [Blockly.Msg.ai_speech_recognition_setup_set_traditional_chinese, "Traditional Chinese"] // ]), "interface") // this.appendValueInput("class_input") // .setCheck(null) // .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Common Object Recognition': Blockly.Msg.ai_model_allinit_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model_title) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_Guesswork_init = function (block) { var language = localStorage.getItem("handPyLanguage"); console.log(language) let a = '' if (language == "en") { a = '["Scissors", "Stone" ,"Paper"]' } else if (language == "zh-hans") { a = '["剪刀", "石头" ,"布"]' } else { a = '["剪刀", "石頭" ,"布"]' } Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.definitions_.import_Guesswork_init = `class Mora: mud_path = "/root/preset/model/mora_int8.mud" labels = ${a} anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56] def __init__(self) -> None: from maix import nn self.model = nn.load(self.mud_path) from maix.nn import decoder self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7)) def __del__(self): del self.model del self.decoder def cal_fps(self ,start , end): one_second = 1 one_flash = end - start fps = one_second / one_flash return fps def draw_rectangle_with_title(self ,img, box, disp_str , fps ): img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2) img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2) #img.draw_string(0, 0 ,"FPS :"+str(fps), scale=2 ,color=(0, 0, 255), thickness=2) def process(self,input): t = time() out = self.model.forward(input, quantize=1, layout = "hwc") boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224)) for i, box in enumerate(boxes): class_id = probs[i][0] prob = probs[i][1][class_id] disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100) fps = self.cal_fps(t, time()) self.draw_rectangle_with_title(input, box, disp_str, fps) Mora = Mora() `; var _code = ""; return _code; } Blockly.Blocks['ai_model_Guesswork_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(Blockly.Msg.ai_models_init_guesswork_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_guessworkrecognition"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Common Object Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_object_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_Guesswork_load = function (block) { var language = localStorage.getItem("handPyLanguage"); let a = '' if (language == "en") { a = '["Scissors", "Stone" ,"Paper"]' } else if (language == "zh-hans") { a = '["剪刀", "石头" ,"布"]' } else { a = '["剪刀", "石頭" ,"布"]' } Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.definitions_.import_Guesswork_init = `class Mora: mud_path = "/root/preset/model/mora_int8.mud" labels = ${a} anchors = [3.23, 3.25, 1.47, 1.55, 5.09, 5.33, 4.03, 4.28, 2.12, 2.56] def __init__(self) -> None: self.model = nn.load(self.mud_path) self.decoder = decoder.Yolo2(len(self.labels) , self.anchors , net_in_size = (224, 224) ,net_out_size = (7,7)) self.MORAS = { "MORA_START_X": [], "MORA_START_Y": [], "MORA_CONFIDENCE": [], "MORA_WIDTH": [], "MORA_HEIGHT": [], "MORA_CENTER_X": [], "MORA_CENTER_Y": [], "MORA_RESULT": [], } def __del__(self): del self.model del self.decoder def cal_fps(self ,start , end): one_second = 1 one_flash = end - start fps = one_second / one_flash return fps def draw_rectangle_with_title(self ,img, box, disp_str ): img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3],color=(255, 0, 0), thickness=2) img.draw_string(box[0], box[1] ,disp_str, scale=1,color=(222, 0, 3), thickness=2) def process(self,input): out = self.model.forward(input, quantize=1, layout = "hwc") boxes, probs = self.decoder.run(out, nms=0.5, threshold=0.3, img_size=(224,224)) for i, box in enumerate(boxes): class_id = probs[i][0] prob = probs[i][1][class_id] disp_str = "{}:{:.2f}%".format(self.labels[class_id], prob*100) self.draw_rectangle_with_title(input, box, disp_str) boxes[i].append(probs[i]) return boxes Mora = Mora() `; var _code = `canvas = canvas.crop(48,8,224,224) BOXES = Mora.process(canvas) ` return _code; } // ai_model_Guesswork_look_new Blockly.Blocks['ai_model_Guesswork_look_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_guesswork_look_attribute) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute); this.setHelpUrl(""); } }; Blockly.Python.ai_model_Guesswork_look_new = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("GuessworkStatements", `def GuessworkStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if len(BOXES) > 0: for BOXESI in BOXES: GuessworkStatements(BOXESI) else: ${statements_input1} ` return code; } Blockly.Blocks['ai_model_Guesswork_get'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(Blockly.Msg.ai_models_guesswork_model_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_object_model_name, "Object"], [Blockly.Msg.ai_models_object_model_x, "X"], [Blockly.Msg.ai_models_object_model_y, "Y"], // [Blockly.Msg.ai_models_object_model_w, "W"], // [Blockly.Msg.ai_models_object_model_h, "H"], // [Blockly.Msg.ai_models_object_model_x_center, "CX"], // [Blockly.Msg.ai_models_object_model_y_center, "CY"], // [Blockly.Msg.ai_models_object_model_count, "Number"], // [Blockly.Msg.ai_models_object_model_index, "Serial"], [Blockly.Msg.ai_models_object_model_confidence, "Confidence"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"] ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get); this.setHelpUrl(""); } }; Blockly.Python.ai_model_Guesswork_get = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = "BOXESI"; var _code = ""; if (type == "Object") { _code = `Mora.labels[${variable_name}[4][0]]` // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)` } else if (type == "X") { _code = '' + variable_name + '[0]'; } else if (type == "Y") { _code = '' + variable_name + '[1]'; } else if (type == "W") { _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])'; } else if (type == "H") { _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])'; } else if (type == "Confidence") { _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`; } else if (type == "CX") { _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`; } else if (type == "CY") { _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`; } else { _code = `${variable_name}[${type}]`; } return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_Guesswork_look'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_guesswork_model_if); this.setInputsInline(false); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_guesswork_model_if); this.setHelpUrl(""); } }; Blockly.Python.ai_model_Guesswork_look = function (block) { Blockly.Python.addFunction("guessworkShowRecognize", `def guessworkShowRecognize(): global BOXES if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string(10,0, (str(str(Mora.labels[PROBS[BOXESI][0]])) + str(str(":") + str(round(PROBS[BOXESI][1][PROBS[BOXESI][0]]*100, 2)))), scale = 1, color = (255,0,0) , thickness = 1) canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) `) var _code = "guessworkShowRecognize()\n"; return _code; } Blockly.Blocks['ai_model_Guesswork_look_attribute'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_guesswork_look_attribute); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_guesswork_look_attribute); this.setHelpUrl(""); } }; Blockly.Python['ai_model_Guesswork_look_attribute'] = function (block) { var code = 'len(BOXES)'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_face_recognition_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(Blockly.Msg.ai_models_init_face_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_facedetection"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_face_recognition_load = function (block) { Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.definitions_.import_face_recognition = `class YoloFaceRecognize: labels = ["person"] anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65] m = { "param": "/root/preset/model/yolo2_face_awnn.param", "bin": "/root/preset/model/yolo2_face_awnn.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "output0": (7, 7, (1+4+len(labels))*5) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } def __init__(self): self.model = nn.load(self.m, opt=self.options) self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7)) self.FACES = { "FACES_START_X": [], "FACES_START_Y": [], "FACENUM": 0, "FACES_CONFIDENCE": [], "FACES_WIDTH": [], "FACES_HEIGHT": [], "FACES_CENTER_X": [], "FACES_CENTER_Y": [] } def __del__(self): del self.model del self.decoder def faceShowDetection(self,canvas): out = YoloFaceRecognize.model.forward(canvas.tobytes(), quantize=True, layout="hwc") BOXES, PROBS = YoloFaceRecognize.decoder.run(out, nms=0.3, threshold=0.5, img_size=(224, 224)) if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) BOXES[BOXESI].append(PROBS[BOXESI]) def returnFaces(self): return self.FACES YoloFaceRecognize = YoloFaceRecognize() `; var _code = `canvas = canvas.crop(48,8,224,224) BOXES = YoloFaceRecognize.faceShowDetection(canvas)\n` return _code; } Blockly.Blocks['ai_model_xy'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(Blockly.Msg.ai_models_face_model_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_object_model_name, "Object"], [Blockly.Msg.ai_models_face_model_x, "X"], [Blockly.Msg.ai_models_face_model_y, "Y"], // [Blockly.Msg.ai_models_face_model_w, "W"], // [Blockly.Msg.ai_models_face_model_h, "H"], // [Blockly.Msg.ai_models_face_model_x_center, "CX"], // [Blockly.Msg.ai_models_face_model_y_center, "CY"], [Blockly.Msg.ai_models_face_model_count, "Number"], // [Blockly.Msg.ai_models_face_model_index, "Serial"], [Blockly.Msg.ai_models_face_model_confidence, "Confidence"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"] ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('TYPE'); var TOOLTIPS = { 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x), 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y), 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w), 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h), // 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center), // 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center), 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count), // 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index), // 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python.ai_model_xy = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = "BOXESI"; var _code = ""; if (type == "X") { _code = '' + variable_name + '[0]'; } else if (type == "Y") { _code = '' + variable_name + '[1]'; } else if (type == "W") { _code = 'int(' + variable_name + '[0]+' + '' + variable_name + '[2])'; } else if (type == "H") { _code = 'int(' + variable_name + '[1]+' + '' + variable_name + '[3])'; } else if (type == "Confidence") { _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`; } else if (type == "Object") { _code = `"Face"`; } else if (type == "CX") { _code = `int((${variable_name}[0] +${variable_name}[0] + ${variable_name}[2])/2)`; } else if (type == "CY") { _code = `int((${variable_name}[1] + ${variable_name}[1] + ${variable_name}[3])/2)`; } else if (type == "Number") { _code = `len(boxes)`; } else { _code = `${variable_name}[${type}]`; } return [_code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_model_face_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_model_list) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_model_face_model_list); this.setHelpUrl(""); } }; Blockly.Python.ai_model_face_new = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("GuessworkStatements", `def GuessworkStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if len(BOXES) > 0: for BOXESI in BOXES: GuessworkStatements(BOXESI) else: ${statements_input1} ` return code; } Blockly.Blocks['ai_model_face'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_face_model_if); this.setInputsInline(false); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_face_model_if); this.setHelpUrl(""); } }; Blockly.Python.ai_model_face = function (block) { Blockly.Python.addFunction("faceShowDetection", `def faceShowDetection(): global BOXES if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_rectangle(BOXOBJ[0],BOXOBJ[1], BOXOBJ[0]+BOXOBJ[2],BOXOBJ[1]+ BOXOBJ[3], color=(255,0,0), thickness=1) `) var _code = "faceShowDetection()\n"; return _code; } Blockly.Blocks['ai_model_face_attribute'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_model_list); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_model_list); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_attribute'] = function (block) { var code = 'boxes'; return [code, Blockly.Python.ORDER_NONE]; }; // 车牌识别 Blockly.Blocks['ai_model_card_recognition_init'] = { init: function () { // this.appendDummyInput() // .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_title) .appendField(Blockly.Msg.ai_models_init_card_model); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_card_recognition_init'] = function (block) { // TODO: Assemble Python into code variable. Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true) Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR: loc_model_path = "/root/preset/model/loc.mud" reg_model_path = "/root/preset/model/reg.mud" chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "警", "学", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-"] variances = [0.1, 0.2] steps = [8, 16, 32] min_sizes = [12, 24, 48, 96, 192, 320] card_input_img = None def __init__(self) -> None: from maix import nn self.loc_model = nn.load(self.loc_model_path, opt=None) self.reg_model = nn.load(self.reg_model_path, opt=None) from maix.nn import decoder self.loc_decoder = decoder.license_plate_location( [224, 224], self.steps, self.min_sizes, self.variances) self.reg_decoder = decoder.CTC((1, 68, 18)) def __del__(self): del self.loc_model del self.loc_decoder def cal_fps(self, start, end): one_second = 1 one_flash = end - start fps = one_second / one_flash return fps def draw_fps(self, img, fps): img.draw_string(0, 0, "FPS :"+str(fps), scale=1, color=(255, 0, 255), thickness=1) def draw_string(self, img, x, y, string, color): img.draw_string(x, y, string, color=color) def draw_paste(self, src, dst): src.paste(dst, 0, 0) def draw_rectangle(self, img, box): img.draw_rectangle(box[0], box[1], box[2], box[3], color=(230, 230, 250), thickness=2) def draw_point(self, img, landmark): for i in range(4): x = landmark[2 * i] y = landmark[2 * i + 1] img.draw_rectangle(x-2, y-2, x+2, y+2, color=(193, 255, 193), thickness=-1) def process(self, input): global CARDDATABOEX self.card_input_img = input # retinaface decoder only support chw layout loc_out = self.loc_model.forward(input, quantize=1, layout="chw") boxes, landmarks = self.loc_decoder.run(loc_out, nms=0.2, score_thresh=0.7, outputs_shape=[ [1, 4, 2058], [1, 2, 2058], [1, 8, 2058]]) if len(boxes): # print(boxes,landmarks) for boxesi, box in enumerate(boxes): boxes[boxesi].append(landmarks[boxesi]) CARDDATABOEX = boxes def get_card_data(self, landmark): # landmark = i[4][:6] reg_in = self.card_input_img.crop_affine(landmark, 94, 24) reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw") LP_number = self.reg_decoder.run(reg_out) string_LP = "" for id in LP_number: string_LP += self.chars[id] return string_LP LPRCARD = LPR() `; var code = ''; return code; }; // 车牌识别 Blockly.Blocks['ai_model_card_recognition_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(Blockly.Msg.ai_models_init_card_model); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_customized_init_setup_source) // .appendField(new Blockly.FieldVariable("img_card_recognition"), "varitem"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_card_recognition_load'] = function (block) { Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` Blockly.Python.addVariable('CARDDATABOEX', `CARDDATABOEX = ""`, true) Blockly.Python.definitions_['v831_card_recognition_init'] = `class LPR: loc_model_path = "/root/preset/model/loc.mud" reg_model_path = "/root/preset/model/reg.mud" chars = ["皖", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑", "苏", "浙", "京", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "警", "学", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-"] variances = [0.1, 0.2] steps = [8, 16, 32] min_sizes = [12, 24, 48, 96, 192, 320] card_input_img = None def __init__(self) -> None: self.loc_model = nn.load(self.loc_model_path, opt=None) self.reg_model = nn.load(self.reg_model_path, opt=None) self.loc_decoder = decoder.license_plate_location( [224, 224], self.steps, self.min_sizes, self.variances) self.reg_decoder = decoder.CTC((1, 68, 18)) self.LPRS = { "LPR_START_X":[], "LPR_START_Y":[], "LPR_CENTER_X":[], "LPR_CENTER_Y":[], "LPR_WIDTH":[], "LPR_HEIGHT":[], "LPR_CONFIDENCE":[], "LPR_RESULT":[], } def __del__(self): del self.loc_model del self.loc_decoder def cal_fps(self, start, end): one_second = 1 one_flash = end - start fps = one_second / one_flash return fps def draw_fps(self, img, fps): img.draw_string(0, 0, "FPS :"+str(fps), scale=1, color=(255, 0, 255), thickness=1) def draw_string(self, img, x, y, string, color): img.draw_string(x, y, string, color=color) def draw_paste(self, src, dst): src.paste(dst, 0, 0) def draw_rectangle(self, img, box): img.draw_rectangle(box[0], box[1], box[2], box[3], color=(230, 230, 250), thickness=2) def draw_point(self, img, landmark): for i in range(4): x = landmark[2 * i] y = landmark[2 * i + 1] img.draw_rectangle(x-2, y-2, x+2, y+2, color=(193, 255, 193), thickness=-1) def process(self, input): self.card_input_img = input # retinaface decoder only support chw layout loc_out = self.loc_model.forward(input, quantize=1, layout="chw") boxes, landmarks = self.loc_decoder.run(loc_out, nms=0.2, score_thresh=0.7, outputs_shape=[[1, 4, 2058], [1, 2, 2058], [1, 8, 2058]]) self.LPRS = { "LPR_START_X":[], "LPR_START_Y":[], "LPR_CENTER_X":[], "LPR_CENTER_Y":[], "LPR_WIDTH":[], "LPR_HEIGHT":[], "LPR_CONFIDENCE":[], "LPR_RESULT":[], } for i,box in enumerate(boxes): landmark = landmarks[i][:6] reg_in = input.crop_affine(landmark , 94 , 24) reg_out = self.reg_model.forward(reg_in , quantize=1, layout = "chw") LP_number = self.reg_decoder.run(reg_out) string_LP = '' for id in LP_number: string_LP += self.chars[id] # string_LP += str(id) input.draw_string(box[0]+5, box[1]+5, string_LP, color=(225,0,0)) input.draw_rectangle(box[0], box[1], box[2], box[3],color=(250,0,0), thickness=1) boxes[i].append(landmarks[i]) return boxes def get_card_data(self, landmark): # landmark = i[4][:6] reg_in = self.card_input_img.crop_affine(landmark, 94, 24) reg_out = self.reg_model.forward(reg_in, quantize=1, layout="chw") LP_number = self.reg_decoder.run(reg_out) string_LP = "" for id in LP_number: string_LP += self.chars[id] return string_LP LPRCARD = LPR() `; // TODO: Assemble Python into code variable. var code = `canvas = canvas.crop(48,8,224,224) BOXES = LPRCARD.process(canvas) `; return code; }; // 车牌识别 Blockly.Blocks['ai_model_card_xy_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_card_attribute) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_models_card_attribute); this.setHelpUrl(""); } }; Blockly.Python['ai_model_card_xy_new'] = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("cardStatements", `def cardStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if len(BOXES) > 0: for BOXESI in BOXES: cardStatements(BOXESI) else: ${statements_input1} ` return code; }; Blockly.Blocks['ai_model_card_get'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(Blockly.Msg.ai_models_card_model_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_init_card_result, "Object"], [Blockly.Msg.ai_models_object_model_x, "X"], [Blockly.Msg.ai_models_object_model_y, "Y"], [Blockly.Msg.ai_models_object_model_w, "W"], [Blockly.Msg.ai_models_object_model_h, "H"], // [Blockly.Msg.ai_models_object_model_x_center, "CX"], // [Blockly.Msg.ai_models_object_model_y_center, "CY"], // [Blockly.Msg.ai_models_object_model_count, "Number"], // [Blockly.Msg.ai_models_object_model_index, "Serial"], [Blockly.Msg.ai_models_object_model_confidence, "Confidence"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"] ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(Blockly.Msg.ai_models_guesswork_model_get); this.setHelpUrl(""); } }; Blockly.Python.ai_model_card_get = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = "BOXESI"; var _code = ""; if (type == "Object") { _code = `LPRCARD.get_card_data(${variable_name}[4][:6])` // _code = `"{}:{:.2f}%".format(labels[probs[${variable_name}][0]], probs[${variable_name}][1][probs[${variable_name}][0]]*100)` } else if (type == "X") { _code = '' + variable_name + '[0]'; } else if (type == "Y") { _code = '' + variable_name + '[1]'; } else if (type == "W") { _code = 'int(' + variable_name + '[2])'; } else if (type == "H") { _code = 'int(' + variable_name + '[3])'; } else if (type == "Confidence") { _code = `${variable_name}[4][1][${variable_name}[4][0]]*100`; } else if (type == "CX") { _code = `int((${variable_name}[0] + ${variable_name}[2])/2)`; } else if (type == "CY") { _code = `int((${variable_name}[1] + ${variable_name}[3])/2)`; } else { _code = `${variable_name}[${type}]-${variable_name}[${type - 2}]`; } // } return [_code, Blockly.Python.ORDER_ATOMIC]; } // // 车牌识别 Blockly.Blocks['ai_model_card_xy'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_card_if_true); this.setInputsInline(false); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_card_if_true); this.setHelpUrl(""); } }; Blockly.Python['ai_model_card_xy'] = function (block) { Blockly.Python.addFunction("cardShowRecognize", `def cardShowRecognize(): global CARDDATABOEX if len(CARDDATABOEX): for CARDDATABOEXI in CARDDATABOEX: canvas.draw_rectangle(CARDDATABOEXI[0],CARDDATABOEXI[1], CARDDATABOEXI[0]+CARDDATABOEXI[2]-CARDDATABOEXI[0],CARDDATABOEXI[1]+ CARDDATABOEXI[3]-CARDDATABOEXI[1], color=(255,0,0), thickness=1) canvas.draw_string(CARDDATABOEXI[0],CARDDATABOEXI[1], (str(LPRCARD.get_card_data(CARDDATABOEXI[4][:6]))), scale = 1, color = (255,255,255) , thickness = 1) `) var code = 'cardShowRecognize()\n'; return code; }; Blockly.Blocks['ai_model_card_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_card_attribute); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_card_attribute); this.setHelpUrl(""); } }; Blockly.Python['ai_model_card_result'] = function (block) { var code = 'CARDDATABOEX'; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_model_face_recognition_init_new'] = { init: function () { this.appendDummyInput().appendField(Blockly.Msg.ai_models_init_title) .appendField('人脸识别模型'); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_init_title + Blockly.Msg.ai_models_init_face_model); this.setHelpUrl(""); } }; Blockly.Python.ai_model_face_recognition_init_new = function (block) { Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize` Blockly.Python.definitions_.import_face_recognition_init_new = ` class Face_recognize: score_threshold = 70 #识别分数阈值 input_size = (224, 224, 3) #输入图片尺寸 input_size_fe = (128, 128, 3) #输入人脸数据 feature_len = 256 #人脸数据宽度 steps = [8, 16, 32] # channel_num = 0 #通道数量 users = [] #初始化用户列表 threshold = 0.5 #人脸阈值 nms = 0.3 max_face_num = 3 #输出的画面中的人脸的最大个数 names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] #人脸标签定义 model = { "param": "/root/preset/model/model_int8.param", "bin": "/root/preset/model/model_int8.bin" } model_fe = { "param": "/root/preset/model/fe_res18_117.param", "bin": "/root/preset/model/fe_res18_117.bin" } def __init__(self): for i in range(len(self.steps)): self.channel_num += self.input_size[1] / self.steps[i] * (self.input_size[0] / self.steps[i]) * 2 self.channel_num = int(self.channel_num) #统计通道数量 self.options = { #准备人脸输出参数 "model_type": "awnn", "inputs": { "input0": self.input_size }, "outputs": { "output0": (1, 4, self.channel_num) , "431": (1, 2, self.channel_num) , "output2": (1, 10, self.channel_num) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } self.options_fe = { #准备特征提取参数 "model_type": "awnn", "inputs": { "inputs_blob": self.input_size_fe }, "outputs": { "FC_blob": (1, 1, self.feature_len) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } print("-- load model:", self.model) self.m = nn.load(self.model, opt=self.options) print("-- load ok") print("-- load model:", self.model_fe) self.m_fe = nn.load(self.model_fe, opt=self.options_fe) print("-- load ok") self.face_recognizer = FaceRecognize(self.m, self.m_fe, self.feature_len, self.input_size, self.threshold, self.nms, self.max_face_num) def map_face(self,box,points): #将224*224空间的位置转换到240*240或320*240空间内 from maix import display # print(box,points) if display.width() == display.height(): def tran(x): return int(x/224*display.width()) box = list(map(tran, box)) def tran_p(p): return list(map(tran, p)) points = list(map(tran_p, points)) else: # 168x224(320x240) > 224x224(240x240) > 320x240 s = (224*display.height()/display.width()) # 168x224 w, h, c = display.width()/224, display.height()/224, 224/s t, d = c*h, (224 - s) // 2 # d = 224 - s // 2 == 28 box[0], box[1], box[2], box[3] = int(box[0]*w), int((box[1]-28)*t), int(box[2]*w), int((box[3])*t) def tran_p(p): return [int(p[0]*w), int((p[1]-d)*t)] # 224 - 168 / 2 = 28 so 168 / (old_h - 28) = 240 / new_h points = list(map(tran_p, points)) # print(box,points) return box,points def recognize(self, feature): #进行人脸匹配 def _compare(user): #定义映射函数 return self.face_recognizer.compare(user, feature) #推测匹配分数 score相关分数 face_score_l = list(map(_compare,self.users)) #映射特征数据在记录中的比对分数 return max(enumerate(face_score_l), key=lambda x: x[-1]) #提取出人脸分数最大值和最大值所在的位置 def __del__(self): del self.face_recognizer del self.m_fe del self.m face_recognizer = Face_recognize() `; // var degee = block.getFieldValue('DEGREE'); var _code = ""; // Blockly.Python.addVariable('task_facerecognition', 'task_facerecognition = None', true); return [_code, Blockly.Python.ORDER_ATOMIC]; } Blockly.Blocks['ai_model_face_recognition_load_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_load_title) .appendField(Blockly.Msg.ai_models_init_face_model); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_init_source) .appendField(new Blockly.FieldVariable("img_facerecognition"), "varitem"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('DEGREE'); var TOOLTIPS = { 'Human Face Recognition': Blockly.Msg.ai_model_allload_TOOLTIP.replace('%1', Blockly.Msg.ai_models_init_face_model) }; return TOOLTIPS[mode]; }); this.setHelpUrl(''); } }; Blockly.Python.ai_model_face_recognition_load_new = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var camera_variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('camera_varitem'), Blockly.Variables.NAME_TYPE); // Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; // var degee = block.getFieldValue('DEGREE'); var _code = `facesRecognitionLoadNew = face_recognizer.face_recognizer.get_faces(AI_img.tobytes(),False) #提取人脸特征信息 `; // Blockly.Python.addVariable('code_facerecognition', '', true); // _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n"; // _code += variable_name + ".ai_to_pix()\n"; return _code; } Blockly.Blocks['ai_model_xy_new'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_models_face_model_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_face_model_x, "X"], [Blockly.Msg.ai_models_face_model_y, "Y"], [Blockly.Msg.ai_models_face_model_w, "W"], [Blockly.Msg.ai_models_face_model_h, "H"], [Blockly.Msg.ai_models_face_model_x_center, "CX"], [Blockly.Msg.ai_models_face_model_y_center, "CY"], [Blockly.Msg.ai_models_face_model_count, "Number"], [Blockly.Msg.ai_models_face_model_index, "Serial"], [Blockly.Msg.ai_models_face_model_confidence, "Confidence"] ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('TYPE'); var TOOLTIPS = { 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x), 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y), 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w), 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h), 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center), 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center), 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count), 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index), 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python.ai_model_xy_new = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var _code = ""; if (type == "X") { _code = variable_name + "[0]"; } else if (type == "Y") { _code = variable_name + "[1]"; } else if (type == "W") { _code = variable_name + "[0] + " + variable_name + "[2]"; } else if (type == "H") { _code = variable_name + "[1] + " + variable_name + "[3]"; } // else if (type == "Number") { // _code = variable_name + ".objnum()"; // } else if (type == "Serial") { // _code = variable_name + ".index()"; // } else if (type == "Confidence") { // _code = variable_name + ".value()"; // } else if (type == "CX") { // _code = variable_name + ".x()+(" + variable_name + ".w()/2)"; // } else if (type == "CY") { // _code = variable_name + ".y()+(" + variable_name + ".h()/2)"; // } return [_code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_model_face_attribute_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_attribute); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_attribute_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_attribute_new'] = function (block) { var code = 'facesRecognitionLoadNew'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['face_recognition_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_name); this.appendDummyInput() .appendField(Blockly.Msg.v831_face_recognition_load); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_init_source) // .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem"); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD + ":") // .appendField(new Blockly.FieldVariable("people_name_list"), "people_name"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.v831_face_recognition_load_title); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_load'] = function (block) { // var face_list = Blockly.Python.variableDB_.getName(block.getFieldValue('people_name'), Blockly.Variables.NAME_TYPE); var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_from_maix_nn_face'] = `from maix.nn.app import face` Blockly.Python.definitions_['v831_import_from_maix_nn_FaceRecognize'] = `from maix.nn.app.face import FaceRecognize` Blockly.Python.addVariable('NUMBERPERSON', 'NUMBERPERSON = 0', true); Blockly.Python.definitions_.import_Face_Recognizer = `class Face_Recognizer: max_face_num = 4 detect_threshold = 0.5 detect_nms = 0.3 FEATURES = [] def __init__(self, threshold = 0.5, nms = 0.3, max_face_num = 1): model = "/root/preset/model/retinaface.mud" model_fe = "/root/preset/model/fe_resnet.mud" self.input_size = (224, 224, 3) input_size_fe = (128, 128, 3) self.feature_len = 256 self.features = [] m = nn.load(model) m_fe = nn.load(model_fe) self.isLoadRecoredFace = False self.CLASSNAMEFACELIST = ${value_class_input} self.recognizer = FaceRecognize(m, m_fe, self.feature_len, self.input_size, threshold, nms, max_face_num) self.FACERECOGNIZES = { } self.FACESRECOGNITONRESULT = [] def get_faces(self, img, std_img = False): faces = self.recognizer.get_faces(img, std_img) return faces def __len__(self): return len(self.features) def add_user(self, name, feature): self.features.append([name, feature]) return True def remove_user(self, name_del): rm = None for name, feature in self.features: if name_del == name: rm = [name, feature] if rm: self.features.remove(rm) return True return False def recognize(self, feature): max_score = 0 uid = -1 for i, user in enumerate(self.features): score = self.recognizer.compare(user[1], feature) if score > max_score: max_score = score uid = i if uid >= 0: return self.features[uid][0], max_score return None, 0 def get_input_size(self): return self.input_size def get_feature_len(self): return self.feature_len def darw_info(self, img, box, points, disp_str, bg_color=(255, 0, 0, 255), font_color=(255, 255, 255, 255), font_size=32): font_wh = image.get_string_size(disp_str) for p in points: img.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=bg_color) img.draw_rectangle(box[0], box[1], box[0] + box[2], box[1] + box[3], color=bg_color, thickness=2) if disp_str: img.draw_rectangle(box[0], box[1] - font_wh[1], box[0] + font_wh[0], box[1], color=bg_color, thickness = -1) img.draw_string(box[0], box[1] - font_wh[1], disp_str, color=font_color) def map_face(self,box,points,IMAGEFACESHOW): # print(box,points) for p in points: IMAGEFACESHOW.draw_rectangle(p[0] - 1, p[1] -1, p[0] + 1, p[1] + 1, color=(255,200,255)) #return box,points def darw_title(self, img, dis_size ,key_l = None, key_r =None): if key_C: key_l = "| "+ key_l img.draw_string( 1, 2 ,key_l , scale = 1, color = (255, 255, 255), thickness = 2) if key_D: key_r = key_r+" |" w = int(dis_size[0] - 4 - image.get_string_size(key_r)[0] * 1) img.draw_string( w, 2 ,key_r , scale = 1, color = (255, 255, 255), thickness = 2) def recognizeShowMessage(self, canvas): self.FACESRECOGNITONRESULT = FACERECGNIZER.get_faces(canvas) if len(self.FACESRECOGNITONRESULT): for FACESRECOGNITONRESULTI in self.FACESRECOGNITONRESULT: if self.isLoadRecoredFace: if int(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1])>85: canvas.draw_rectangle(FACESRECOGNITONRESULTI[1][0],FACESRECOGNITONRESULTI[1][1], FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][2],FACESRECOGNITONRESULTI[1][1]+ FACESRECOGNITONRESULTI[1][3], color=(51,204,0), thickness=1) canvas.draw_string(40,0, ("".join([str(x) for x in [FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[0], " : ", round(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1], 2)]])), scale = 1, color = (51,204,0) , thickness = 1) else: canvas.draw_rectangle(FACESRECOGNITONRESULTI[1][0],FACESRECOGNITONRESULTI[1][1], FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][2],FACESRECOGNITONRESULTI[1][1]+ FACESRECOGNITONRESULTI[1][3], color=(204,0,0), thickness=1) canvas.draw_string(40,0, ("".join([str(x) for x in [FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[0], " : ", round(FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[1], 2)]])), scale = 1, color = (204,0,0) , thickness = 1) else: FACERECGNIZER.map_face(FACESRECOGNITONRESULTI[1],FACESRECOGNITONRESULTI[2],canvas) canvas.draw_rectangle(FACESRECOGNITONRESULTI[1][0],FACESRECOGNITONRESULTI[1][1], FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][2],FACESRECOGNITONRESULTI[1][1]+ FACESRECOGNITONRESULTI[1][3], color=(255,0,0), thickness=1) FACERECGNIZER = Face_Recognizer(0.5, 0.3, max_face_num = 4) ` var code = `canvas = canvas.crop(48, 8,224, 224) FACERECGNIZER.recognizeShowMessage(canvas) `; return code; }; Blockly.Blocks['face_recognition_if_face_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_attribute_new) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_model_face_attribute_new); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_if_face_new'] = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("recognitionStatements", `def recognitionStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if len(FACERECGNIZER.FACESRECOGNITONRESULT) > 0: for BOXESI in FACERECGNIZER.FACESRECOGNITONRESULT: recognitionStatements(BOXESI) else: ${statements_input1} ` return code; }; Blockly.Blocks['face_recognition_if_face'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_face_model_if_new); this.setInputsInline(false); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_face_model_if_new); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_if_face'] = function (block) { var code = ``; return code; }; Blockly.Blocks['face_recognition_face_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_attribute_new); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_attribute_new); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_face_result'] = function (block) { var code = `FACESRECOGNITONRESULT`; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['face_recognition_detection_rectangle'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_face_model_get) .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.face_information, "rect"], [Blockly.Msg.ai_models_face_model_x, "X"], [Blockly.Msg.ai_models_face_model_y, "Y"], [Blockly.Msg.ai_models_face_model_confidence_1, "Confidence"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"], [Blockly.Msg.v831_model_face_name, "0"], [Blockly.Msg.v831_models_face_model_confidence, "1"], ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('TYPE'); var TOOLTIPS = { 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect), 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x), 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y), 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w), 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h), 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center), 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center), 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count), 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index), 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python.face_recognition_detection_rectangle = function (block) { var type = block.getFieldValue('TYPE'); var _code = ""; if (type == "rect") { _code = "FACESRECOGNITONRESULTI[3]"; } else if (type == "X") { _code = "FACESRECOGNITONRESULTI[1][0]"; } else if (type == "Y") { _code = "FACESRECOGNITONRESULTI[1][1]"; } else if (type == "W") { _code = `int(FACESRECOGNITONRESULTI[1][2]+FACESRECOGNITONRESULTI[1][0])`; } else if (type == "H") { _code = `int(FACESRECOGNITONRESULTI[1][3]+FACESRECOGNITONRESULTI[1][1])`; } else if (type == "Number") { _code = "FACESRECOGNITONRESULTI.objnum()"; } else if (type == "Serial") { _code = "FACESRECOGNITONRESULTI.index()"; } else if (type == "Confidence") { _code = "FACESRECOGNITONRESULTI[0]"; } else if (type == "CX") { _code = `int((FACESRECOGNITONRESULTI[1][2]+FACESRECOGNITONRESULTI[1][0]+FACESRECOGNITONRESULTI[1][0])/2)`; } else if (type == "CY") { _code = `int((FACESRECOGNITONRESULTI[1][3]+FACESRECOGNITONRESULTI[1][1]+FACESRECOGNITONRESULTI[1][1])/2)`; } else if (type == "0" || type == "1") { _code = `FACERECGNIZER.recognize(FACESRECOGNITONRESULTI[3])[${type}]` } else { _code = `FACESRECOGNITONRESULTI[1][${type}]`; } return [_code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['face_recognition_map_face'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.face_recognition_map_face_canvas) .appendField(new Blockly.FieldVariable("img_recognized_face"), "varitem") .appendField(Blockly.Msg.face_recognition_map_face_show) .appendField(Blockly.Msg.face_recognition_map_face_key_point); // this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_map_face'] = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var variable1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE); var code = `FACERECGNIZER.map_face(FACESRECOGNITONRESULTI[1],FACESRECOGNITONRESULTI[2],${variable_name}) `; return code; }; Blockly.Blocks['face_recognition_add'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ai_model_face_gather_1); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.v831_setting_face_data_save_title); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_add'] = function (block) { var _type = block.getFieldValue('button_type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` // var code = `key_${_type}.is_pressed()` Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.addVariable('ai_model_face_gather', ` def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep): f = open(_path, "a") f.write(_data + _sep) f.close() `, true); var language = localStorage.getItem("handPyLanguage"); let saveFace = "" if (language == "en") { saveFace = "Save Face" } else if (language == "zh-hant") { saveFace = "儲存人臉" } else { saveFace = "保存人脸" } var code = `if key_${_type}.is_pressed(): while not (key_${_type}.is_pressed() == False): time.sleep(0.1) if NUMBERPERSON < len(FACERECGNIZER.CLASSNAMEFACELIST): NUMBERPERSON = NUMBERPERSON + 1 FACERECGNIZER.add_user(FACERECGNIZER.CLASSNAMEFACELIST[len(FACERECGNIZER)], FACESRECOGNITONRESULTI[3]) FEATURES = FACERECGNIZER.features try: os.remove("/root/user/model/recorded_face_features.py") except: pass try: _CREATE_TEXT_FILE_WITH_CONTENT("/root/user/model/recorded_face_features.py", json.dumps(FACERECGNIZER.features), "\\r\\n") except: pass canvas.draw_string(0,0, str("${saveFace}") + str(NUMBERPERSON), scale = 1, color = (51,204,0) , thickness = 1) v831_display_show_canvas(canvas,_canvas_x,_canvas_y) time.sleep(1000 / 1000) `; return code; }; Blockly.Blocks['face_recognition_remove'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.v831_setting_face_data_remove) // this.appendStatementInput("input") // .setCheck(null) // .appendField(Blockly.Msg.basic_motion_statement_exec); // .appendField(new Blockly.FieldVariable("save_face_data"), "varitem"); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.v831_setting_face_data_remove_title); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_remove'] = function (block) { var _type = block.getFieldValue('button_type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` let language = localStorage.getItem("handPyLanguage"); let removeFace = "" let faceData = "" if (language == "en") { removeFace = "Remove Face" faceData = "Data" } else if (language == "zh-hant") { removeFace = "刪除人臉" faceData = "數據" } else { removeFace = "删除人脸" faceData = "数据" } var code = `if key_${_type}.is_pressed() and NUMBERPERSON > 0: while not (key_${_type}.is_pressed() == False): time.sleep(0.1) canvas.draw_rectangle(0,0, 0+320,0+ 20, color=(0,0,0), thickness=-1) canvas.draw_string(40,0, ("".join([str(x) for x in ["${removeFace}", NUMBERPERSON, "${faceData}"]])), scale = 1, color = (255,255,255) , thickness = 1) v831_display_show_canvas(canvas,_canvas_x,_canvas_y) time.sleep(1000 / 1000) NUMBERPERSON = NUMBERPERSON - 1 FACERECGNIZER.remove_user(FACERECGNIZER.CLASSNAMEFACELIST[len(FACERECGNIZER)-1]) FEATURES = FACERECGNIZER.features `; return code; }; Blockly.Blocks['face_recognition_data_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_data_load); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_data_load); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_data_load'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_json'] = `import json` Blockly.Python.definitions_['load_face_data'] = `isLoadRecoredFace = False try: with open("/root/user/model/recorded_face_features.py", "r") as file: FACERECGNIZER.features = json.loads(file.read()) FACERECGNIZER.isLoadRecoredFace = True except: FACERECGNIZER.isLoadRecoredFace = False ` var code = ``; return code; }; Blockly.Blocks['face_recognition_data_results'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(new Blockly.FieldVariable("img_face_Recognizer"), "varitem") .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_TYPE) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.v831_model_face_name, "0"], [Blockly.Msg.ai_models_face_model_confidence, "1"], ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.v831_face_recognition_result_title); this.setHelpUrl(""); } }; Blockly.Python['face_recognition_data_results'] = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var code = `FACERECGNIZER.recognize(${variable_name})[${type}] `; return [code, Blockly.Python.ORDER_ATOMIC]; }; // 自学习 Blockly.Blocks['ai_model_self_learning_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_init); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_init); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_init'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_.import_self_learning_init = ` CLASSNUM = ${JSON.parse(value_class_input).length} SAMPLENUM = ${JSON.parse(value_class_input).length * 5} CLASSNAMELIST = ${value_class_input} ` var code = ``; return code; }; Blockly.Blocks['ai_model_self_learning_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_load); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_load); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_load'] = function (block) { Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier` Blockly.Python.addVariable("SELFLEARNCOUNT", `SELFLEARNCOUNT = 0`, true) var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_.import_self_learning_init = ` CLASSNUM = ${JSON.parse(value_class_input).length} SAMPLENUM = ${JSON.parse(value_class_input).length * 5} CLASSNAMELIST = ${value_class_input} ` Blockly.Python.definitions_.self_learing_load = `class Self_learn: model = { "param": "/root/preset/model/resnet18_1000_awnn.param", "bin": "/root/preset/model/resnet18_1000_awnn.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "190": (1, 1, 512) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0176, 0.0176, 0.0176], } class_num = CLASSNUM #学习类别 sample_num = SAMPLENUM #学习类别总数量 curr_class = 0 curr_sample = 0 def __init__(self): self.m = nn.load(self.model, opt=self.options) self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224) SELFLEARN = Self_learn() ` var code = ''; return code; }; Blockly.Blocks['ai_model_self_learning_recognize_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_recognize_load); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_recognize_load); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_recognize_load'] = function (block) { Blockly.Python.definitions_['v831_import_from_maix_nn'] = `from maix import nn` Blockly.Python.definitions_['v831_import_Classifier'] = `from maix.nn.app.classifier import Classifier` Blockly.Python.definitions_['v831_from_nn_import_load'] = `from maix.nn.app.classifier import load` Blockly.Python.definitions_['v831_import_os'] = `import os` var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.addVariable("SELFLEARNCOUNT", `SELFLEARNCOUNT = 0`, true) Blockly.Python.definitions_.import_self_learning_init = ` CLASSNUM = ${JSON.parse(value_class_input).length} SAMPLENUM = ${JSON.parse(value_class_input).length * 5} CLASSNAMELIST = ${value_class_input} ` Blockly.Python.definitions_.self_learing_load = `class Self_learn: model = { "param": "/root/preset/model/resnet18_1000_awnn.param", "bin": "/root/preset/model/resnet18_1000_awnn.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "190": (1, 1, 512) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0176, 0.0176, 0.0176], } class_num = CLASSNUM #学习类别 sample_num = SAMPLENUM #学习类别总数量 curr_class = 0 curr_sample = 0 def __init__(self): if os.path.isfile("/root/module.bin"): self.m = nn.load(self.model, opt=self.options) self.classifier = load(self.m,"/root/module.bin") else: self.m = nn.load(self.model, opt=self.options) self.classifier = Classifier(self.m, self.class_num, self.sample_num, 512, 224, 224) print("not have model!") SELFLEARN = Self_learn() ` var code = ''; return code; }; Blockly.Blocks['ai_model_self_learning_add_class'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ai_model_self_learning_add_class_category + Blockly.Msg.ai_model_self_learning_make_data_set); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_add_class_category + Blockly.Msg.ai_model_self_learning_make_data_set); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_add_class'] = function (block) { var _type = block.getFieldValue('button_type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` var code = `canvas = canvas.crop(48, 8, 224, 224) if key_${_type}.is_pressed() and SELFLEARNCOUNT < SELFLEARN.class_num: while not (key_${_type}.is_pressed() == False): time.sleep(0.1) SELFLEARN.classifier.add_class_img(canvas) for i in range(5): SELFLEARN.classifier.add_sample_img(canvas) SELFLEARNCOUNT = SELFLEARNCOUNT + 1 `; return code; }; Blockly.Blocks['ai_model_self_learning_make_data_set'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_make_data_set); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_make_data_set); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_make_data_set'] = function (block) { var code = `for i in range(5): SELFLEARN.classifier.add_sample_img(canvas) `; return code; }; Blockly.Blocks['ai_model_self_learning_picture'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.CocoRobo_EVENT_ACTION_OPT1) .appendField(new Blockly.FieldDropdown([ ["A", "A"], ["B", "B"], ["C", "C"], ["D", "D"] ]), "button_type") .appendField(Blockly.Msg.ai_model_self_learning_picture + Blockly.Msg.ai_model_self_learning_save_modal); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_picture + Blockly.Msg.ai_model_self_learning_save_modal); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_picture'] = function (block) { var _type = block.getFieldValue('button_type'); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_BUTTON'] = `from CocoPi import BUTTON` // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")` Blockly.Python.definitions_['import_define_x_v831_button'] = `key_A = BUTTON(14) key_B = BUTTON(8) key_C = BUTTON(13) key_D = BUTTON(7) ` var code = `if key_${_type}.is_pressed() and SELFLEARNCOUNT >= SELFLEARN.class_num: while not (key_${_type}.is_pressed() == False): time.sleep(0.1) SELFLEARN.classifier.train() SELFLEARN.classifier.save("/root/module.bin") `; return code; }; Blockly.Blocks['ai_model_self_learning_save_modal'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_save_modal); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_save_modal); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_save_modal'] = function (block) { var code = `SELFLEARN.classifier.save("/root/module.bin") `; return code; }; Blockly.Blocks['ai_model_self_learning_class_verification'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_class_verification); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_class_verification); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_class_verification'] = function (block) { var code = `canvas = canvas.crop(48, 8, 224, 224) SELFLEARNidx, SELFLEARNdistance = SELFLEARN.classifier.predict(canvas) `; return code; }; Blockly.Blocks['ai_model_self_learning_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_self_learning_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_model_self_learning_result_name, "X"], [Blockly.Msg.ai_models_object_model_confidence, "Y"] ]), "TYPE");; this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_self_learning_result); this.setHelpUrl(""); } }; Blockly.Python['ai_model_self_learning_result'] = function (block) { var type = block.getFieldValue('TYPE'); var code = ''; if (type == 'X') { code = `CLASSNAMELIST[SELFLEARNidx]` } else { code = `100-SELFLEARNdistance` } return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_model_customized_init_setup_definition'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/header_customized_model.png", 50, 50, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_model_customized_init_setup_definition); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_definition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_init_setup_definition'] = function (block) { // TODO: Assemble Python into code variable. Blockly.Python.includes_.import_amxisd = '' + 'print("Clearing Cached Variables...", end="")\n' + 'for name in dir(): \n' + ' if not name.startswith(\'_\'): \n' + ' del globals()[name]\n' + 'print(" Done")\n' + 'import KPU as kpu\n' + 'kpu.memtest()\n' + 'from Maix import utils\n' + 'import gc\n' + 'gc.enable()\n' + 'utils.gc_heap_size()\n' + '\n' + '################# Done Init #################\n' + ''; var code = ''; return code; }; // 初始化serialcomm_read_setup_title_text_1 Blockly.Blocks['ai_model_index_custom_initialization_init_1'] = { init: function () { this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.serialcomm_read_setup_title_text_1) // .appendField("DEGREE"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.serialcomm_read_setup_title_text_1); this.setHelpUrl(''); } }; Blockly.Python.ai_model_index_custom_initialization_init_1 = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_.import_KPU = "import KPU as kpu"; var _code = value_class_input; return _code; } // 自定义人脸识别 Blockly.Blocks['ai_model_face_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_setup); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_setup); this.setHelpUrl(""); } }; Blockly.Python.ai_model_face_model = function (block) { Blockly.Python.definitions_['v831_import_time'] = `import time` Blockly.Python.definitions_['v831_import_gc'] = `import gc` Blockly.Python.includes_.import_amxisd = '' + 'for name in dir(): \n' + ' if not name.startswith(\'_\'): \n' + ' del globals()[name]\n' + 'gc.enable()\n' + '\n' + 'try:\n' + ' from cocorobo import firmware_info\n' + 'except BaseException as e:\n' + ' print(str(e))\n' + ' pass\n' + '\n' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' from Maix import utils\n' + ' utils.gc_heap_size(0xAF000)\n' + 'else:\n' + ' import utime\n' + ' clock = None\n' + ' ACCURACY = 85\n' + '\n' + 'task_fd = None\n' + 'task_ld = None\n' + 'task_fe = None\n' + '\n' + ''; var code = ` from fpioa_manager import * from Maix import FPIOA, GPIO _gp_side_buttons = [9, 10, 11] FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0) FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1) FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2) _gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP) _gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP) _gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP) side_button_state = False def run_face_compare(record_ftrs, feature): scores = [] for j in range(len(record_ftrs)): score = kpu.face_compare(record_ftrs[j], feature) scores.append(score) max_score = 0 # if int(str(firmware_info.ai()).split("-")[0]) < 2021: # index = -1 # else: # index = 0 index = -1 for k in range(len(scores)): if max_score < scores[k]: max_score = scores[k] index = k return [scores, max_score, index] # print(scores) `; // var code = ''; return [code, Blockly.Python.ORDER_ATOMIC]; } // 设置人脸识别名称 Blockly.Blocks['ai_model_face_setup'] = { init: function () { // this.appendDummyInput() // .appendField(Blockly.Msg.ai_model_face_setup); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_face_name); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_name.replace(":", "")); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_setup'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var code = ` img_lcd = image.Image() # img_face = image.Image(size=(128, 128)) collectNum = 0 record_ftrs = [] result = [] res_index = -1 # a = img_face.pix_to_ai() names = ` + value_class_input + ` `; return code; }; Blockly.Blocks['ai_face_detection_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_face_detection_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_face_detection_model_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_face_detection_model'] = function (block) { var code = '\n' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' task_fd = kpu.load("/sd/preset/models/face_reocgnition/FD.emodel") # 人脸检测模型\n' + 'else:\n' + ' task_fd = kpu.load("/sd/preset/models/face/v2/FaceDetection.emodel") # 0x300000)\n' + 'anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n' + 'a = kpu.init_yolo2(task_fd, 0.5, 0.3, 5, anchor)\n' + '\n' + ''; return code; }; Blockly.Blocks['ai_face_point_detection_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_face_point_detection_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_face_point_detection_model_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_face_point_detection_model'] = function (block) { Blockly.Python.definitions_.import_ai_face_point_detection_model = ` def run_five_points_inference(canvas, canvas_face, detected_face_rect): a = canvas.draw_rectangle(detected_face_rect) # Create face image from detection face_cut = canvas.cut(detected_face_rect[0], detected_face_rect[1], detected_face_rect[2], detected_face_rect[3]) # Convert created face image to a dimension of 128x128 face_cut_128 = face_cut.resize(128, 128) # 将正脸图像转为kpu格式, 便于后面的关键点模型的使用 a = face_cut_128.pix_to_ai() # Get landmark for 5 points of the detected face # 运行人脸5点关键点检测模型, 获取当前识别人脸的关键点数据 fmap = kpu.forward(task_ld, face_cut_128) # print("fmap", fmap) # 获取关键点预测结果 plist = fmap[:] # print("plist", plist) # Get position of left eye, then draw it on the canvas. le = (i.x()+int(plist[0]*i.w() - 10), i.y()+int(plist[1]*i.h())) a = canvas.draw_circle(le[0], le[1], 4) # Get position of Right eye, then draw it on the canvas. re = (i.x()+int(plist[2]*i.w()), i.y()+int(plist[3]*i.h())) a = canvas.draw_circle(re[0], re[1], 4) # Get position of Nose, then draw it on the canvas. nose = (i.x()+int(plist[4]*i.w()), i.y()+int(plist[5]*i.h())) a = canvas.draw_circle(nose[0], nose[1], 4) # Get position of Left cheek, then draw it on the canvas. lm = (i.x()+int(plist[6]*i.w()), i.y()+int(plist[7]*i.h())) a = canvas.draw_circle(lm[0], lm[1], 4) # Get position of Right cheek, then draw it on the canvas. rm = (i.x()+int(plist[8]*i.w()), i.y()+int(plist[9]*i.h())) a = canvas.draw_circle(rm[0], rm[1], 4) # Align face to standard position src_point = [le, re, nose, lm, rm] ''' get_affine_transform() 函数, 根据获得的5点坐标与标准正脸坐标获取仿射变换矩阵 - 计算3个二维点对之间的仿射变换矩阵H(2行x3列),自由度为6。 - 仿射变换的原理就是根据源图像中一个三角形的顶点坐标和应用仿射变换之后的 - 目标图像中一个三角形的顶点坐标计算出一个变换矩阵,然后将这个矩阵应用到整个源图像。 src_point 为输入源图像中的三角形顶点坐标 dst_point 为输出目标图像中的三角形顶点坐标 Ref: https://zhuanlan.zhihu.com/p/142260846 ''' T = image.get_affine_transform(src_point, dst_point) ''' warp_affine_ai() 函数, 对原始图片人脸图片进行仿射变换,变换为正脸图像 ''' a = image.warp_affine_ai(canvas, canvas_face, T) ''' 将正脸图像转为kpu格式 ''' a = canvas_face.ai_to_pix() # Recycle face_cut_128 in order to reduce memory usage del(face_cut_128) `; var code = '\n' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' task_ld = kpu.load("/sd/preset/models/face_reocgnition/KP_chwise.emodel") # 人脸5点关键点检测模型\n' + 'else:\n' + ' task_ld = kpu.load("/sd/preset/models/face/v2/FaceLandmarkDetection.emodel")# 0x400000)\n' + 'dst_point = [(44, 59), (84, 59), (64, 82), (47, 105),(81, 105)]\n' + '\n' + ''; return code; }; Blockly.Blocks['ai_face_Vitter_eigenvalue_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_face_Vitter_eigenvalue_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_face_Vitter_eigenvalue_model_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_face_Vitter_eigenvalue_model'] = function (block) { Blockly.Python.definitions_.import_ai_face_Vitter_eigenvalue_model = ` def run_fmap_calculation(canvas_face): global fmap # Calculate face feature vector from 'img_face', 计算正脸图片的196维特征值 fmap = kpu.forward(task_fe, canvas_face) # 获取计算结果 feature = kpu.face_encode(fmap[:]) return feature `; var code = '\n' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' task_fe = kpu.load("/sd/preset/models/face_reocgnition/face_recognition_v4_2020_09_07.emodel") # 人脸196维特征值模型\n' + ' kpu.set_outputs(task_fe, 0,1,1, 512)\n' + 'else:\n' + ' task_fe = kpu.load("/sd/preset/models/face/v2/FeatureExtraction.emodel")# 0x500000)\n' + ' clock = time.clock()\n' + '\n' + ''; return code; }; // 加载人脸检测模型,设置识别图像源 Blockly.Blocks['ai_model_face_start_recognition'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source) .appendField(new Blockly.FieldVariable("img"), "varitem"); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_customized_init_type_set) // .appendField(new Blockly.FieldDropdown([ // [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"], // [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"] // ]), "detect_type"); // this.appendStatementInput("NAME") // .setCheck(null) // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_start_recognition_TOOLTIP); this.setHelpUrl(""); } } Blockly.Python['ai_model_face_start_recognition'] = function (block) { // var statements_name = Blockly.Python.statementToCode(block, 'NAME'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // var dropdown_detect_type = block.getFieldValue('detect_type'); localStorage.setItem("ai_model_face_variable_name", variable_name); var code = '' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' index = -1\n' + 'else:\n' + ' clock.tick()\n' + 'a = img_face.pix_to_ai()\n' + 'code = kpu.run_yolo2(task_fd, ' + variable_name + ')\n'; return code; } Blockly.Blocks['ai_models_customized_init_type_set'] = { init: function () { // this.appendDummyInput() // .appendField(Blockly.Msg.ai_model_face_start_recognition + Blockly.Msg.ai_models_customized_init_setup_source) // .appendField(new Blockly.FieldVariable("img"), "varitem"); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_customized_init_type_set) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_customized_init_type_set_fast, "fast"], [Blockly.Msg.ai_models_customized_init_type_set_slow, "slow"] ]), "detect_type"); // this.appendStatementInput("NAME") // .setCheck(null) // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_customized_init_type_set.replace(":", "")); this.setHelpUrl(""); } } Blockly.Python['ai_models_customized_init_type_set'] = function (block) { // var statements_name = Blockly.Python.statementToCode(block, 'NAME'); // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var dropdown_detect_type = block.getFieldValue('detect_type'); // localStorage.setItem("ai_model_face_variable_name", variable_name); if (dropdown_detect_type == "fast") { // var break_string = " break\n"; var break_string = "break_string = True\n"; } else if (dropdown_detect_type == "slow") { // var break_string = " # break\n"; var break_string = "break_string = False\n"; } var code = '' + break_string + '\n'; return code; } Blockly.Blocks['ai_model_face_model_load_finish'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_model_load_finish); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_model_load_finish_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_model_load_finish'] = function (block) { var code = 'code is not None'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_face_model_list'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_model_list); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_model_list_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_model_list'] = function (block) { var code = 'code'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_face_detection_rectangle'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(new Blockly.FieldVariable("i"), "varitem") .appendField(Blockly.Msg.ai_models_face_model_get) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_face_model_rect, "rect"], [Blockly.Msg.ai_models_face_model_x, "X"], [Blockly.Msg.ai_models_face_model_y, "Y"], [Blockly.Msg.ai_models_face_model_w, "W"], [Blockly.Msg.ai_models_face_model_h, "H"], [Blockly.Msg.ai_models_face_model_x_center, "CX"], [Blockly.Msg.ai_models_face_model_y_center, "CY"], [Blockly.Msg.ai_models_face_model_count, "Number"], [Blockly.Msg.ai_models_face_model_index, "Serial"], [Blockly.Msg.ai_models_face_model_confidence, "Confidence"] ]), "TYPE"); this.setInputsInline(false); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('TYPE'); var TOOLTIPS = { 'rect': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_rect), 'X': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x), 'Y': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y), 'W': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_w), 'H': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_h), 'CX': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_x_center), 'CY': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_y_center), 'Number': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_count), 'Serial': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_index), 'Confidence': Blockly.Msg.ai_model_xy_TOOLTIP.replace('%1', Blockly.Msg.ai_models_face_model_confidence) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python.ai_model_face_detection_rectangle = function (block) { var type = block.getFieldValue('TYPE'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var _code = ""; if (type == "rect") { _code = variable_name + ".rect()"; } else if (type == "X") { _code = variable_name + ".x()"; } else if (type == "Y") { _code = variable_name + ".y()"; } else if (type == "W") { _code = variable_name + ".w()"; } else if (type == "H") { _code = variable_name + ".h()"; } else if (type == "Number") { _code = variable_name + ".objnum()"; } else if (type == "Serial") { _code = variable_name + ".index()"; } else if (type == "Confidence") { _code = variable_name + ".value()"; } else if (type == "CX") { _code = variable_name + ".x()+(" + variable_name + ".w()/2)"; } else if (type == "CY") { _code = variable_name + ".y()+(" + variable_name + ".h()/2)"; } return [_code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks['ai_model_face_load_point_detection_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_load_point_detection_model + Blockly.Msg.ai_models_customized_init_setup_source) .appendField(new Blockly.FieldVariable("img"), "varitem"); this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_1) .appendField(new Blockly.FieldVariable("img_face"), "varitem1"); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_face_load_point_detection_model_2); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_load_point_detection_model_TOOLTIP); this.setHelpUrl(""); } } Blockly.Python.ai_model_face_load_point_detection_model = function (block) { var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var variable_name_1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE); var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var _code = "run_five_points_inference(" + variable_name + ", " + variable_name_1 + ", " + value_class_input + ")\n"; return _code; }; Blockly.Blocks['ai_model_face_gather'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_gather); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_face_gather_1); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_gather_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_gather'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', ''); Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.addVariable('ai_model_face_gather', ` def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep): f = open(_path, 'a') f.write(_data + _sep) f.close() `, true); var code = '' + '# start to gather faces\n' + 'result = run_face_compare(record_ftrs, feature)\n' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021 and collectNum < len(names):\n' + ' if(len(names) > result[2]):\n' + ' if result[1] <= 80:\n' + ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), ("X :%2.1f" % (result[1])), color=(102, 204, 153), scale=1, mono_space=False)\n' + ' if _gp_side_b.value() == True and side_button_state == False:\n' + ' record_ftrs.append(feature)\n' + ' collectNum = collectNum + 1\n' + ' side_button_state = True\n' + ' elif _gp_side_b.value() == False and side_button_state == True:\n' + ' side_button_state = False\n' + 'elif int(str(firmware_info.ai()).split("-")[0]) >= 2021 and collectNum < len(names):\n' + ' if(len(names) > result[2]):\n' + ' if result[1] <= ACCURACY:\n' + ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), " " , color=(102, 204, 153), scale=1, mono_space=False)\n' + ' if _gp_side_b.value() == True and side_button_state == False:\n' + ' record_ftrs.append(feature)\n' + ' collectNum = collectNum + 1\n' + ' side_button_state = True\n' + ' elif _gp_side_b.value() == False and side_button_state == True:\n' + ' side_button_state = False\n' + 'if collectNum >= len(names):\n' + ' try:\n' + ' os.remove("/sd/user/' + value_class_input + '.py")\n' + ' except:\n' + ' pass\n' + ' all = {}\n' + ' try:\n' + ' for j in range(len(names)):\n' + ' all[names[j]] = record_ftrs[j]\n' + ' _CREATE_TEXT_FILE_WITH_CONTENT("/sd/user/' + value_class_input + '.py", "all =" + str(all), "\\r\\n")\n' + '\n' + ' except:\n' + ' pass\n' + // 'if break_string == True:\n' + // ' break\n' + '\n'; return code; }; Blockly.Blocks['ai_model_face_gather_num_judge'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_gather_num_judge); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_gather_num_judge_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_gather_num_judge'] = function (block) { var code = 'collectNum >= len(names)'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_face_data_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_data_load); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_face_data_load_1); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_data_load_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_data_load'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', ''); Blockly.Python.addVariable('ai_model_face_data_load', ` try: import user.${value_class_input} as recorded_face_features except: pass `, true); var code = '' + '# load faces data\n' + 'all = {}\n' + 'record_ftrs = []\n' + 'collectNum = len(names)\n' + 'try:\n' + ' all = recorded_face_features.all\n' + ' for j in range(len(names)):\n' + ' record_ftrs.append(all[names[j]])\n' + '\n' + 'except:\n' + ' pass\n' + '\n'; // 'all = recorded_face_features.all\n' + return code; }; Blockly.Blocks['ai_model_face_recognition'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_recognition); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_recognition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_recognition'] = function (block) { var code = '' + 'if collectNum >= len(names):\n' + ' result = run_face_compare(record_ftrs, feature)\n' + ' if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' if(len(names) > result[2]):\n' + ' if result[1] > 80:\n' + ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), ("%s :%2.1f" % (names[result[2]], result[1])), color=(0, 255, 0), scale=1, mono_space=False)\n' + ' else:\n' + ' if(len(names) > result[2]):\n' + ' if result[1] > ACCURACY:\n' + ' a = lcd_draw_string(' + localStorage.getItem("ai_model_face_variable_name") + ', i.x(), i.y(), ("%s :%2.1f" % (names[result[2]], result[1])), color=(0, 255, 0), scale=1, mono_space=False)\n' + ' res_index = result[2]\n' + '\n' + 'if break_string == True:\n' + ' break\n' + '\n' + ''; return code; }; Blockly.Blocks['ai_model_face_recognition_get_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_face_recognition_get_result); // this.appendStatementInput("NAME") // .setCheck(null) // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do); this.setOutput(true); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_face_recognition_get_result_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_face_recognition_get_result'] = function (block) { // var statements_name = Blockly.Python.statementToCode(block, 'NAME'); var code = '(len(names) > result[2] and collectNum >= len(names))'; // statements_name + // 'if break_string == True:\n' + // ' break\n' + // 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + // ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' + // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' + // ' gc.collect()\n' + // ' # kpu.memtest()\n' + // 'else:\n' + // ' fps = clock.fps()\n' + // ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' + // ' gc.collect()\n' + // ' # kpu.memtest()\n' + // '\n' + // ''; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_getfaceresult'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_getface); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_getface_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_getfaceresult'] = function (block) { // TODO: Assemble Python into code variable. var code = 'names[res_index] if (res_index != -1 and len(names) > res_index and collectNum >= len(names)) else ""'; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_show_face'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_show_face); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_show_face'] = function (block) { var code = '' + // ' if break_string == True:\n' + // ' break\n' + 'lcd_draw_string(img, 240, 0, (str(num)), color = (255, 102, 0), scale = 2, mono_space = False)\n' + 'if isCollect == 0:\n' + ' lcd_draw_string(img, 40, 0, "按A识别上次样本", color = (255, 0, 0), scale = 1, mono_space = False)\n' + ' lcd_draw_string(img, 40, 16, "按C重新拍摄", color = (255, 0, 0), scale = 1, mono_space = False)\n' + 'elif isCollect == 1:\n' + ' lcd_draw_string(img, 40, 0, "开始识别", color = (255, 0, 0), scale = 1, mono_space = False)\n' + 'elif isCollect == 2:\n' + ' lcd_draw_string(img, 40, 0, "开始采集人脸模板数据", color = (255, 0, 0), scale = 1, mono_space = False)\n' + 'if int(str(firmware_info.ai()).split("-")[0]) < 2021:\n' + ' ' + localStorage.getItem("ai_model_face_variable_name") + ' = ' + localStorage.getItem("ai_model_face_variable_name") + '.cut(40,0,240,240)\n' + ' lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ', oft=(0,0))\n' + ' gc.collect()\n' + 'else:\n' + ' fps = clock.fps()\n' + ' a = lcd.display(' + localStorage.getItem("ai_model_face_variable_name") + ')\n' + ' gc.collect()\n' + ''; return code; }; Blockly.Blocks['ai_model_class_setup'] = { init: function () { // this.appendDummyInput() // .appendField(Blockly.Msg.ai_model_class_setup); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_class_name); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_class_name.replace(":", "")); this.setHelpUrl(""); } }; Blockly.Python['ai_model_class_setup'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var code = ` ############### config ################# class_names = ` + value_class_input + ` class_num = len(class_names) sample_num = len(class_names) * 5 THRESHOLD = 11 board_cube = 0 button_state = False FPIOA().set_function(10, FPIOA.GPIO1) key1 = GPIO(GPIO.GPIO1, GPIO.IN, GPIO.PULL_UP) `; return code; }; Blockly.Blocks['ai_class_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_class_model); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_class_model_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_class_model'] = function (block) { Blockly.Python.addVariable('ai_class_model', ` try: del model except Exception: pass try: del classifier except Exception: pass gc.collect() cap_num = 0 train_status = 0 last_cap_time = 0 last_btn_status = 0 res_index = -1 is_save = 0 `) var code = 'model = kpu.load("/sd/preset/models/object_classifier.emodel")\n'; return code; }; Blockly.Blocks['ai_class_model_cluster'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_class_model_cluster); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_class_model_cluster_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_class_model_cluster'] = function (block) { // Blockly.Python.addVariable('ai_class_model_cluster', ` // `) var code = 'classifier = kpu.classifier(model, class_num, sample_num)\n'; return code; }; Blockly.Blocks['ai_model_class_start_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_customized_init_setup_source) .appendField(new Blockly.FieldVariable("img"), "varitem"); this.appendDummyInput() .appendField(Blockly.Msg.ai_model_class_start_load); // this.appendStatementInput("NAME") // .setCheck(null) // .appendField(Blockly.Msg.ai_speech_recognition_any_result_text_do); this.setInputsInline(false); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_class_start_load_TOOLTIP); this.setHelpUrl(""); } } Blockly.Python['ai_model_class_start_load'] = function (block) { // var statements_name = Blockly.Python.statementToCode(block, 'NAME'); var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); localStorage.setItem("ai_model_class_start_load", variable_name); var code = '' + 'if board_cube:\n' + ' ' + variable_name + ' = ' + variable_name + '.rotation_corr(z_rotation=90)\n' + ' ' + variable_name + '.pix_to_ai()\n' + '\n'; return code; } Blockly.Blocks['ai_model_class_data_load'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_class_data_load); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_class_data_load_1); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_class_data_load_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_class_data_load'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', ''); var code = '' + 'try:\n' + ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' + ' f=open(saved_path,"r")\n' + ' classifier, class_num, sample_num = kpu.classifier.load(model, saved_path)\n' + ' train_status = 1\n' + 'except:\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0, 0, 240,20, fill=True, color=(0,0,0))\n' + ' lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 0, 0, "Not found last sample", color=lcd.WHITE,scale=1,mono_space=False)\n' + '\n'; return code; }; Blockly.Blocks['ai_model_class_gather_load_finish'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_class_gather_load_finish); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_class_gather_load_finish_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_class_gather_load_finish'] = function (block) { var code = 'train_status == 0'; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_class_cluster_train'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_class_cluster_train); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_model_class_cluster_train_1); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_class_cluster_train_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_class_cluster_train'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC).replace('\"', '').replace('\"', ''); var code = '' + 'if cap_num >= class_num + sample_num and train_status == 0:\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(58,98, len("training...")*10+8 , 24, fill=True, color=lcd.RED)\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 60, 100, "training...", color=lcd.WHITE,scale=1,mono_space=False)\n' + ' lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ')\n' + ' try:\n' + ' classifier.train()\n' + ' saved_path = "/sd/user/' + value_class_input + '.classifier"\n' + ' f=open(saved_path,"r")\n' + ' os.remove("/sd/user/' + value_class_input + '.classifier")\n' + ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' + ' except:\n' + ' classifier.save("/sd/user/' + value_class_input + '.classifier")\n' + ' time.sleep(2)\n' + ' train_status = 1\n' + '\n'; return code; }; Blockly.Blocks['ai_model_class_recognition'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_class_recognition); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_class_recognition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_class_recognition'] = function (block) { var code = '' + '# predict\n' + 'if train_status == 1:\n' + ' res_index = -1\n' + ' try:\n' + ' res_index, min_dist = classifier.predict(' + localStorage.getItem("ai_model_class_start_load") + ')\n' + ' except Exception as e:\n' + ' print("predict err:", e)\n' + ' if res_index >= 0 and min_dist < THRESHOLD :\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0,0, len(class_names[res_index])*10+8 , 24, fill=True, color=lcd.RED)\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 2, 2, class_names[res_index], color=lcd.WHITE,scale=1,mono_space=False)\n' + ' else:\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + '.draw_rectangle(0,0, len("maybe {}".format(class_names[res_index]))*10+8 , 24, fill=True, color=lcd.RED)\n' + ' ' + localStorage.getItem("ai_model_class_start_load") + ' = lcd_draw_string(' + localStorage.getItem("ai_model_class_start_load") + ', 2, 2, "maybe {}".format(class_names[res_index]), color=lcd.WHITE,scale=1,mono_space=False)\n' + '\n'; return code; }; Blockly.Blocks['ai_model_show_class'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_show_face); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_show_face_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_show_class'] = function (block) { var code = '' + '' + localStorage.getItem("ai_model_class_start_load") + ' = ' + localStorage.getItem("ai_model_class_start_load") + '.cut(0,0,240,240)\n' + 'lcd.display(' + localStorage.getItem("ai_model_class_start_load") + ', oft=(0,0))\n' + ''; return code; }; Blockly.Blocks['ai_model_customized_init_setup'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_customized_init_setup_title); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_customized_init_setup_path) .appendField(new Blockly.FieldTextInput("yolov2_int8"), "model_path"); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_customized_init_setup_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_init_setup'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var text_model_path = block.getFieldValue('model_path'); Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn"; Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` let path = `/root/user/model/${text_model_path}` if (text_model_path == "autologistics") { path = `/root/preset/model/${text_model_path}` } let code = `class Yolo: labels = ${value_class_input} anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65] m = { "param": "${path}.param", "bin": "${path}.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "output0": (7, 7, (1+4+len(labels))*5) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } def __init__(self): from maix import nn from maix.nn import decoder self.model = nn.load(self.m, opt=self.options) self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7)) def __del__(self): del self.model del self.decoder Yolo = Yolo() `; return code; }; Blockly.Blocks['ai_model_customized_load_setup'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_customized_load_setup_title); this.appendDummyInput() .appendField(Blockly.Msg.ai_models_customized_init_setup_path) .appendField(new Blockly.FieldTextInput("yolov2_int8"), "model_path"); // this.appendDummyInput() // .appendField(Blockly.Msg.ai_models_customized_init_setup_source) // .appendField(new Blockly.FieldVariable("img_modelrecognition"), "varitem"); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.ai_models_customized_init_setup_name); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_customized_load_setup_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_load_setup'] = function (block) { var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var text_model_path = block.getFieldValue('model_path'); Blockly.Python.definitions_['v831_import_from_maix_nn'] = "from maix import nn"; Blockly.Python.definitions_['v831_import_from_maixnn_decoder'] = `from maix.nn import decoder` let path = `/root/user/model/${text_model_path}` if (text_model_path == "autologistics") { path = `/root/preset/model/${text_model_path}` } Blockly.Python.definitions_['CLASSYOLO'] = `class Yolo: labels = ${value_class_input} anchors = [1.19, 1.98, 2.79, 4.59, 4.53, 8.92, 8.06, 5.29, 10.32, 10.65] m = { "param": "${path}.param", "bin": "${path}.bin" } options = { "model_type": "awnn", "inputs": { "input0": (224, 224, 3) }, "outputs": { "output0": (7, 7, (1+4+len(labels))*5) }, "mean": [127.5, 127.5, 127.5], "norm": [0.0078125, 0.0078125, 0.0078125], } def __init__(self): self.model = nn.load(self.m, opt=self.options) self.decoder = decoder.Yolo2(len(self.labels), self.anchors, net_in_size=(224, 224), net_out_size=(7, 7)) self.FACESYOLOS = { "FACE_START_X": [], "FACE_START_Y": [], "FACE_CENTET_X": [], "FACE_CENTET_Y": [], "FACE_WIDTH": [], "FACE_HEIGHT": [], "FACE_RESULT": [], "FACE_CONFIDENCE": [], } def __del__(self): del self.model del self.decoder def faceRecognizeShowResult(self,canvas): out = self.model.forward(canvas, quantize=True, layout="hwc") BOXES, PROBS = self.decoder.run(out, nms=0.3, threshold=0.3, img_size=(224, 224)) if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string((BOXOBJ[0]),(BOXOBJ[1]), ("".join([str(x) for x in [self.labels[PROBS[BOXESI][0]], ";", str(round((PROBS[BOXESI][1][PROBS[BOXESI][0]]*100), 2)) + str("%")]])), scale = 1, color = (255,0,0) , thickness = 1) canvas.draw_rectangle((BOXOBJ[0]),(BOXOBJ[1]), (BOXOBJ[0])+(BOXOBJ[2]),(BOXOBJ[1])+ (BOXOBJ[3]), color=(255,0,0), thickness=1) BOXES[BOXESI].append(PROBS[BOXESI]) return BOXES FaceYolo = Yolo() `; var code = `canvas = canvas.crop(48,8,224,224) BOXES = FaceYolo.faceRecognizeShowResult(canvas) `; return code; }; Blockly.Blocks['ai_model_customized_get_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_from) .appendField(Blockly.Msg.ai_models_customized_get_result_any) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_models_customized_get_result_name, "classid"], [Blockly.Msg.ai_models_customized_get_result_x, "x"], [Blockly.Msg.ai_models_customized_get_result_y, "y"], // [Blockly.Msg.ai_models_customized_get_result_w, "w"], // [Blockly.Msg.ai_models_customized_get_result_h, "h"], // [Blockly.Msg.ai_models_customized_get_result_x_center, "cx"], // [Blockly.Msg.ai_models_customized_get_result_y_center, "cy"], // [Blockly.Msg.ai_models_customized_get_result_count, "objnum"], // [Blockly.Msg.ai_models_customized_get_result_index, "index"], [Blockly.Msg.ai_models_customized_get_result_confidence, "value"], [Blockly.Msg.ai_models_face_model_ws, "2"], [Blockly.Msg.ai_models_face_model_hs, "3"], [Blockly.Msg.ai_models_object_model_x_center, "CX"], [Blockly.Msg.ai_models_object_model_y_center, "CY"] ]), "get_results"); this.setOutput(true, null); this.setColour("#ee783a"); var thisBlock = this; this.setTooltip(function () { var mode = thisBlock.getFieldValue('get_results'); var TOOLTIPS = { 'classid': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_name), 'x': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x), 'y': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y), 'w': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_w), 'h': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_h), 'cx': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_x_center), 'cy': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_y_center), 'objnum': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_count), 'index': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_index), 'value': Blockly.Msg.ai_model_customized_get_result_TOOLTIP.replace('%1', Blockly.Msg.ai_models_customized_get_result_confidence) }; return TOOLTIPS[mode]; }); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_get_result'] = function (block) { var variable_name = "BOXESI"; var dropdown_get_results = block.getFieldValue('get_results'); // TODO: Assemble Python into code variable. var code = ''; if (dropdown_get_results == "classid") { code = 'Yolo.labels[' + variable_name + '[4][0]]'; } else if (dropdown_get_results == 'x') { code = variable_name + '[0]'; } else if (dropdown_get_results == "y") { code = variable_name + "[1]"; } else if (dropdown_get_results == "w") { code = `${variable_name}[0]+${variable_name}[2]`; } else if (dropdown_get_results == "h") { code = `${variable_name}[1]+${variable_name}[3]`; } else if (dropdown_get_results == "value") { code = `${variable_name}[4][1][${variable_name}[4][0]]`; } else if (dropdown_get_results == "CX") { code = `int((${variable_name}[0] + ${variable_name}[2])/2)`; } else if (dropdown_get_results == "CY") { code = `int((${variable_name}[1] + ${variable_name}[3])/2)`; } else { code = `${variable_name}[${dropdown_get_results}]`; } // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['ai_model_customized_if_got_new'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_customized_attribute) this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.appendStatementInput("input1") .setCheck(null) .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE); this.setColour("#ee783a"); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setTooltip(Blockly.Msg.ai_model_customized_attribute); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_if_got_new'] = function (block) { var statements_input = Blockly.Python.statementToCode(block, 'input'); var statements_input1 = Blockly.Python.statementToCode(block, 'input1'); let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.addFunction("cardStatements", `def cardStatements(BOXESI): ${global != "" ? `global ${global}` : "pass"} ${statements_input} `) var code = `if len(BOXES) > 0: for BOXESI in BOXES: cardStatements(BOXESI) else: ${statements_input1} ` return code; }; Blockly.Blocks['ai_model_customized_if_got'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_models_customized_if_got); this.setNextStatement(true, null); this.setPreviousStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_models_customized_if_got); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_if_got'] = function (block) { Blockly.Python.addFunction("faceRecognizeShowResult", `def faceRecognizeShowResult(): global BOXES if len(BOXES): for BOXESI, BOXOBJ in enumerate(BOXES): canvas.draw_string((BOXOBJ[0]),(BOXOBJ[1]), ("".join([str(x) for x in [Yolo.labels[PROBS[BOXESI][0]], ";", str(round((PROBS[BOXESI][1][PROBS[BOXESI][0]]*100), 2)) + str("%")]])), scale = 1, color = (255,0,0) , thickness = 1) canvas.draw_rectangle((BOXOBJ[0]),(BOXOBJ[1]), (BOXOBJ[0])+(BOXOBJ[2]),(BOXOBJ[1])+ (BOXOBJ[3]), color=(255,0,0), thickness=1) `) var code = 'faceRecognizeShowResult()\n'; return code; }; Blockly.Blocks['ai_model_customized_attribute'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_model_customized_attribute); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_customized_attribute_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_model_customized_attribute'] = function (block) { var code = 'len(BOXES)'; return [code, Blockly.Python.ORDER_NONE]; }; /* _ ___ ____ _ / \ |_ _| / ___| _ _ ___| |_ ___ _ __ ___ / _ \ | | \___ \| | | / __| __/ _ \ '_ ` _ \ / ___ \ | | ___) | |_| \__ \ || __/ | | | | | /_/ \_\___| |____/ \__, |___/\__\___|_| |_| |_| |___/ */ Blockly.Blocks['ai_system_off'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_off); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_restart_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_system_off = function (block) { Blockly.Python.definitions_['v831_import_os'] = `import os` var _code = `os.system("poweroff") ` return _code; } Blockly.Blocks['ai_system_restart'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_restart); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_off_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_system_restart = function (block) { Blockly.Python.definitions_['v831_import_os'] = `import os` var _code = `os.system("reboot") ` return _code; } Blockly.Blocks['ai_system_refresh'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_refresh); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_refresh_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python.ai_system_refresh = function (block) { Blockly.Python.definitions_['v831_import_os'] = `import os` var _code = `os.system("sync") ` return _code; } Blockly.Blocks['ai_system_volume'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.system_voice) .appendField(new Blockly.FieldNumber(25, 0, 100), "play_vol"); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#22398e"); } } Blockly.Python.ai_system_volume = function (block) { var number_play_vol = block.getFieldValue('play_vol'); Blockly.Python.definitions_['v831_import_os'] = `import os` Blockly.Python.definitions_['systemVoice_numberMap'] = `def voice_numberMap(value): valueScaled = float(value - 0) / float(100) return int(valueScaled * 31) ` var _code = `VOICENUMP = str(voice_numberMap(${number_play_vol})) time.sleep(0.01) SYSTEMVOICE = "amixer cset numid=8,iface=MIXER,name=\\"LINEOUT volume\\" "+ VOICENUMP+"" os.system(SYSTEMVOICE) ` return _code; } Blockly.Blocks['ai_system_thread'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_thread_setting) .appendField(new Blockly.FieldNumber(1, 1, 5), "thread") this.appendStatementInput("input") .setCheck(null) .appendField(Blockly.Msg.basic_motion_statement_exec); this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_thread_setting); this.setHelpUrl(""); } }; Blockly.Python['ai_system_thread'] = function (block) { var threadNum = block.getFieldValue('thread'); var statements_input = Blockly.Python.statementToCode(block, 'input'); Blockly.Python.definitions_['v831_import_threading'] = `import threading` let allBlocks = block.workspace.getAllBlocks(); let global = "" try { global = allBlocks[0].workspace.variableList.toString() } catch (e) { console.log(e) } Blockly.Python.definitions_['v831_import_thread_calsss_fun' + threadNum] = `def thread_calsss_fun${threadNum}(): ${global != "" ? global : ""} ${statements_input} CocoPiThread${threadNum} = threading.Thread(target=thread_calsss_fun${threadNum}) ` var code = ``; return code; }; Blockly.Blocks['ai_system_thread_create_with_container'] = { init: function () { this.setColour("#22398e"); this.appendDummyInput() .appendField(Blockly.Msg.serialcomm_write_item); this.appendStatementInput('STACK'); this.setTooltip(''); this.contextMenu = false; } }; Blockly.Blocks['ai_system_thread_data_create_with_item'] = { init: function () { this.setColour("#22398e"); this.appendDummyInput() .appendField(Blockly.Msg.ai_systen_thread_val); this.setPreviousStatement(true); this.setNextStatement(true); this.setTooltip(''); this.contextMenu = false; } }; Blockly.Blocks['ai_system_thread_set_setDaemon'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_thread_setting).appendField(new Blockly.FieldNumber(1, 1, 5), "thread") .appendField(Blockly.Msg.digital_set_as).appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ai_system_thread_setDaemon, "True"], [Blockly.Msg.ai_system_thread_not_setDaemon, "False"] ]), "setDaemon"); this.setPreviousStatement(true, null); this.setNextStatement(true, null) this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_system_thread_set_setDaemon'] = function (block) { var threadNum = block.getFieldValue('thread'); var queue_value = block.getFieldValue('setDaemon'); var code = `CocoPiThread${threadNum}.setDaemon(${queue_value}) `; return code; }; Blockly.Blocks['ai_system_thread_set_join'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_thread_setting) .appendField(new Blockly.FieldNumber(1, 1, 5), "thread") .appendField(Blockly.Msg.ai_system_thread_set_join) this.setPreviousStatement(true, null); this.setNextStatement(true, null) this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_system_thread_set_join'] = function (block) { var threadNum = block.getFieldValue('thread'); var code = `CocoPiThread${threadNum}.join() `; return code; }; Blockly.Blocks['ai_system_thread_start'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_system_thread).appendField(new Blockly.FieldNumber(1, 1, 5), "thread"); // this.appendStatementInput("input") // .setCheck(null) // .appendField(Blockly.Msg.basic_motion_statement_exec); this.setPreviousStatement(true, null); this.setNextStatement(true, null) this.setColour("#22398e"); this.setTooltip(Blockly.Msg.ai_system_thread_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['ai_system_thread_start'] = function (block) { var threadNum = block.getFieldValue('thread'); // var statements_input = Blockly.Python.statementToCode(block, 'input'); var code = `CocoPiThread${threadNum}.start() `; return code; }; Blockly.Blocks["ai_system_set_queue"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_systen_queue_aritem) this.appendValueInput("queueVaritem") .setCheck(null); this.appendDummyInput().appendField(Blockly.Msg.ai_systen_queue_put) .appendField(new Blockly.FieldDropdown([ ["1", "1"], ["2", "2"], ["3", "3"], ["4", "4"], ["5", "5"] ]), "queue_value"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#22398e"); this.setTooltip(""); } } Blockly.Python['ai_system_set_queue'] = function (block) { var variable_name = Blockly.Python.valueToCode(block, 'queueVaritem', Blockly.Python.ORDER_ATOMIC); // var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); var queue_value = block.getFieldValue('queue_value'); Blockly.Python.definitions_["v831_import_queue"] = `import queue` Blockly.Python.definitions_["v831_import_queue_init" + queue_value] = `queue${queue_value} = queue.Queue()` var code = `queue${queue_value}.put(${variable_name}) `; return code; } Blockly.Blocks["ai_system_get_queue"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_systen_queue_get) .appendField(new Blockly.FieldDropdown([ ["1", "1"], ["2", "2"], ["3", "3"], ["4", "4"], ["5", "5"] ]), "queue_value") .appendField(Blockly.Msg.ai_systen_queue_value); this.setOutput(true, null); this.setColour("#22398e"); this.setTooltip(""); } } Blockly.Python['ai_system_get_queue'] = function (block) { var queue_value = block.getFieldValue('queue_value'); var code = `queue${queue_value}.get()`; return [code, Blockly.Python.ORDER_NONE]; } // 拼音识别 Blockly.Blocks['speech_recognition_phonetic_to_pinyin_setup'] = { init: function () { this.appendDummyInput() .appendField(new Blockly.FieldImage("blockly/media/speech_recognition_header_recognition_new.png", 130, 60, { alt: "*", flipRtl: "FALSE" })); this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_setup); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_setup_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_phonetic_to_pinyin_setup'] = function (block) { Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech` Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr() asr.open("hw:0,0", "/root/preset/drivers/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1") asr.clear() asr_kws_result=[0,0] #获取识别结果及识别概率 similars = [ ["pai3", "ai4"], ["le4", "luo4"], ] def asr_kws(keys): global asr_kws_result tmp = max(keys) asr_kws_result[0] = keys.index(tmp) asr_kws_result[1] = round(tmp,2) ` var code = ""; return code; }; Blockly.Blocks.set_pinyin_dict_create_with_items_insert = { init: function () { this.setColour("#ee783a"); this.appendDummyInput("").appendField(new Blockly.FieldLabel(Blockly.Msg.ai_speech_recognition_setup_pinyin), "TIP"); this.itemCount_ = 3; this.updateShape_(); this.setOutput(!0); this.setMutator(new Blockly.Mutator(["set_pinyin_dict_create_with_item"])); this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone) }, mutationToDom: function () { var a = document.createElement("mutation"); a.setAttribute("items", this.itemCount_); return a }, domToMutation: function (a) { this.itemCount_ = parseInt(a.getAttribute("items"), 10); this.updateShape_() }, decompose: function (a) { var b = a.newBlock("set_pinyin_dict_create_with_container"); b.initSvg(); for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) { var d = a.newBlock("set_pinyin_dict_create_with_item"); d.initSvg(); c.connect(d.previousConnection); c = d.nextConnection } return b }, compose: function (a) { a = a.getInputTargetBlock("STACK"); for (var b = [], c = 0; a;) b[c] = a.valueConnection_, a = a.nextConnection && a.nextConnection.targetBlock(), c++; this.itemCount_ = c; this.updateShape_(); for (c = 0; c < this.itemCount_; c++) b[c] && this.getInput("ADD" + c).connection.connect(b[c]) }, saveConnections: function (a) { a = a.getInputTargetBlock("STACK"); for (var b = 0; a;) { var c = this.getInput("ADD" + b); a.valueConnection_ = c && c.connection; b++; a = a.nextConnection && a.nextConnection.targetBlock() } }, updateShape_: function () { this.getInput("EMPTY") && this.removeInput("EMPTY"); for (var a = [], b = 0; this.getInput("ADD" + b); b++) a.push(this.getFieldValue("KEY" + b)), this.removeInput("ADD" + b); if (0 == this.itemCount_) this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin); else for (this.getField("TIP").setText(Blockly.Msg.ai_speech_recognition_setup_pinyin), b = 0; b < this.itemCount_; b++) this.appendInput_(Blockly.DUMMY_INPUT, "ADD" + b).appendField(new Blockly.FieldTextInput(a.length > b ? a[b] : 0 == b ? "key_0" : "key_" + b), "KEY" + b).appendField(":") .appendField(Blockly.Msg.ai_speech_recognition_setup_tone).appendField(new Blockly.FieldDropdown([ ["1", "1"], ["2", "2"], ["3", "3"], ["4", "4"], ]), "toneADD" + b + b) }, getVars: function () { return [this.getFieldValue("VAR")] }, renameVar: function (a, b) { Blockly.Names.equals(a, this.getFieldValue("VAR")) && this.setTitleValue(b, "VAR") } }; Blockly.Blocks.set_pinyin_dict_create_with_item = { init: function () { this.setColour("#ee783a"); this.appendDummyInput().appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin); this.setPreviousStatement(!0); this.setNextStatement(!0); this.setTooltip(Blockly.Msg.ai_speech_recognition_setup_pinyin); this.contextMenu = !1 } }; Blockly.Blocks.set_pinyin_dict_create_with_container = { init: function () { this.setColour("#ee783a"); this.appendDummyInput().appendField(Blockly.Msg.robot_dog_servo_execution); this.appendStatementInput("STACK"); this.setTooltip(Blockly.Msg.robot_dog_servo_execution); this.contextMenu = !1 } }; Blockly.Python.set_pinyin_dict_create_with_items_insert = function (block) { for (var a = Array(this.itemCount_), b = 0; b < this.itemCount_; b++) { var c = this.getFieldValue("KEY" + b); a[b] = c + block.getFieldValue("toneADD" + b + b); } a = "{" + a.join(", ") + "}"; return [a, Blockly.Python.ORDER_ATOMIC] }; Blockly.Blocks['speech_recognition_phonetic_to_pinyin_set_param'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param); // this.appendValueInput("data") // .setCheck(null) // .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setInputsInline(false); this.setColour("#ee783a"); this.pinyinitemCount_ = 1 this.updateShape_(); this.setMutator(new Blockly.Mutator(["v831_to_pinyin_set_param"])); this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_set_param_TOOLTIP); this.setHelpUrl(""); }, mutationToDom: function () { var a = document.createElement("mutation"); a.setAttribute("items", this.pinyinitemCount_); return a }, domToMutation: function (a) { this.pinyinitemCount_ = parseInt(a.getAttribute("items"), 10); this.updateShape_() }, decompose: function (a) { var b = a.newBlock("v831_to_pinyin_set_param_container"); b.initSvg(); for (var c = b.getInput("STACK").connection, e = 0; e < this.pinyinitemCount_; e++) { var d = a.newBlock("v831_to_pinyin_set_param"); d.initSvg(); c.connect(d.previousConnection); c = d.nextConnection } return b }, compose: function (a) { var b = a.getInputTargetBlock("STACK"); for (a = []; b;) a.push(b.valueConnection_), b = b.nextConnection && b.nextConnection.targetBlock(); for (b = 0; b < this.pinyinitemCount_; b++) { var c = this.getInput("PINYIN" + b).connection.targetConnection; c && -1 == a.indexOf(c) && c.disconnect() } this.pinyinitemCount_ = a.length; this.updateShape_(); for (b = 0; b < this.pinyinitemCount_; b++) Blockly.Mutator.reconnect(a[b], this, "PINYIN" + b) }, saveConnections: function (a) { a = a.getInputTargetBlock("STACK"); for (var b = 0; a;) { var c = this.getInput("PINYIN" + b); a.valueConnection_ = c && c.connection.targetConnection; b++; a = a.nextConnection && a.nextConnection.targetBlock() } }, updateShape_: function () { // this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE); for (var a = 0; a < this.pinyinitemCount_; a++) if (!this.getInput("PINYIN" + a)) { var b = this.appendValueInput("PINYIN" + a); 0 == a && b.appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone) } for (; this.getInput("PINYIN" + a);) this.removeInput("PINYIN" + a), a++ } }; Blockly.Blocks['v831_to_pinyin_set_param'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_setup_pinyin_and_tone); this.setPreviousStatement(true); this.setNextStatement(true); this.setColour("#ee783a") this.setTooltip(''); this.contextMenu = false; } }; Blockly.Blocks['v831_to_pinyin_set_param_container'] = { init: function () { this.setColour("#ee783a"); this.appendDummyInput() .appendField(Blockly.Msg.ARD_SERIAL_SETUP); this.appendStatementInput('STACK'); this.setTooltip(''); this.contextMenu = false; } }; Blockly.Python['speech_recognition_phonetic_to_pinyin_set_param'] = function (block) { // var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_display'] = `from maix import display`; Blockly.Python.definitions_['v831_import_image'] = `from maix import image`; Blockly.Python.definitions_['v831_import_camera'] = `from maix import camera`; Blockly.Python.definitions_["v831_import_maix_speech"] = `import _maix_speech` var a = Array(this.pinyinitemCount_) for (let b = 0; b < this.pinyinitemCount_; b++) { var c = Blockly.Python.valueToCode(this, "PINYIN" + b, Blockly.Python.ORDER_NONE) a[b] = c.slice(1, -1).replaceAll(",", "") } a = a.map(r => [r, 0.1]) Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_setup_def = `asr = _maix_speech.Asr() asr.open("hw:0,0", "/home/ASR/CocoPi_Asr_Model/CocoPi_Asr_Model_V2.1") asr.clear() asr_kws_result=[0,0] #获取识别结果及识别概率 similars = [ ["pai3", "ai4"], ["le4", "luo4"], ] def asr_kws(keys): global asr_kws_result tmp = max(keys) asr_kws_result[0] = keys.index(tmp) asr_kws_result[1] = round(tmp,2) ` // Blockly.Python.definitions_["set_keywords_function"] = `def SetKeywords(data): // dataList = [] // for obj in data: // dataList.append([obj,0.1]) // print(dataList) // return dataList // ` var code = `keywords = ${JSON.stringify(a)} asr.set_kws(keywords, similars, asr_kws) `; return code; }; Blockly.Blocks['speech_recognition_set_pinyin_tone'] = { init: function () { this.appendDummyInput() .appendField("声调").appendField(new Blockly.FieldDropdown([ ["1", "1"], ["2", "2"], ["3", "3"], ["4", "4"], ]), "tone"); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_set_pinyin_tone'] = function (block) { let tone = block.getFieldValue('tone'); console.log(tone) Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult(): global asr_kws_result,keywords if(asr_kws_result[1]!=0): asr_kws_result_list = keywords[asr_kws_result[0]][0] return asr_kws_result_list ` var code = tone; return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['speech_recognition_phonetic_to_pinyin_start_recognition'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_start_recognition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_phonetic_to_pinyin_start_recognition'] = function (block) { var code = "asr.run(1)\n"; return code; }; Blockly.Blocks['speech_recognition_phonetic_to_pinyin_stop_recognition'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_stop_recognition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_phonetic_to_pinyin_stop_recognition'] = function (block) { var code = "asr.exit()\n"; return code; }; Blockly.Blocks['speech_recognition_phonetic_to_pinyin_pause_recognition'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.speech_recognition_phonetic_to_pinyin_pause_recognition_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_phonetic_to_pinyin_pause_recognition'] = function (block) { var code = "asr.clear()\n"; return code; }; Blockly.Blocks['speech_recognition_phonetic_to_pinyin_get_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_speech_recognition_phonetic_to_pinyin_get_result_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['speech_recognition_phonetic_to_pinyin_get_result'] = function (block) { Blockly.Python.definitions_.speech_recognition_phonetic_to_pinyin_start_recognition_def = `def getAsrResult(): global asr_kws_result,keywords if(asr_kws_result[1]!=0): asr_kws_result_list = keywords[asr_kws_result[0]][0] return asr_kws_result_list ` var code = 'getAsrResult()'; return [code, Blockly.Python.ORDER_NONE]; }; // numpy + mnist Blockly.Blocks['Numpy_Neural_Network_init'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_model_init); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_model_init); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_init'] = function (block) { Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`; Blockly.Python.definitions_["v831_import_pickle"] = `import pickle` Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x): return 1/(1+np.exp(-x)) def grad(x): return x*(1-x) class NeuralNetwork: """ 三层全连接前馈神经网络 """ def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1): """ :param inputnodes: 输入层结点数 :param hiddennodes: 隐藏层节点数 :param outputnodes: 输出层节点数 :param learningrate: 学习率 :param active_function: 激活函数 :param gradient: 激活函数的导数 :param lambda_: L2正则化系数 """ self.inputnodes = inputnodes self.hiddennodes = hiddennodes self.outputnodes = outputnodes self.learningrate = learningrate self.active_function = active_function self.gradient = gradient self.lambda_ = lambda_ # 权值矩阵 self.weights_i_h = np.random.rand( self.hiddennodes, self.inputnodes) - 0.5 self.weights_h_o = np.random.rand( self.outputnodes, self.hiddennodes) - 0.5 def train_sgd(self, x, y): """梯度下降训练""" TRAINX = np.array(x).reshape(-1, 1) target = np.zeros((self.outputnodes, 1)) + 0.01 target[y, 0] = 0.99 hiddeninputs = np.dot(self.weights_i_h, TRAINX) hiddenoutputs = self.active_function(hiddeninputs) outputinputs = np.dot(self.weights_h_o, hiddenoutputs) final_outputs = self.active_function(outputinputs) error = target - final_outputs hidden_error = np.dot(self.weights_h_o.transpose(), error) self.weights_h_o += self.learningrate * error * \ np.dot(self.gradient(final_outputs), hiddenoutputs.transpose()) self.weights_i_h += self.learningrate * hidden_error * \ np.dot(self.gradient(hiddenoutputs), TRAINX.transpose()) def fit(self, TRAINX, targets): TRAINX = np.array(TRAINX) for i in range(TRAINX.shape[0]): self.train_sgd(TRAINX[i], targets[i]) def query(self, inputs, debug=False): """单个值预测""" inputs = np.array(inputs).reshape(-1, 1) hidden_input = np.dot(self.weights_i_h, inputs) hidden_output = self.active_function(hidden_input) output_input = np.dot(self.weights_h_o, hidden_output) final_output = self.active_function(output_input) if debug: print("predict: ", final_output) return np.argmax(final_output) def predict(self, inputs): """批量预测""" res = [] for x in inputs: res.append(self.query(x)) return res def __str__(self): return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate) # 用测试数据测试 def accuracy(y_true, y_pred): """准确度""" y_true = np.array(y_true) y_pred = np.array(y_pred) return sum(y_true == y_pred)/y_true.shape[0] # 用全部数据进行训练 def get_data(): # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str) # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str) global train_df, test_df print(train_df.shape) print(test_df.shape) train_data = train_df.astype("int") TRAINX = train_data[:, 1:] TRAINY = train_data[:, 0] TRAINX = TRAINX / 255 * 0.99 + 0.01 test_data = test_df.astype("int") TESTX = test_data[:, 1:] TESTY = test_data[:, 0] TESTX = TESTX / 255 * 0.99 + 0.01 return TRAINX, TRAINY, TESTX, TESTY ` var code = ''; return code; }; Blockly.Blocks['Numpy_Neural_Network_load'] = { init: function () { this.appendDummyInput() .appendField("numpy + mnist 训练模型加载"); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip("numpy + mnist 训练模型加载"); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_load'] = function (block) { Blockly.Python.definitions_['v831_import_numpy_as_np'] = `import numpy as np`; Blockly.Python.definitions_["v831_import_pickle"] = `import pickle` Blockly.Python.definitions_["v831_NeuralNetwork_init"] = `def sigmoid(x): return 1/(1+np.exp(-x)) def grad(x): return x*(1-x) class NeuralNetwork: """ 三层全连接前馈神经网络 """ def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate, active_function=sigmoid, gradient=grad, lambda_=0.1): """ :param inputnodes: 输入层结点数 :param hiddennodes: 隐藏层节点数 :param outputnodes: 输出层节点数 :param learningrate: 学习率 :param active_function: 激活函数 :param gradient: 激活函数的导数 :param lambda_: L2正则化系数 """ self.inputnodes = inputnodes self.hiddennodes = hiddennodes self.outputnodes = outputnodes self.learningrate = learningrate self.active_function = active_function self.gradient = gradient self.lambda_ = lambda_ # 权值矩阵 self.weights_i_h = np.random.rand( self.hiddennodes, self.inputnodes) - 0.5 self.weights_h_o = np.random.rand( self.outputnodes, self.hiddennodes) - 0.5 def train_sgd(self, x, y): """梯度下降训练""" TRAINX = np.array(x).reshape(-1, 1) target = np.zeros((self.outputnodes, 1)) + 0.01 target[y, 0] = 0.99 hiddeninputs = np.dot(self.weights_i_h, TRAINX) hiddenoutputs = self.active_function(hiddeninputs) outputinputs = np.dot(self.weights_h_o, hiddenoutputs) final_outputs = self.active_function(outputinputs) error = target - final_outputs hidden_error = np.dot(self.weights_h_o.transpose(), error) self.weights_h_o += self.learningrate * error * \ np.dot(self.gradient(final_outputs), hiddenoutputs.transpose()) self.weights_i_h += self.learningrate * hidden_error * \ np.dot(self.gradient(hiddenoutputs), TRAINX.transpose()) def fit(self, TRAINX, targets): TRAINX = np.array(TRAINX) for i in range(TRAINX.shape[0]): self.train_sgd(TRAINX[i], targets[i]) def query(self, inputs, debug=False): """单个值预测""" inputs = np.array(inputs).reshape(-1, 1) hidden_input = np.dot(self.weights_i_h, inputs) hidden_output = self.active_function(hidden_input) output_input = np.dot(self.weights_h_o, hidden_output) final_output = self.active_function(output_input) if debug: print("predict: ", final_output) return np.argmax(final_output) def predict(self, inputs): """批量预测""" res = [] for x in inputs: res.append(self.query(x)) return res def __str__(self): return "NeuralNetwork: \\ninput_nodes = {0}, hidden_nodes = {1}, \\noutputnodes = {2}, learningrate = {3}".format(self.inputnodes, self.hiddennodes, self.outputnodes, self.learningrate) # 用测试数据测试 def accuracy(y_true, y_pred): """准确度""" y_true = np.array(y_true) y_pred = np.array(y_pred) return sum(y_true == y_pred)/y_true.shape[0] # 用全部数据进行训练 def get_data(): # train_df = np.loadtxt("mnist_train.csv", delimiter=",", dtype=str) # test_df = np.loadtxt("mnist_test.csv", delimiter=",", dtype=str) global train_df, test_df print(train_df.shape) print(test_df.shape) train_data = train_df.astype("int") TRAINX = train_data[:, 1:] TRAINY = train_data[:, 0] TRAINX = TRAINX / 255 * 0.99 + 0.01 test_data = test_df.astype("int") TESTX = test_data[:, 1:] TESTY = test_data[:, 0] TESTX = TESTX / 255 * 0.99 + 0.01 return TRAINX, TRAINY, TESTX, TESTY ` var code = `#构建神经网络训练服务 TRAINX, TRAINY, TESTX, TESTY = get_data() NN = NeuralNetwork(784, 100, 10, 0.3) NN.fit(TRAINX, TRAINY) y_pred = NN.predict(TESTX) `; return code; }; Blockly.Blocks['Numpy_Neural_Network_LOading_test_train'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_loading_train_and_test_set); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_train_set_url); this.appendValueInput("class_input1") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_test_set_url); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_loading_train_and_test_set); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) { var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str) train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str) `; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['Numpy_Neural_Network_numpy_isStart'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_is_training_start); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_is_training_start); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_numpy_isStart'] = function (block) { // TODO: Assemble Python into code variable. var code = `not os.path.exists("/usr/lib/python3.8/site-packages/numpy/random/__init__.py")`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; Blockly.Blocks['Numpy_Neural_Network_setting_training_argument'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_setting_training_argument); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_input_trait_dimensionality); this.appendValueInput("class_input1") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_number_node); this.appendValueInput("class_input2") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_output_dimensionality); this.appendValueInput("class_input3") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_learning_rate); this.appendValueInput("class_input4") .setCheck(null) .appendField(Blockly.Msg.numpy_mnist_setting_training_argument_frequency); this.appendValueInput("class_input5") .setCheck(null) .appendField(Blockly.Msg.VIDEO_S_S); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_setting_training_argument); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_setting_training_argument'] = function (block) { var class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var class_input1 = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC); var class_input2 = Blockly.Python.valueToCode(block, 'class_input2', Blockly.Python.ORDER_ATOMIC); var class_input3 = Blockly.Python.valueToCode(block, 'class_input3', Blockly.Python.ORDER_ATOMIC); var class_input4 = Blockly.Python.valueToCode(block, 'class_input4', Blockly.Python.ORDER_ATOMIC); var class_input5 = Blockly.Python.valueToCode(block, 'class_input5', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. console.log(Number(class_input.slice(1, -1)), class_input1, class_input2, class_input3) var code = `TRAINX, TRAINY, TESTX, TESTY = get_data() NN = NeuralNetwork(${Number(class_input.slice(1, -1))}, ${Number(class_input1.slice(1, -1))}, ${Number(class_input2.slice(1, -1))}, ${Number(class_input3.slice(1, -1))}) #开启神经网络训练,记录时长 AccuracyRATE = 0 # 训练10次,每3次训练下降一次学习率 for e in range(1, ${Number(class_input4.slice(1, -1)) + 1}): if e % 3 == 0: NN.learningrate /= 2 NN.fit(TRAINX, TRAINY) y_pred = NN.predict(TESTX) CURRENTACCURACY = accuracy(TESTY, y_pred) if CURRENTACCURACY > AccuracyRATE: AccuracyRATE = CURRENTACCURACY #文件已保存至 with open(${class_input5}, "wb") as f: # 保存模型 pickle.dump(pickle.dumps(NN), f) os.system("touch /usr/lib/python3.8/site-packages/numpy/random/__init__.py") `; // TODO: Change ORDER_NONE to the correct strength. return code; }; // Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_loading_model); this.appendValueInput("class_input") .setCheck(null) .appendField(Blockly.Msg.AUDIO_S_PF); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_loading_model); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_numpy_loading_model'] = function (block) { var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = `try: with open(${trainUrl},"rb") as f: b_data = pickle.load(f) net_model = pickle.loads(b_data) except: pass `; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Python['Numpy_Neural_Network_LOading_test_train'] = function (block) { var trainUrl = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC); var testUrl = Blockly.Python.valueToCode(block, 'class_input1', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = `test_df = np.loadtxt(${testUrl}, delimiter=",", dtype=str) train_df = np.loadtxt(${trainUrl}, delimiter=",", dtype=str) `; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_fun'] = { init: function () { // this.appendDummyInput() // .appendField("获取检测结果"); this.appendDummyInput() .appendField("在屏幕中显示numpy的检测结果") this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.ai_model_getclass_TOOLTIP); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_numpy_loading_model_fun'] = function (block) { Blockly.Python.definitions_["v831_import_PIL_image"] = `from PIL import Image` Blockly.Python.definitions_["v831_function_numpy_result"] = `def numpyResult(img): img_path="/root/user/image_1.png" img_gray_path="/root/user/image_gray.png" mk = img.crop(0, 0, 240, 240) #裁剪图像为320*240 mk1=img.crop(0, 0, 240, 240).resize(224,224) #继续裁剪图像为224*224 numpyResultcanvas= image.new(size = (320, 240), color = (0,255,0), mode = 'RGB') #创建背景图 numpyResultcanvas.draw_image(mk1.rotate(90,adjust=1),58,8) #贴224*224的图片 mk2=mk1.resize(28,28) #裁剪图片为28*28 numpyResultcanvas.draw_image(mk2,8,8) #贴28*28的图 mk2.save(img_path) origin=Image.open(img_path).convert('L') #转为8位分辨率灰度图(0~255) origin.save(img_gray_path) origin_gray=image.open(img_gray_path) numpyResultcanvas.draw_image(origin_gray,8,48) numpyResultImg = np.array(origin).reshape(1, 784).astype('int') numpyResultImg = numpyResultImg / 255 * 0.99 + 0.01 print(numpyResultImg.shape) result = net_model.query(numpyResultImg) return result ` // TODO: Assemble Python into code variable. var code = `canvas = canvas.crop(48,8,224,224) GETNUMPYRESULT = numpyResult(canvas) if GETNUMPYRESULT != "": canvas.draw_string(0,0, (str(GETNUMPYRESULT)), scale = 3, color = (204,204,204) , thickness = 1) else: canvas.draw_string(0,0, ("None"), scale = 3, color = (204,204,204) , thickness = 1) `; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks['Numpy_Neural_Network_numpy_loading_model_result'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_get_result); this.setOutput(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_get_result); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_numpy_loading_model_result'] = function (block) { var code = `GETNUMPYRESULT`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_NONE]; }; // Blockly.Blocks['Numpy_Neural_Network_numpy_clear'] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.numpy_mnist_clear); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#ee783a"); this.setTooltip(Blockly.Msg.numpy_mnist_clear); this.setHelpUrl(""); } }; Blockly.Python['Numpy_Neural_Network_numpy_clear'] = function (block) { var code = `os.system('rm -rf /usr/lib/python3.8/site-packages/numpy/random/__init__.py') `; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks["cocopi_chatGpt_init"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_init); // this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_init); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_init'] = function (block) { Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = ``; // TODO: Change ORDER_NONE to the correct strength. return code; }; Blockly.Blocks["cocopi_chatGpt_text_to_img_loading"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_img_des); this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_img_path_result); this.setOutput(true, null); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_set_img_des); this.setInputsInline(false) this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_text_to_img_loading'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` // Blockly.Python.addVariable("TextContent", `TextContent = ""`, true) var code = `gptInit.get_text_to_img(${text})`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks["cocopi_chatGpt_image_to_text_loading"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_text_path); this.appendValueInput("NAME1") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_text_text_content); this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_text_content_result); this.setOutput(true, null); this.setInputsInline(false); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_set_text_path); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_image_to_text_loading'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = `gptInit.get_image_to_text(${text},${content})`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks["cocopi_chatGpt_text_to_voice_loading"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_text_content); this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_voice_path_result); this.setOutput(true, null); this.setInputsInline(false); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_text_to_voice_loading'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = `gptInit.get_text_to_voice(${text})`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks["cocopi_chatGpt_text_to_voice_result"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_voice_path_result); this.setOutput(true, null); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_get_voice_path_result); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_text_to_voice_result'] = function (block) { var code = `gptInit.get_text_to_voice(VOICECONTENT)`; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks["cocopi_chatGpt_voice_to_text_loading"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_voice_path); this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_voice_text_content_result); this.setOutput(true, null); this.setInputsInline(false) this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_set_voice_path); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_voice_to_text_loading'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = `gptInit.get_voice_to_text(${text})`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks["cocopi_chatGpt_post_chatgpt_loading"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_problem_content); this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_problem_result); this.setOutput(true, null); this.setInputsInline(false) this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_set_problem_content); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_post_chatgpt_loading'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = `gptInit.get_post_chatgpt(${text})`; // TODO: Change ORDER_NONE to the correct strength. return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks["cocopi_chatGpt_post_chatgpt_result"] = { init: function () { this.appendDummyInput() .appendField(Blockly.Msg.ChatGpt_get_problem_result); this.setOutput(true, null); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_post_chatgpt_result'] = function (block) { var code = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)`; return [code, Blockly.Python.ORDER_ATOMIC];; }; // Blockly.Blocks["cocopi_chatGpt_result"] = { init: function () { this.appendDummyInput() // .appendField(Blockly.Msg.ChatGpt_get_problem_result) .appendField(new Blockly.FieldDropdown([ [Blockly.Msg.ChatGpt_get_img_path_result, "1"], [Blockly.Msg.ChatGpt_get_text_content_result, "2"], [Blockly.Msg.ChatGpt_get_voice_path_result, "3"], [Blockly.Msg.ChatGpt_get_voice_text_content_result, "4"], [Blockly.Msg.ChatGpt_get_problem_result, "5"], [Blockly.Msg.ChatGpt_ai_agent_chat_result, "6"] ]), "gpt_return"); this.setOutput(true, null); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_get_problem_result); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_result'] = function (block) { var queue_value = block.getFieldValue('gpt_return'); Blockly.Python.addVariable("CocoPiGPTRESULT", `CocoPiGPTRESULT = None`, true) var res = ``; if (queue_value == 5) { res = `gptInit.get_post_chatgpt(CHATGPTPROBLEM)` } else if (queue_value == 4) { res = `gptInit.get_voice_to_text(VOICEPATH)` } else if (queue_value == 3) { res = `gptInit.get_text_to_voice(VOICECONTENT)` } else if (queue_value == 2) { res = `gptInit.get_image_to_text(IMAGEPATH,IMAGECONTENT)` } else if (queue_value == 1) { res = `gptInit.get_text_to_img(TextContent)` } else if (queue_value == 6) { res = `gptInit.get_post_AI_Intelligence(AIAGENTCHATID,AIAGENTCHATMESSAGE)` } Blockly.Python.definitions_["CocoPiGPTRESULTFUNC"] = `def CocoPiGPTRESULTFUNC(res): global CocoPiGPTRESULT try: CocoPiGPTRESULT = res except: CocoPiGPTRESULT = "" return CocoPiGPTRESULT ` var code = `CocoPiGPTRESULTFUNC(${res})`; return [code, Blockly.Python.ORDER_ATOMIC];; }; Blockly.Blocks["cocopi_chatGpt_AI_loading"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID); this.appendValueInput("NAME1") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_problem_content); this.appendDummyInput().appendField(Blockly.Msg.ChatGpt_ai_agent_chat_result) this.setOutput(true, null); this.setInputsInline(false); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_set_text_path); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_AI_loading'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC); var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = `gptInit.get_post_AI_Intelligence(${text},${content})` return [code, Blockly.Python.ORDER_ATOMIC]; }; // Blockly.Blocks["cocopi_chatGpt_AI_loading_more"] = { init: function () { this.appendValueInput("NAME") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_ai_agent_chat_set_appID_more); this.appendValueInput("NAME1") .setCheck(null) .appendField(Blockly.Msg.ChatGpt_set_problem_content); this.appendDummyInput().appendField(Blockly.Msg.ChatGpt_ai_agent_chat_result_more) this.setOutput(true, null); this.setInputsInline(false); this.setColour("#7e3cca"); this.setTooltip(Blockly.Msg.ChatGpt_set_text_path); this.setHelpUrl(""); } }; Blockly.Python['cocopi_chatGpt_AI_loading_more'] = function (block) { var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); var content = Blockly.Python.valueToCode(block, 'NAME1', Blockly.Python.ORDER_ATOMIC); var text = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC); Blockly.Python.definitions_['v831_import_sys'] = `import sys sys.path.append("/root/")` Blockly.Python.definitions_['v831_import_CocoPi_Gpt'] = `try: from CocoPi import GPTrequest except: import sys sys.path.append("/home/drivers/pylib/") from GPTrequest import GPTrequest` Blockly.Python.definitions_['v831_import_CocoPi_Gpt_init'] = `gptInit = GPTrequest()` var code = `gptInit.cocopi_chatGpt_AI_loading_more(${text},${content})` // Blockly.Python.definitions_['v831_import_requests'] = `import requests` // Blockly.Python.definitions_['v831_import_json'] = `import json` // Blockly.Python.definitions_['v831_import_os'] = `import os` // Blockly.Python.definitions_['v831_import_time'] = `import time` // Blockly.Python.addFunction("cocopi_chatGpt_AI_loading_more", `def cocopi_chatGpt_AI_loading_more(appID,content): // url = "https://gpt4.cocorobo.cn/handle_muti_agent" // headers={ // "Content-Type":"application/json", // } // cmd="cat /sys/class/sunxi_info/sys_info" // rec=os.popen(cmd).read() // hwMac=rec[rec.find("sunxi_serial : ")+20:rec.find("sunxi_serial : ")+52] // params = { // "muti_agent_id":appID, // "message":content, // "userId":"602def61-005d-11ee-91d8-005056b86db5", // "session_name":"0606" // } // textContent = "" // res = requests.post(url, headers=headers, data=json.dumps(params)) // try: // textContent = json.loads(res.text)["FunctionResponse"]["response"] // except: // textContent = "" // return textContent // `, true) return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Blocks.tuple_create_with_items_inserts = { init: function () { this.setHelpUrl(Blockly.Msg.TUPLE_CREATE_WITH_ITEMS_INSERT_HELPURL); this.setColour("#ee783a"); this.itemCount_ = 3; this.updateShape_(); this.setOutput(!0); this.setMutator(new Blockly.Mutator(["tuple_create_with_items"])); this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_ITEMS_INSERT_TOOLTIP) }, mutationToDom: function () { var a = document.createElement("mutation"); a.setAttribute("items", this.itemCount_); return a }, domToMutation: function (a) { this.itemCount_ = parseInt(a.getAttribute("items"), 10); this.updateShape_() }, decompose: function (a) { var b = a.newBlock("tuple_create_with_containers"); b.initSvg(); for (var c = b.getInput("STACK").connection, e = 0; e < this.itemCount_; e++) { var d = a.newBlock("tuple_create_with_items"); d.initSvg(); c.connect(d.previousConnection); c = d.nextConnection } return b }, compose: function (a) { var b = a.getInputTargetBlock("STACK"); for (a = []; b;) a.push(b.valueConnection_), b = b.nextConnection && b.nextConnection.targetBlock(); for (b = 0; b < this.itemCount_; b++) { var c = this.getInput("ADD" + b).connection.targetConnection; c && -1 == a.indexOf(c) && c.disconnect() } this.itemCount_ = a.length; this.updateShape_(); for (b = 0; b < this.itemCount_; b++) Blockly.Mutator.reconnect(a[b], this, "ADD" + b) }, saveConnections: function (a) { a = a.getInputTargetBlock("STACK"); for (var b = 0; a;) { var c = this.getInput("ADD" + b); a.valueConnection_ = c && c.connection.targetConnection; b++; a = a.nextConnection && a.nextConnection.targetBlock() } }, updateShape_: function () { this.itemCount_ && this.getInput("EMPTY") ? this.removeInput("EMPTY") : this.itemCount_ || this.getInput("EMPTY") || this.appendDummyInput("EMPTY").appendField(Blockly.Msg.TUPLE_CREATE_EMPTY_TITLE); for (var a = 0; a < this.itemCount_; a++) if (!this.getInput("ADD" + a)) { var b = this.appendValueInput("ADD" + a); 0 == a && b.appendField(Blockly.Msg.TUPLE_CREATE_WITH_INPUT_WITH) } for (; this.getInput("ADD" + a);) this.removeInput("ADD" + a), a++ } }; Blockly.Blocks.tuple_create_with_items = { init: function () { this.setColour("#ee783a"); this.appendDummyInput().appendField(Blockly.Msg.TUPLE_CREATE_WITH_ITEM_TITLE); this.setPreviousStatement(!0); this.setNextStatement(!0); this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_ITEM_TOOLTIP); this.contextMenu = !1 } }; Blockly.Blocks.tuple_create_with_containers = { init: function () { this.setColour("#ee783a"); this.appendDummyInput().appendField(Blockly.Msg.TUPLE_CREATE_WITH_CONTAINER_TITLE_ADD); this.appendStatementInput("STACK"); this.setTooltip(Blockly.Msg.TUPLE_CREATE_WITH_CONTAINER_TOOLTIP); this.contextMenu = !1 } }; Blockly.Python.tuple_create_with_items_inserts = function (a) { for (var b = Array(a.itemCount_), c = 0; c < a.itemCount_; c++) b[c] = Blockly.Python.valueToCode(a, "ADD" + c, Blockly.Python.ORDER_NONE) || "None"; return [1 == a.itemCount_ ? "(" + b[0] + ",)" : "(" + b.join(", ") + ")", Blockly.Python.ORDER_ATOMIC] };