Форум сайта python.su
current_time = datetime.datetime.now().time() class Graph(object): def __init__(self, nodes, init_graph): self.nodes = nodes self.graph = self.construct_graph(nodes, init_graph) def construct_graph(self, nodes, init_graph): ''' Этот метод обеспечивает симметричность графика. Другими словами, если существует путь от узла A к B со значением V, должен быть путь от узла B к узлу A со значением V. ''' graph = {} for node in nodes: graph[node] = {} graph.update(init_graph) for node, edges in graph.items(): for adjacent_node, value in edges.items(): if graph[adjacent_node].get(node, False) == False: graph[adjacent_node][node] = value return graph def get_nodes(self): "Возвращает узлы графа" return self.nodes def get_outgoing_edges(self, node): "Возвращает соседей узла" connections = [] for out_node in self.nodes: if self.graph[node].get(out_node, False) != False: connections.append(out_node) return connections def value(self, node1, node2): "Возвращает значение ребра между двумя узлами." return self.graph[node1][node2] def dijkstra_algorithm(graph, start_node): unvisited_nodes = list(graph.get_nodes()) # Мы будем использовать этот словарь, чтобы сэкономить на посещении каждого узла и обновлять его по мере продвижения по графику shortest_path = {} # Мы будем использовать этот dict, чтобы сохранить кратчайший известный путь к найденному узлу previous_nodes = {} # Мы будем использовать max_value для инициализации значения "бесконечности" непосещенных узлов max_value = sys.maxsize for node in unvisited_nodes: shortest_path[node] = max_value # Однако мы инициализируем значение начального узла 0 shortest_path[start_node] = 0 # Алгоритм выполняется до тех пор, пока мы не посетим все узлы while unvisited_nodes: # Приведенный ниже блок кода находит узел с наименьшей оценкой current_min_node = None for node in unvisited_nodes: # Iterate over the nodes if current_min_node == None: current_min_node = node elif shortest_path[node] < shortest_path[current_min_node]: current_min_node = node # Приведенный ниже блок кода извлекает соседей текущего узла и обновляет их расстояния neighbors = graph.get_outgoing_edges(current_min_node) for neighbor in neighbors: tentative_value = shortest_path[current_min_node] + graph.value(current_min_node, neighbor) if tentative_value < shortest_path[neighbor]: shortest_path[neighbor] = tentative_value # We also update the best path to the current node previous_nodes[neighbor] = current_min_node # После посещения его соседей мы отмечаем узел как "посещенный" unvisited_nodes.remove(current_min_node) return previous_nodes, shortest_path def print_result(previous_nodes, shortest_path, start_node, target_node): path = [] node = target_node while node != start_node: path.append(node) node = previous_nodes[node] # Добавить начальный узел вручную path.append(start_node) result_text = "Найден следующий лучший маршрут с расстоянием {} км".format(shortest_path[target_node]) result_text += "\n" + " -> ".join(reversed(path)) # Вставить результат в текстовое поле text_input.insert(END, result_text + "\n") nodes = {"Склад": (43.356374, 132.072318), "Некрасовская": (43.128128, 131.910649), "3-я Рабочая": (43.123089, 131.924877), "Центр": (43.115797, 131.885064), "Луговая": (43.128078, 131.940321), "Нивельского": (43.112586, 131.943152), "Нейбута": (43.116441, 131.955245), "ДВФУ": (43.025101, 131.894189)} valuegor = list(nodes.keys()) etaj = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] #Координаты остановок storage = (43.356374, 132.072318) necra = (43.128128, 131.910649) raboch = (43.123089, 131.924877) center = (43.115797, 131.885064) lugovaya = (43.128078, 131.940321) nivels = (43.112586, 131.943152) newboot = (43.116441, 131.955245) DVFU = (43.025101, 131.894189) init_graph = {} for node in nodes: init_graph[node] = {} if current_time < datetime.time(12, 0, 0): init_graph["Склад"]["Некрасовская"] = round(GD(nodes["Склад"], nodes["Некрасовская"]).km + 5, 2) init_graph["Склад"]["Центр"] = round(GD(nodes["Склад"], nodes["Центр"]).km + 5, 2) init_graph["Некрасовская"]["Нивельского"] = round(GD(nodes["Некрасовская"], nodes["Нивельского"]).km + 5, 2) init_graph["Некрасовская"]["3-я Рабочая"] = round(GD(nodes["Некрасовская"], nodes["3-я Рабочая"]).km + 5, 2) init_graph["3-я Рабочая"]["Нейбута"] = round(GD(nodes["3-я Рабочая"], nodes["Нейбута"]).km + 5, 2) init_graph["3-я Рабочая"]["ДВФУ"] = round(GD(nodes["3-я Рабочая"], nodes["ДВФУ"]).km + 5, 2) init_graph["3-я Рабочая"]["Луговая"] = round(GD(nodes["3-я Рабочая"], nodes["Луговая"]).km + 5, 2) init_graph["ДВФУ"]["Нейбута"] = round(GD(nodes["ДВФУ"], nodes["Нейбута"]).km + 5, 2) init_graph["Луговая"]["Нивельского"] = round(GD(nodes["Луговая"], nodes["Нивельского"]).km + 5, 2) init_graph["Луговая"]["ДВФУ"] = round(GD(nodes["Луговая"], nodes["ДВФУ"]).km + 5, 2) elif current_time < datetime.time(18, 0, 0): init_graph["Склад"]["Некрасовская"] = round(GD(nodes["Склад"], nodes["Некрасовская"]).km + 6, 2) init_graph["Склад"]["Центр"] = round(GD(nodes["Склад"], nodes["Центр"]).km + 5, 2) init_graph["Некрасовская"]["Нивельского"] = round(GD(nodes["Некрасовская"], nodes["Нивельского"]).km + 6, 2) init_graph["Некрасовская"]["3-я Рабочая"] = round(GD(nodes["Некрасовская"], nodes["3-я Рабочая"]).km + 6, 2) init_graph["3-я Рабочая"]["Нейбута"] = round(GD(nodes["3-я Рабочая"], nodes["Нейбута"]).km + 6, 2) init_graph["3-я Рабочая"]["ДВФУ"] = round(GD(nodes["3-я Рабочая"], nodes["ДВФУ"]).km + 6, 2) init_graph["3-я Рабочая"]["Луговая"] = round(GD(nodes["3-я Рабочая"], nodes["Луговая"]).km + 6, 2) init_graph["ДВФУ"]["Нейбута"] = round(GD(nodes["ДВФУ"], nodes["Нейбута"]).km + 6, 2) init_graph["Луговая"]["Нивельского"] = round(GD(nodes["Луговая"], nodes["Нивельского"]).km + 6, 2) init_graph["Луговая"]["ДВФУ"] = round(GD(nodes["Луговая"], nodes["ДВФУ"]).km + 6, 2) else: init_graph["Склад"]["Некрасовская"] = round(GD(nodes["Склад"], nodes["Некрасовская"]).km + 5, 2) init_graph["Склад"]["Центр"] = round(GD(nodes["Склад"], nodes["Центр"]).km + 5, 2) init_graph["Некрасовская"]["Нивельского"] = round(GD(nodes["Некрасовская"], nodes["Нивельского"]).km, 2) init_graph["Некрасовская"]["3-я Рабочая"] = round(GD(nodes["Некрасовская"], nodes["3-я Рабочая"]).km, 2) init_graph["3-я Рабочая"]["Нейбута"] = round(GD(nodes["3-я Рабочая"], nodes["Нейбута"]).km, 2) init_graph["3-я Рабочая"]["ДВФУ"] = round(GD(nodes["3-я Рабочая"], nodes["ДВФУ"]).km, 2) init_graph["3-я Рабочая"]["Луговая"] = round(GD(nodes["3-я Рабочая"], nodes["Луговая"]).km, 2) init_graph["ДВФУ"]["Нейбута"] = round(GD(nodes["ДВФУ"], nodes["Нейбута"]).km, 2) init_graph["Луговая"]["Нивельского"] = round(GD(nodes["Луговая"], nodes["Нивельского"]).km, 2) init_graph["Луговая"]["ДВФУ"] = round(GD(nodes["Луговая"], nodes["ДВФУ"]).km, 2) #КОД МЕНЮ def close_window(): root.destroy() def save_to_file(): text_to_save = text_input.get("1.0", END) file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")]) if file_path: try: with open(file_path, 'w', encoding='utf-8') as file: file.write(text_to_save) except Exception as e: print(f"An error occurred while saving the file: {e}") def open_file(): file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")]) if file_path: try: with open(file_path, 'r', encoding='utf-8') as file: text = file.read() text_input.delete(1.0, END) text_input.insert(END, text) except Exception as e: print(f"An error occurred while opening the file: {e}") def change_button_color(): color = colorchooser.askcolor(title="Choose Button Color") if color[1]: # Check if a color was chosen save_button.config(bg=color[1]) open_button.config(bg=color[1]) exit_button.config(bg=color[1]) slovo_button.config(bg=color[1]) delete_button.config(bg=color[1]) run_button.config(bg=color[1]) def change_menu_color(): color = colorchooser.askcolor(title="Choose Button Color") if color[1]: # Check if a color was chosen text_input.config(bg=color[1]) text1_input.config(bg=color[1]) root.config(bg=color[1]) def current_time(): t = time.localtime() current_time = time.strftime("%H:%M:%S", t) text1_input.delete(1.0, END) text1_input.insert(END, current_time) #Выбор пункта доставки selected_value = None def select_value(): global selected_value selected_value = combo.get() print(f"Выбрано значение: {selected_value}") #Выбор этажа selected_value1 = None def select_value1(): global selected_value1 selected_index = combo1.current() selected_value1 = etaj[selected_index] print("Selected value:", selected_value1) #Выбор стартовой точки selected_value2 = None def select_value2(): global selected_value2 selected_value2 = combo2.get() print(f"Выбрано значение: {selected_value2}") def clear_text(): text_input.delete(1.0, END) text1_input.delete(1.0, END) root = Tk() root.title("Меню") root.geometry("1920x1080") root.option_add("*tearOff", False) main_menu = Menu() file_menu = Menu() setting_menu = Menu() selected_font = tk.StringVar(root) main_menu.add_cascade(label="Файл", menu=file_menu) main_menu.add_cascade(label="Настройки", menu=setting_menu) file_menu.add_command(label="Выход", command=close_window) setting_menu.add_command(label="Выбор цвета кнопок", command = change_button_color) setting_menu.add_command(label="Выбор цвета меню", command = change_menu_color) root.config(menu=main_menu) text_input = Text(root, wrap="word", height=30, width=120, font = ("Arial", 16)) # Указываем высоту и ширину текстового поля text_input.grid(row=0, column=0, rowspan=3, padx=10, pady=10) #Подпись для обозначения цены label = Label(root, text="Стоимость доставки", font = ("Arial", 16)) label.place(x = 340, y = 777) text1_input = Text(root, wrap="word", height=1, width=25 , font = ("Arial", 16)) text1_input.grid(row=4, column=0, rowspan=1, padx=0, pady=0) #ввод этажа для доставки label1 = Label(root, text="Этаж доставки", font = ("Arial", 16)) label1.place(x = 340, y = 807) #Выбор этажа combo1 = ttk.Combobox(root, values=etaj) combo1['values'] = etaj combo1.grid(row=5, column=0, padx=0, pady=0) #кнопка Выбора этажа button_etaj = Button(root, text="Выбрать этаж", command=select_value1) button_etaj.place(x = 840, y = 807) save_button = Button(root, text="Сохранить", command=save_to_file) save_button.grid(row=0, column=1, padx=10, pady=5) open_button = Button(root, text="Загрузить", command=open_file) open_button.grid(row=1, column=1, padx=10, pady=5) #Кнопка выхода exit_button = Button(root, text="Выход", command=close_window) exit_button.grid(row=6, column=0, padx=10, pady=5) #Выбор пункта доставки combo = ttk.Combobox(root, values=valuegor) combo.grid(row=2, column=2, padx=10, pady=5) combo.bind("<<ComboboxSelected>>", select_value) #Выбор стартовой точки #combo2 = ttk.Combobox(root, values=nodes) #combo2.grid(row=3, column=2, padx=10, pady=5) #combo2.bind("<<Combobox2Selected>>", select_value2) slovo_button = Button(root, text="Выбрать", command=select_value) slovo_button.grid(row=2, column=1, padx=10, pady=5) #slovo1_button = Button(root, text="Выбрать", command=select_value2) #slovo1_button.grid(row=3, column=1, padx=10, pady=5) delete_button = Button(root, text="Очистить", command=clear_text) delete_button.grid(row=4, column=1, padx=10, pady=5) #Сбор остановок в массив array = [] def add_value(): value = combo.get() array.append(value) #text_input.delete(0, tk.END) def display_array(): text_input.config(state=tk.NORMAL) #text_input.delete(1.0, tk.END) text_input.insert(tk.END, "Текущий список остановок: ") text_input.insert(tk.END, ', '.join(array)) #text_input.config(state=tk.DISABLED) add_button = tk.Button(root, text="Добавить значение", command=add_value) add_button.grid(row=0, column=2) display_button = tk.Button(root, text="показать массив", command=display_array) display_button.grid(row=0, column=3) #Конец этой части кода #Функция запуска алгоритма Дейкстры def run_dijkstra(): global selected_value global selected_value1 global selected_value2 route_value = 0 if selected_value: for index, znach in enumerate(array): previous_index = index -1 if index == 0: graph = Graph(nodes, init_graph) previous_nodes, shortest_path = dijkstra_algorithm(graph=graph, start_node= selected_value) print_result(previous_nodes, shortest_path, start_node= selected_value, target_node=znach) route_value += shortest_path[znach] elif index < len(array): previous_znach = array[previous_index] graph = Graph(nodes, init_graph) previous_nodes, shortest_path = dijkstra_algorithm(graph=graph, start_node= previous_znach) print_result(previous_nodes, shortest_path, start_node= previous_znach, target_node=znach) route_value += shortest_path[znach] #Рассчет стоимости traffic_value = 150 if route_value > 30: traffic_value = 150 * route_value * selected_value1 text1_input.insert(END, traffic_value) else: text1_input.insert(END, traffic_value + 150) text_input.insert(END, route_value) #text_input.insert(END, result_text) #Конец рассчета стоимости # Создайте новую кнопку для запуска алгоритма Дейкстры run_button = Button(root, text="Запустить Дейкстру", command=run_dijkstra) run_button.grid(row=4, column=2, padx=10, pady=5) root.mainloop()
from PyQt5.QtWidgets import QWidget from PyQt5.Qt import * import sys from enum import Enum class Direction(Enum): Up = 0 Down = 1 class Joystick(QWidget): def __init__(self, parent=None): super(Joystick, self).__init__(parent) self.setMinimumSize(1200, 600) self.movingOffset = QPointF(0, 0) self.grabCenter = False self.__maxDistance = 50 def paintEvent(self, event): painter = QPainter(self) bounds = QRectF(-self.__maxDistance, -self.__maxDistance, self.__maxDistance * 2, self.__maxDistance * 2).translated(self._center()) painter.drawEllipse(bounds) painter.setBrush(Qt.black) painter.drawEllipse(self._centerEllipse()) def _centerEllipse(self): if self.grabCenter: return QRectF(-20, -20, 40, 40).translated(self.movingOffset) return QRectF(-20, -20, 40, 40).translated(self._center()) def _center(self): return QPointF(self.width()/2, self.height()/2) def _boundJoystick(self, point): limitLine = QLineF(self._center(), point) if (limitLine.length() > self.__maxDistance): limitLine.setLength(self.__maxDistance) return limitLine.p2() def joystickDirection(self): if not self.grabCenter: return 0 normVector = QLineF(self._center(), self.movingOffset) currentDistance = normVector.length() angle = normVector.angle() distance = min(currentDistance / self.__maxDistance, 1.0) if 45 <= angle < 135: return (Direction.Up, distance) if 225 <= angle < 315: return (Direction.Down, distance) def mousePressEvent(self, ev): self.grabCenter = self._centerEllipse().contains(ev.pos()) return super().mousePressEvent(ev) def mouseReleaseEvent(self, event): self.grabCenter = False self.movingOffset = QPointF(0, 0) self.update() def mouseMoveEvent(self, event): if self.grabCenter: print("Moving") self.movingOffset = self._boundJoystick(event.pos()) self.update() print(self.joystickDirection()) if __name__ == '__main__': app = QApplication([]) app.setStyle(QStyleFactory.create("Cleanlooks")) mw = QMainWindow() mw.setWindowTitle('Joystick') cw = QWidget() ml = QGridLayout() cw.setLayout(ml) mw.setCentralWidget(cw) joystick = Joystick() ml.addWidget(joystick,0,0) mw.show() if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QApplication.instance().exec_()
import device from device.enums import * import time dev = device.find_any() try: for i in range(1): dev.axis0.requested_state = AxisState.CLOSED_LOOP_CONTROL time.sleep(1) dev.axis0.controller.input_vel = 15 time.sleep(5) dev.axis0.controller.input_vel = 0 time.sleep(1) dev.axis0.requested_state = AxisState.IDLE time.sleep(1)
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView from PyQt5.QtGui import QPen, QPainter from PyQt5.QtCore import Qt class TestSequence(QGraphicsView): def __init__(self, sequence): super().__init__() self.setWindowTitle("Test Sequence") self.setGeometry(100, 100, 800, 600) scene = QGraphicsScene(self) self.setScene(scene) pen = QPen(Qt.black) pen.setWidth(2) x, y = 0, 0 for bit in sequence: if bit == '0': scene.addLine(x, y, x + 20, y, pen) x += 20 elif bit == '1': scene.addLine(x, y, x, y - 20, pen) y -= 20 def read_sequence(filename): with open(filename, 'r') as file: sequence = file.read().strip() return sequence if __name__ == '__main__': app = QApplication(sys.argv) sequence = read_sequence("last_bits.txt") test_sequence = TestSequence(sequence) test_sequence.show() sys.exit(app.exec_())
import numpy as np from scipy import integrate import matplotlib.pyplot as plt import datetime start = datetime.datetime.now() plt.rcParams['axes.grid'] = True XX=[None, 11.3, 14.8, 7.6, 10.5, 12.7, 3.9, 11.2, 5.4, 8.5, 5.0, 4.4, 7.3, 2.9, 5.7, 6.2, 7.3, 3.3, 4.2, 5.5, 4.2] I = [None,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] N=20 # Задаем G-ю функцию которая включает в себя произведения плотностей вроятности # каждого независимого результата Xi в которых МО и СКО изменяются по линейной зависимости def G(M1, Mn, S1, Sn): def loc (M1, Mn, i, n): return (M1*(n-i)/(n-1)) + (Mn*(i-1)/(n-1)) def scale (S1, Sn, i, n): return (S1*(n-i)/(n-1)) + (Sn*(i-1)/(n-1)) def fnorm (x): return (np.exp((-x**2)/2))/(np.sqrt(2*np.pi)) def y (M1, Mn, S1, Sn, i, n, x): return (x-loc(M1,Mn,i,n))/scale(S1,Sn,i,n) def F (M1, Mn, S1, Sn, i, n, x): return (fnorm(y(M1, Mn, S1, Sn, i, n, x)))/scale(S1, Sn, i, n) # Распаковка значений x и i из глобальных переменных x = XX[1:] i = I[1:] n=N # Вычисляем значение функции F для каждого x и i values=[F(M1, Mn, S1, Sn, i_val, n, x_val) for i_val, x_val in zip(i, x)] # Вычисляем произведение всех значений result = np.prod(values) return result # находим сомножитель К для получения общей ПВ оценок options={'epsrel':1e-20, 'epsabs':1e-20} K, errorK = integrate.nquad(G, ranges=[[0, 30],[0, 10],[0, 10],[0, 10]], opts=[options, options, options, options]) # K = 2.9613332457351404e-18 errorK = 9.999171231431291e-21 # формируем ПВ оценок def pdf(Mn, S1, Sn, M1): return (G(M1, Mn, S1, Sn) / K) # строим график автономной ПВ оценок для параметра М1 (уменьшаем значения ошибок для оперативности) def pdf_m1 (M1): return [(integrate.tplquad(pdf, 0, 10, 0, 10, 0, 10, args=(m,), epsabs=0.1, epsrel=0.1)[0]) for m in M1] x = np.arange(4, 16, 0.2) plt.plot(x, pdf_m1(x), 'k', lw=3) plt.ylim(bottom=0) plt.title('Fm1(m1)') plt.show() # находим несмещенную оценку М1 и её ско sm1 (примерные значения по методу ММП М1 = 9.66) def F1 (M1): return integrate.tplquad(pdf, 0, 10, 0, 10, 0, 10, args=(M1,))[0] M1, _ = integrate.quad(lambda M1: M1 * F1(M1), 4, 16) print(M1) Dm1, _ = integrate.quad (lambda x: ((x-M1)**2) * F1(x), 4, 16) sm1 = np.sqrt(Dm1) print(sm1) print("Время вычисления М1 и СКОм1:", datetime.datetime.now()-start)
import sys def transformation(input): if len(input) == 0: return None cycle_list = sorted([input[i+1:]+input[:i+1] for i in range(len(input))]) output = "" for s in cycle_list: output += s[len(s)-1] return output if __name__ == '__main__': for line in sys.stdin: print(transformation(line[:-1]))
import sys def re_transformation(input): if len(input) == 0: return None re_cycle_list = ["" for s in input] while len(re_cycle_list[0]) < len(input): re_cycle_list = sorted([input[i]+re_cycle_list[i] for i in range(len(input))]) for s in re_cycle_list: if s[len(s)-1] == '|': return s if __name__ == '__main__': for line in sys.stdin: print(re_transformation(line[:-1]))
[code python]from ast import While
import json
import datetime as dt
import pyaudio
from vosk import Model, KaldiRecognizer
import pyttsx3
import os
import pygame
import time
from fuzzywuzzy import fuzz
import platform
import webbrowser
import subprocess
import sys
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QLineEdit, QMainWindow, QPushButton,
QSizePolicy, QStatusBar, QWidget)
class Ui_LoginWindow(object):
with open('commands.json', 'r') as file:
commands_data = json.load(file)
commands = commands_data.get('commands', [])
def setupUi(self, LoginWindow):
if not LoginWindow.objectName():
LoginWindow.setObjectName(u"LoginWindow")
LoginWindow.resize(480, 157)
LoginWindow.setMinimumSize(QSize(480, 157))
LoginWindow.setMaximumSize(QSize(480, 157))
icon = QIcon()
icon.addFile(u"1679059321_bogatyr-club-p-fioletovii-fon-kiberpank-foni-vkontakte-80.png", QSize(), QIcon.Normal, QIcon.Off)
LoginWindow.setWindowIcon(icon)
LoginWindow.setStyleSheet(u"background-color: rgb(1, 0, 31);")
self.centralwidget = QWidget(LoginWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.LoginEnter = QPushButton(self.centralwidget)
self.LoginEnter.setObjectName(u"LoginEnter")
self.LoginEnter.setGeometry(QRect(290, 60, 161, 51))
self.LoginEnter.setStyleSheet(u"background-color: rgb(56, 56, 56);")
self.NoAccount = QPushButton(self.centralwidget)
self.NoAccount.setObjectName(u"NoAccount")
self.NoAccount.setGeometry(QRect(230, 0, 251, 34))
self.NoAccount.setStyleSheet(u"background-color: rgb(56, 56, 56);")
self.LoginLogin = QLineEdit(self.centralwidget)
self.LoginLogin.setObjectName(u"LoginLogin")
self.LoginLogin.setGeometry(QRect(20, 40, 221, 41))
self.LoginLogin.setStyleSheet(u"background-color: rgb(56, 56, 56);")
self.LoginPassword = QLineEdit(self.centralwidget)
self.LoginPassword.setObjectName(u"LoginPassword")
self.LoginPassword.setGeometry(QRect(20, 90, 221, 41))
self.LoginPassword.setStyleSheet(u"background-color: rgb(56, 56, 56);")
self.LoginPassword.setEchoMode(QLineEdit.Password)
LoginWindow.setCentralWidget(self.centralwidget)
self.statusbar = QStatusBar(LoginWindow)
self.statusbar.setObjectName(u"statusbar")
LoginWindow.setStatusBar(self.statusbar)
self.retranslateUi(LoginWindow)
self.LoginEnter.clicked.connect(self.login)
QMetaObject.connectSlotsByName(LoginWindow)
def login(self):
is_gosha_active = False
last_command_time = None
username = self.LoginLogin.text()
password = self.LoginPassword.text()
try:
with open('accounts.json') as accounts_file:
accounts = json.load(accounts_file)
except FileNotFoundError:
print("Файл 'accounts.json' не найден.")
return
except json.JSONDecodeError:
print("Ошибка декодирования JSON в файле 'accounts.json'.")
return
for account in accounts:
if account["username"] == username and account["password"] == password:
print("Вход выполнен!")
user_role = account['role']
if user_role == 'admin':
model = Model("vosk")
rec = KaldiRecognizer(model, 16000)
engine = pyttsx3.init()
p = pyaudio.PyAudio()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
user = os.getlogin()
now = dt.datetime.now()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=8000)
stream.start_stream()
with open('commands.json', 'r') as file:
commands_data = json.load(file)
commands = commands_data.get('commands', [])
def close_current_window():
system = platform.system()
if system == "Windows":
os.system("taskkill /f /im explorer.exe")
elif system == "Linux":
os.system("xdotool key Alt+F4")
elif system == "Darwin":
os.system('osascript -e "tell application \\"System Events\\" to keystroke \\"w\\" using {command down}"')
def minimize_current_window():
system = platform.system()
if system == "Windows":
os.system("powershell -command $wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('% ')")
elif system == "Linux":
os.system("xdotool getactivewindow windowminimize")
elif system == "Darwin":
os.system('osascript -e "tell application \\"System Events\\" to keystroke \\"m\\" using {command down}"')
def listen():
while True:
data = stream.read(4000, exception_on_overflow=False)
if (rec.AcceptWaveform(data)) and (len(data) > 0):
answer = json.loads(rec.Result())
if answer['text']:
user_text = answer['text']
print("User said:", user_text)
yield user_text
def find_most_similar_command(text):
max_similarity = -1
closest_command = None
for command_data in commands:
activation_phrase = command_data.get('activation_phrase', '')
similarity = fuzz.token_set_ratio(text.lower(), activation_phrase.lower())
if similarity > max_similarity:
max_similarity = similarity
closest_command = command_data
return closest_command, max_similarity
def execute_command(command):
global is_gosha_active, Speak
closest_command, similarity = find_most_similar_command(command)
with open('commands.json', 'r') as file:
commands_data = json.load(file)
commands = commands_data.get('commands', [])
if similarity >= 80:
response = closest_command['response']
engine.say(response)
engine.runAndWait()
if closest_command.get('action') == "run_mom_code":
time.sleep(1)
subprocess.Popen(["python", "mom.py"])
if closest_command.get('action') == "time":
timeh = now.hour
timem = now.minute
engine.say(timeh)
engine.say('часов')
engine.say(timem)
engine.say("минут")
engine.runAndWait()
if closest_command.get('action') == "open_browser":
webbrowser.open("https://www.google.ru/")
if closest_command.get('action') == "open_youtube":
webbrowser.open("https://www.youtube.com/")
if closest_command.get('action') == "close_window":
close_current_window()
if closest_command.get('action') == "minimize_window":
minimize_current_window()
if closest_command.get('action') == "user":
engine.say(user)
engine.runAndWait()
else:
print("Команда не распознана.")
for text in listen():
current_time = now
with open('commands.json', 'r') as file:
commands_data = json.load(file)
commands = commands_data.get('commands', [])
if last_command_time and (current_time - last_command_time).seconds > 7:
is_gosha_active = False
if not is_gosha_active and commands[0]["activation_phrase"] in text.lower():
last_command_time = now
is_gosha_active = True
print("Активация ассистента.")
if commands:
engine.say(commands[0]["response"])
engine.runAndWait()
elif is_gosha_active:
last_command_time = now
if text.lower() == commands[4]["activation_phrase"]:
print("Деактивация ассистента.")
if len(commands) > 3:
engine.say(commands[4]["response"])
engine.runAndWait()
sys.exit(app.exec())
else:
execute_command(text.lower())
elif user_role == 'tester':
print('Не доступно для тестера')
elif user_role == 'user':
print('Не доступно для пользователя')
def retranslateUi(self, LoginWindow):
LoginWindow.setWindowTitle(QCoreApplication.translate("LoginWindow", u"\u0413\u043e\u043b\u043e\u0441\u043e\u0432\u043e\u0439 \u0410\u0441\u0441\u0438\u0441\u0442\u0435\u043d\u0442 \u0413\u043e\u0448\u0430(\u0412\u0445\u043e\u0434)", None))
self.LoginEnter.setText(QCoreApplication.translate("LoginWindow", u"\u0412\u043e\u0439\u0442\u0438", None))
self.NoAccount.setText(QCoreApplication.translate("LoginWindow", u"\u041d\u0435\u0442 \u0430\u043a\u043a\u0430\u0443\u043d\u0442\u0430? \u0417\u0430\u0440\u0435\u0433\u0435\u0441\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u0442\u044c\u0441\u044f.", None))
self.LoginLogin.setPlaceholderText(QCoreApplication.translate("LoginWindow", u"\u041b\u043e\u0433\u0438\u043d", None))
self.LoginPassword.setPlaceholderText(QCoreApplication.translate("LoginWindow", u"\u041f\u0430\u0440\u043e\u043b\u044c", None))
class LoginWindow(QMainWindow):
def __init__(self):
super(LoginWindow, self).__init__()
self.ui = Ui_LoginWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = LoginWindow()
window.show()
sys.exit(app.exec())[/code]
{
"commands": [
{
"name": "гоша",
"activation_phrase": "гоша",
"response": "Слушаю"
},
{
"name": "привет",
"activation_phrase": "привет",
"response": "Приветствую вас!"
},
{
"name": "как дела",
"activation_phrase": "как дела",
"response": "У меня всё отлично, спасибо!"
},
{
"name": "время",
"activation_phrase": "время",
"response": "Текущее время:",
"action": "time"
},
{
"name": "пока",
"activation_phrase": "пока",
"response": "До свидания!"
},
{
"name": "пользователь",
"activation_phrase": "пользователь",
"response": "Сейчас в системе:",
"action": "user"
},
{
"name": "открой браузер",
"activation_phrase": "открой браузер",
"response": "Открываю браузер",
"action": "open_browser"
},
{
"name": "открой ютуб",
"activation_phrase": "открой ютуб",
"response": "Открываю Ютуб",
"action": "open_youtube"
},
{
"name": "др",
"activation_phrase": "поздравь мою маму",
"response": "Поздравляю вашу маму с днем рождения",
"action": "run_mom_code"
},
{
"name": "молодец",
"activation_phrase": "ты молодец",
"response": "Спасибо"
},
{
"name": "закрой текущее окно",
"activation_phrase": "закрой текущее окно",
"response": "Закрываю текущее окно",
"action": "close_window"
},
{
"name": "сверни",
"activation_phrase": "сверни текущее окно",
"response": "Сворачиваю текущее окно",
"action": "minimize_window"
},
{
"activation_phrase": "посчитай",
"response": "Хорошо, давай посчитаем.",
"action": "calculate"
}
]
}
[
{"username": "admin", "password": "admin", "role": "admin"},
{"username": "tester", "password": "tester", "role": "tester"},
{"username": "gosha", "password": "gosha", "role": "user"}
]