コード例 #1
0
ファイル: speech_conversion.py プロジェクト: Monsets/Eva
def recognize():
    set = SettingsEva()
    met = set.get_method()
    if check_internet_connection():
        text, filename = recognition_google()
        print("GOOGLE: {}".format(text))
        system = "google"
    else:
        return None
    return (text, system, filename, met)
コード例 #2
0
 def show_output1(self):
     self.__is_working = True
     self.set_button_to_waiting_mode()
     try:
         set = SettingsEva()
         set.save_method(1)
         command = recognize_and_execute(self.modules)
         self.indicator.chg_icon('green')
     except Exception as e:
         command = e.args[0]
         self.indicator.chg_icon('red')
     self.indicator.show_msg(command)
     self.set_button_to_normal_mode()
     self.__is_working = False
コード例 #3
0
ファイル: text_to_command.py プロジェクト: Monsets/Eva
def recognize_and_execute(modules):
    his = History()
    path = "./Application/History/Audio/"
    try:
        text = recognize()
    except Exception as e:
        print("Error: ", e.args)
        print("Речь не распознана")
        dir_list = [os.path.join(path, x) for x in os.listdir(path)]
        set = SettingsEva()
        if dir_list:
            # Создадим список из путей к файлам и дат их создания.
            date_list = [[x, os.path.getctime(x)] for x in dir_list]

            # Отсортируем список по дате создания в обратном порядке
            sort_date_list = sorted(date_list, key=lambda x: x[1], reverse=True)

            # Выведем первый элемент списка. Он и будет самым последним по дате
            lastfile = sort_date_list[0][0]
        mtd = set.get_method()
        his.save_params("Речь не распознана", lastfile, "Речь не распознана", mtd, "Речь не распознана")
        raise NameError("Речь не распознана")
    print(text)
    textComand = text[0]
    print("DEBUG recognized command: {}".format(textComand))
    try:
        path, args = modules.get_command_params(textComand)
        his.save_params(text[0], text[2], format(textComand), text[3], text[1])
    except:
        print("Команда {} не найдена!".format(text))
        his.save_params(text[0], text[2], "Команда не найдена!", text[3], text[1])
        raise ModuleNotFoundError("Команда {} не найдена".format(textComand))
    try:
        modules.execute_script(path, args)
    except FileNotFoundError:
        print("Скрипт не найден")
        raise FileNotFoundError("Скрипт не найден")
    except PermissionError:
        print("Нет прав для выполнения скрипта")
        raise PermissionError("Нет прав для выполнения скрипта")


    return text[0]
コード例 #4
0
 def show_output0(self):
     self.__is_working = True
     self.set_button_to_waiting_mode()
     self.indicator.chg_icon("yellow")
     try:
         set = SettingsEva()
         set.save_method(0)
         command = recognize_and_execute(self.modules)
         self.mini_ui.Button_Recognize.setStyleSheet(self.green_button)
         self.indicator.chg_icon('green')
     except Exception as e:
         command = e.args[0]
         self.mini_ui.Button_Recognize.setStyleSheet(self.red_button)
         self.indicator.chg_icon('red')
     self.mini_ui.Text_RecognizedCommand.setText(command)
     self.indicator.show_msg(command)
     self.set_button_to_normal_mode()
     self.__is_working = False
     self.indicator.call_for_recognize = False
コード例 #5
0
def main():
    app = QtWidgets.QApplication(sys.argv)  # Новый экземпляр QApplication
    modules = init_modules('Modules')
    settings = SettingsEva()
    mini_app = MiniApp(settings, modules)
    window = EvaApp(mini_app, modules)  # Создаём объект класса
    window.show()  # Показываем окно
    mini_app.show()
    mini_app.window = window
    app.exec_()  # и запускаем приложение
コード例 #6
0
    def save_setings(self):
        self.settingsEva = SettingsEva()
        # Сохранение значения слайдера громкости микрофона
        self.settingsEva.slider_micro(self.ui.Slider_Micro_Volume)
        # Сохранение состояния чекбокса "Горячая клавиша"
        self.settingsEva.CheckBox_HotKey(self.ui.CheckBox_HotKey)
        # Сохранение состояния чекбокса "Ключевое слово"
        self.settingsEva.CheckBox_KeyWork(self.ui.CheckBox_KeyWork)
        # Сохранение значения слайдера размера шрифта
        self.settingsEva.slider_font(self.ui.horizontalSlider, 50)
        # Сохранение состояния чекбокса "Включить вывод текста на экран"
        self.settingsEva.ToggleSlider_TextNotify(
            self.ui.ToggleSlider_TextNotify, 1)
        # Сохранение состояния чекбокса "Включить звуковое оповещение"
        self.settingsEva.ToggleSlider_SoundNotify(
            self.ui.ToggleSlider_SoundNotify, 1)

        self.settingsEva.HotKey_Choosen(self.ui.HotKey_Choosen)

        self.settingsEva.Slider_Micro_Kws_Threshold(
            self.ui.Slider_Micro_Kws_Threshold)

        self.ui.Slider_Micro_Kws_Threshold.valueChanged.connect(self.chg_tws)
