Y
Y
Yura Milevsky2021-11-08 20:54:54
Python
Yura Milevsky, 2021-11-08 20:54:54

Why does not see the path / executable?

I have a voice assistant. Why is it not getting data from the input field?

Kernel code
from DataBase_0_2_0 import *
import GUI
import json
import pyttsx3
import os
import sys
import speech_recognition as sr
import time
import datetime
from fuzzywuzzy import fuzz
#import tkinter as tk
#from PIL import ImageTk, Image
import webbrowser as wb

filename = "settings.json"
Program1way = ""
Program2way = ""

#=============================================================Датабаза
def _save(settings):
    with open (filename, 'w', encoding='utf-8') as f:
        json.dump(settings, f, indent = 4, ensure_ascii = False)
        f.close()       
 
def _getDate():
    with open (filename, 'r', encoding='utf-8') as f:
        load = json.load(f)
        dates = list(load.values())
        return dates
        f.close() 

#==============================================================

#=========================================================== Ход работы

#    def _from_rgb(rgb): # Для работы TKinter
#        return "#%02x%02x%02x" % rgb

#    error = 0
#    root = tk.Tk() # Задаем новое окно

#    root.geometry('400x500') # Определяем размеры
#    root.resizable(width=False, height=False) # Закрепляем размеры
#    root.title("Голосовой ассистент Юля")

#======= Непонятный код ======

#    image = Image.open("Background.png")
#    width = 500
#    ratio = (width / float(image.size[0]))
#    height = int((float(image.size[1]) * float(ratio)))
#    image = image.resize((width, height), Image.ANTIALIAS)
#    image = ImageTk.PhotoImage(image)
#    canvas = tk.Canvas(root, width=width, height=height)
#    canvas.pack(side="top", fill="both", expand="no")
#    canvas.create_image(0, 0, anchor="nw", image=image)

#==============================

#    canvas.create_text(200, 25, text="Юлия 0.2.0", fill="Purple", font='Helvetica 30') # Текст
#    canvas.create_text(200, 50, text="Голосовой помощник, созданный для помощи", fill="Purple", font='Times 13') # Текст
#    Program = tk.Entry(root, width=61)
#    Program2 = tk.Entry(root, width=61)
#    canvas.create_text(200, 75, text="Программа №1", fill="Purple", font='Times 13')
#    canvas.create_window((10, 85), anchor="nw", window=Program)
#    canvas.create_text(200, 115, text="Программа №2", fill="Purple", font='Times 13')
#    canvas.create_window((10, 125), anchor="nw", window=Program2) 

#    Program1way = ""
#    Program2way = ""
#    root = tk.mainloop() # Запуск окна

#===========================================================



def speak(what): # Сказать
    print(what)
    x = pyttsx3.init()
    x.say(what)
    x.runAndWait()
    x.stop()

def hear(): # Записать
    global error
    r = sr.Recognizer()
    try:
        with sr.Microphone() as source:  # Запись аудио
            r.adjust_for_ambient_noise(source, duration=0.6)  # шумоподавление
            print("Скажите что-нибудь: ")
            audio = r.listen(source)
        text = r.recognize_google(audio, language="ru-RU") # Преобразование речи в текст
        error = 0 # Возвращает 0 в ложные запросы
        return text.lower()  # Возврат

    except:
        return hear()

def debug_Mode(): # Режим отладки
    speak("Введи ключ доступа")
    cod = input("--> ")
    if cod == "2004":
        speak("Запускаю режим отладки")
        print("=" * 40)
        mod = True
    else:
        speak("Ошибка доступа")

    while mod == True:
        zapros = hear()
        print("[log]:" + zapros)
        if zapros == "выход":
            mod = False
            speak("закрываю режим отладки")
            print("=" * 40)

def Search(zapros): # Функция поиска
    speak("Открываю в поиске: " + zapros)
    url = "https://www.google.ru/search?q=" + zapros
    wb.open_new(url)
    play = False