コード例 #7
0
class EvaApp(QtWidgets.QMainWindow):
    def __init__(self, mini_app, modules):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле generated_design.py
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.mini_app = mini_app
        # временное решение
        self.init_text_constants()

        self.init_navigation_buttons()
        self.modules = modules
        # Fill in module's page tabl
        self.init_modules_table()
        self.init_history_table()
        # Save settings
        self.save_setings()

    def init_navigation_buttons(self):
        self.ui.settings_button_widget.hide()
        self.menu_buttons = self.get_menu_buttons()
        self.bound_menu_buttons()

    def closeEvent(self, event):
        """docstring"""
        #self.mini_app.show()
        #self.mini_app.pass_info(self)
        pass

    def init_text_constants(self):
        self.modules_path = "./Modules"
        self.no_module_info = "Информация о модуле не найдена!"

    def save_setings(self):
        self.settingsEva = SettingsEva()
        # Сохранение значения слайдера громкости микрофона
        self.settingsEva.slider_micro(self.ui.Slider_Micro_Volume)
        # Сохранение состояния чекбокса "Горячая клавиша"
        self.settingsEva.CheckBox_HotKey(self.ui.CheckBox_HotKey)
        # Сохранение состояния чекбокса "Ключевое слово"
        self.settingsEva.CheckBox_KeyWork(self.ui.CheckBox_KeyWork)
        # Сохранение значения слайдера размера шрифта
        self.settingsEva.slider_font(self.ui.horizontalSlider, 50)
        # Сохранение состояния чекбокса "Включить вывод текста на экран"
        self.settingsEva.ToggleSlider_TextNotify(
            self.ui.ToggleSlider_TextNotify, 1)
        # Сохранение состояния чекбокса "Включить звуковое оповещение"
        self.settingsEva.ToggleSlider_SoundNotify(
            self.ui.ToggleSlider_SoundNotify, 1)

        self.settingsEva.HotKey_Choosen(self.ui.HotKey_Choosen)

        self.settingsEva.Slider_Micro_Kws_Threshold(
            self.ui.Slider_Micro_Kws_Threshold)

        self.ui.Slider_Micro_Kws_Threshold.valueChanged.connect(self.chg_tws)

    def chg_tws(self, value):
        self.ui.label_tws.setText("Порог распознавания: 1e-" + str(value))

    def get_menu_buttons(self):
        buttons = [
            self.ui.Button_History,
            self.ui.Button_Settings,
            self.ui.Button_Settings_Micro,
            self.ui.Button_Settings_Notify,
            self.ui.Button_Modules,
            self.ui.Button_Settings_Interface,
            self.ui.Button_About,
        ]
        return buttons

    """History page events"""

    def init_history_table(self):
        history_PATH = "./Application/History/history.xml"
        if not os.path.exists(history_PATH):
            History.init_file(self)
        scroll = self.ui.ScrollArea_History
        scroll.setStyleSheet('border: null')
        scroll.setWidget(self.ui.ListWidget_History)
        list = self.ui.ListWidget_History

        self.ui.ListWidget_History.setStyleSheet(
            'QListWidget::item { border: 1px solid; margin-bottom: 1px   }')
        list.setMinimumWidth(list.sizeHintForColumn(0))

        with open(history_PATH) as fobj:
            xml = fobj.read()
        root = etree.fromstring(xml)
        element = ""
        #        row = CustomQWidget()
        for appt in root.getchildren():
            pathf = ""
            textf = ""
            commandf = ""
            methodf = ""
            systemf = ""
            datef = ""
            row = None
            for elem in appt.getchildren():
                if elem.text == 'History/testID':
                    break
                else:
                    if elem.tag == "path":
                        pathf = elem.text
                    elif elem.tag == "text":
                        textf = elem.text
                    elif elem.tag == "command":
                        commandf = elem.text
                    elif elem.tag == "method":
                        methodf = elem.text
                    elif elem.tag == "system":
                        systemf = elem.text
                    elif elem.tag == "date":
                        datef = elem.text
                row = CustomQWidget(pathf, textf, commandf, methodf, systemf,
                                    datef)
            if elem.text != 'History/testID':
                item = QListWidgetItem(list)
                item.setSizeHint(row.minimumSizeHint())
                list.setItemWidget(item, row)
        # click on item
        self.ui.ListWidget_History.itemClicked.connect(self.play_sound)

    def play_sound(self):
        rowId = self.ui.ListWidget_History.currentIndex().row()
        HISTORY_PATH = "./Application/History/history.xml"
        with open(HISTORY_PATH) as f:
            xml = f.read()
        root = objectify.fromstring(xml)
        sounds = []
        for appt in root.getchildren():
            sounds.append(appt.getchildren()[0])
        subprocess.Popen(["aplay", str(sounds[rowId + 1])])

    """Module page events"""

    def init_modules_table(self):
        # add modules to table
        for module in self.modules:
            self.ui.ListWidget_ModuleNames.addItem(
                QtWidgets.QListWidgetItem(module.module_name))
        # click on item
        self.ui.ListWidget_ModuleNames.itemClicked.connect(
            self.change_info_module)
        self.ui.ListWidget_ModuleCommands.itemClicked.connect(
            self.change_info_command)

    def change_info_module(self):
        # clear table
        self.ui.ListWidget_ModuleCommands.clear()
        # chosen item
        module = self.modules[
            self.ui.ListWidget_ModuleNames.currentIndex().row()]
        # change commands table
        for command in module.commands.keys():
            self.ui.ListWidget_ModuleCommands.addItem(
                QtWidgets.QListWidgetItem(command))

    def change_info_command(self):
        module = self.modules[
            self.ui.ListWidget_ModuleNames.currentIndex().row()]
        command = module.commands[list(module.commands.keys())[
            self.ui.ListWidget_ModuleCommands.currentIndex().row()]]
        info = ""
        for attr in command.keys():
            if attr == "path":
                continue
            info += attr + " : " + command[attr] + "\n"
        self.ui.Label_CommandInfo.setText(info)

    """Buttons events"""

    def bound_menu_buttons(self):
        self.ui.Button_History.clicked.connect(self.display_history_page)
        self.ui.Button_Settings.clicked.connect(self.display_settings)
        self.ui.Button_Settings_Micro.clicked.connect(
            self.display_settings_micro)
        self.ui.Button_Settings_Notify.clicked.connect(
            self.display_settings_notify)
        self.ui.Button_Modules.clicked.connect(self.display_modules_page)
        self.ui.Button_Settings_Interface.clicked.connect(
            self.display_settings_interface)
        self.ui.Button_About.clicked.connect(self.display_about_page)
        self.ui.exit_Button.clicked.connect(self.quit_app)

    def set_button_colors(self, clicked_button):
        # sets buttons bakground color to app's standart
        for button in self.menu_buttons:
            button.setStyleSheet(
                "background-color: rgb(65,105,225); color: white;border: none;font:  17px ;text-align:left;"
            )
        # highlight clicked button
        clicked_button.setStyleSheet(
            "background-color: rgb(30,144,255); color: white;border: none;font:  17px ;text-align:left;"
        )

    def quit_app(self):
        os.kill(os.getpid(), signal.SIGKILL)

    def display_settings(self):
        self.set_button_colors(self.ui.Button_Settings)
        self.ui.settings_button_widget.show()

    def display_modules_page(self):
        self.set_button_colors(self.ui.Button_Modules)
        # hide setting's buttons
        self.ui.settings_button_widget.hide()
        # change page at the right part of app
        self.ui.stackedWidget.setCurrentIndex(1)

    def display_history_page(self):
        self.set_button_colors(self.ui.Button_History)
        self.ui.settings_button_widget.hide()
        self.ui.stackedWidget.setCurrentIndex(0)

    def display_settings_micro(self):
        self.set_button_colors(self.ui.Button_Settings_Micro)
        self.ui.stackedWidget.setCurrentIndex(2)

    def display_settings_notify(self):
        self.set_button_colors(self.ui.Button_Settings_Notify)
        self.ui.stackedWidget.setCurrentIndex(3)

    def display_settings_interface(self):
        self.set_button_colors(self.ui.Button_Settings_Interface)
        self.ui.stackedWidget.setCurrentIndex(4)

    def display_about_page(self):
        self.set_button_colors(self.ui.Button_About)
        self.ui.settings_button_widget.hide()
        self.ui.stackedWidget.setCurrentIndex(5)