def main(): # Главная функция
    settings = {}
    date = _getDate()

    speak("Здравствуй, я голосовой ассистент Юля. Версия 0.2.0. Не закрывайте окно, иначе вам нужно будет перезапустить меня чтобы его вернуть.")

    while True: # Главный цикл

        request = hear() # Прослушмваем

        result = [key for key, val in database.items() if request in val]  # Проверяем наличие нашего запроса в базе, помещаем ответ в переменную
        result = "".join(result)  # Преобразуем список в строку

        if result:

            if result == "Режим отладки":
                debug_Mode()

            elif result == exit_:
                speak(result)
                os.system("TASKKILL /F /IM python.exe")

            elif result == Real_Need:
                speak(result)

            elif result == Your_History:
                speak(result)

            elif result == Program1:
                #global Program1way
                Program1way = GUI.Program.get() <-- ВОТ ПРОБЛЕМНОЕ МЕСТО!!!!! АЛАРМ, АЛЕРТ,  ЗЫРЬТЕ СЮДЫ!!!
                settings['Program1way'] = str(Program1way)
                _save(settings)
                speak(result)
                print(Program1way)

            elif result == Program1Start:
                #global Program1way
                os.startfile(Program1way)
                speak(result)

            elif result == Program2:
                #global Program2way
                Program2way = GUI.Program2.get() <-- ВОТ  ВТОРОЕ ПРОБЛЕМНОЕ МЕСТО!!! АЛАРМ, АЛЕРТ, ЗЫРЬТЕ И СЮДЫ ТОЖЕ!
                settings['Program2way'] = Program2way
                _save(settings)
                speak(result)

            elif result == Program2Start:
                #global Program2way
                os.startfile(Program2way)
                speak(result)

            elif result == FindIt:
                speak("Скажите запрос")
                Findit = hear()
                Search(Findit)

            elif result == Csgo:
                speak(result)
                os.startfile("steam://rungameid/730")

            elif result == Check:
                speak(result)

            else:
                speak(result)
        else:
            speak("Команда не распознана")
            continue
main()
#==========================================================

Here is the tkinter code:
Tkinter code
import tkinter as tk
from PIL import ImageTk, Image


def _from_rgb(rgb):
    return "#%02x%02x%02x" % rgb #Для работы Tkinter

error = 0
root = tk.Tk() # Задаем новое окно

root.geometry('400x500') # Определяем размеры
root.resizable(width=False, height=False) # Закрепляем размеры
root.title("Голосовой ассистент Юля")

#======= Непонятный код ======

image = Image.open("Background.png")
width = 500
ratio = (width / float(image.size[0]))
height = int((float(image.size[1]) * float(ratio)))
image = image.resize((width, height), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
canvas = tk.Canvas(root, width=width, height=height)
canvas.pack(side="top", fill="both", expand="no")
canvas.create_image(0, 0, anchor="nw", image=image)

#==============================

canvas.create_text(200, 25, text="Юлия 0.2.0", fill="Purple", font='Helvetica 30') # Текст
canvas.create_text(200, 50, text="Голосовой помощник, созданный для помощи", fill="Purple", font='Times 13') # Текст
Program = tk.Entry(root, width=61)
Program2 = tk.Entry(root, width=61)
canvas.create_text(200, 75, text="Программа №1", fill="Purple", font='Times 13')
canvas.create_window((10, 85), anchor="nw", window=Program)
canvas.create_text(200, 115, text="Программа №2", fill="Purple", font='Times 13')
canvas.create_window((10, 125), anchor="nw", window=Program2) 

if __name__ == "__main__":
    tk.mainloop() # Запуск окна

I even deliberately run the kernel AFTER I entered the data in the field! And he gives me:
Screenshot
618964006a842823887298.png

The empty space is where the contents of the Program1way variable are output, but it's empty! Based on this - when importing and executing the code, for some reason, there is a void in the Program tkinter variable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-09
@Vindicar

Yura Milevsky , move the kernel code to a separate thread (via threading) or to a separate process (via multiprocessing). Leave the GUI in the main thread/process.
Organize communication through threading.Queue or multiprocessing.Queue (depending on what you use).
Your GUI sets only the kernel settings, right? Then when you change something in the GUI, you queue a tuple of the form ("parameter name", "parameter value"). The kernel in its free time checks for new elements in the Queue, extracts these tuples, and remembers the new settings already locally (for example, in a dictionary). Well, he uses this dictionary when necessary.
If you need to complicate the interaction, then complicate the data structure that you pass. For example, a tuple would look like ("Command name", ["options", "commands"]). The kernel will have to somehow interpret and execute this command. Anyway, the key idea is this - you pass only primitive types like strings and numbers through the queue, as well as tuples, lists and dictionaries.
And if you need to transfer something from the kernel to the GUI, then use a separate queue, which the GUI will check, and the kernel will fill.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question