Skip to content

Commit 568e71a

Browse files
committed
Some refactoring
1 parent 6c7e572 commit 568e71a

File tree

20 files changed

+364
-98
lines changed

20 files changed

+364
-98
lines changed

src/UBUVoiceAssistant/GUI/chat_window.py

Lines changed: 91 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Module for the chat window GUI
2+
"""
13
from threading import Thread
24
import subprocess
35
import sys
@@ -16,11 +18,13 @@
1618

1719

1820
class ChatWindow(QtWidgets.QMainWindow):
19-
def __init__(self, bus: MessageBusClient, ws: WebService) -> None:
21+
"""Class for the Chat window GUI
22+
"""
23+
def __init__(self, bus: MessageBusClient, webservice: WebService) -> None:
2024
super().__init__(parent=None)
2125
uic.loadUi("./UBUVoiceAssistant/GUI/forms/chat-window.ui", self)
2226
self.bus = bus
23-
self.ws = ws
27+
self.webservice = webservice
2428
self.user_utterance = ""
2529
self.mycroft_response = ""
2630
self.mic_muted = False
@@ -29,8 +33,10 @@ def __init__(self, bus: MessageBusClient, ws: WebService) -> None:
2933
self.next_message = 0
3034
self.intent_labels = []
3135

32-
self.mic_icon = QtGui.QIcon(QtGui.QPixmap("UBUVoiceAssistant/imgs/mic.svg"))
33-
self.mic_muted_icon = QtGui.QIcon(QtGui.QPixmap("UBUVoiceAssistant/imgs/mic_muted.svg"))
36+
self.mic_icon = QtGui.QIcon(
37+
QtGui.QPixmap("UBUVoiceAssistant/imgs/mic.svg"))
38+
self.mic_muted_icon = QtGui.QIcon(
39+
QtGui.QPixmap("UBUVoiceAssistant/imgs/mic_muted.svg"))
3440

3541
self.color: List[Union[int, float]] = list(
3642
self.palette().color(QtGui.QPalette.ColorRole.Background).getRgb())
@@ -73,6 +79,8 @@ def __init__(self, bus: MessageBusClient, ws: WebService) -> None:
7379
# os.path.abspath(os.getcwd())+"/UBUVoiceAssistant/GUI/forms/chat_window_html"))
7480

7581
def set_elements_web(self):
82+
"""Sets the initial elements for the HTML webview
83+
"""
7684
print(self.color)
7785
js_color = "document.body.style.backgroundColor = 'rgba(" + ','.join(
7886
map(str, self.color)) + ")';"
@@ -84,7 +92,8 @@ def set_elements_web(self):
8492
message += "· " + _("Tell me about the forums of (course)\n")
8593
message += "· " + _("Tell me my grades\n")
8694
message += "· " + _("Tell me about the events of (course)\n")
87-
message += "· " + _("Tell me about the events on (month) (day) (year)\n")
95+
message += "· " + \
96+
_("Tell me about the events on (month) (day) (year)\n")
8897
message += "· " + _("Tell me about the changes of (course)\n")
8998
message += "· " + _("Tell me the grades of (course)\n")
9099
message += "· " + _("Read the latest messages\n")
@@ -99,11 +108,19 @@ def set_elements_web(self):
99108
self.web.page().runJavaScript(js_string)
100109

101110
def update_texts(self):
111+
"""Sets the localized texts for the UI
112+
"""
102113
self.btnConfig.setText(_("Manage skills"))
103114
self.btnSend.setText(_("Send"))
104115
self.tbxInput.setPlaceholderText(_("Type your command here..."))
105116

106117
def update_chat(self, source: str, message: str):
118+
"""Adds the new message to the chat
119+
120+
Args:
121+
source (str): "u" when coming from user, "r" when coming from Mycroft
122+
message (str): The message text
123+
"""
107124
js_string = "var chat = document.getElementById('chat-window');\n"
108125
js_string += "var msg = document.createElement('li');\n"
109126
if source == "u":
@@ -116,12 +133,24 @@ def update_chat(self, source: str, message: str):
116133
self.web.page().runJavaScript(js_string)
117134

118135
def handle_speak(self, message: Message):
136+
"""Sets the Mycroft response variable when a message comes
137+
138+
Args:
139+
message (Message): Mycroft bus message
140+
"""
119141
self.mycroft_response = message.data.get("utterance")
120142

121143
def handle_utterance(self, message: Message):
144+
"""Sets the user message variable when you send a message
145+
146+
Args:
147+
message (Message): User bus message
148+
"""
122149
self.user_utterance = message.data["utterances"][0]
123150

124151
def check_for_chat_update(self):
152+
"""Checks if a new message arrives and updates the UI
153+
"""
125154
if self.user_utterance:
126155
self.update_chat("u", self.user_utterance)
127156
self.user_utterance = ""
@@ -130,6 +159,11 @@ def check_for_chat_update(self):
130159
self.mycroft_response = ""
131160

132161
def closeEvent(self, event: QtGui.QCloseEvent) -> None:
162+
"""Handles when the user tries to close the window
163+
164+
Args:
165+
event (QtGui.QCloseEvent): Qt Close Event
166+
"""
133167
self.close_window = MessageBox(_("Are you sure?"))
134168
self.close_window.setStandardButtons(
135169
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel)
@@ -148,19 +182,33 @@ def closeEvent(self, event: QtGui.QCloseEvent) -> None:
148182
event.ignore()
149183

150184
def finish_exit(self):
185+
"""Exits the program
186+
"""
151187
sys.exit(0)
152188

153189
def keyPressEvent(self, event):
190+
"""This is executed when the user press a key
191+
192+
Args:
193+
event: Qt Keypress event
194+
"""
154195
if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
155196
self.on_send_pressed()
156197

157198
def on_send_pressed(self):
199+
"""This runs when the user press enter or clicks the button on the UI
200+
"""
158201
self.user_utterance = self.tbxInput.text()
159202
self.bus.emit(Message('recognizer_loop:utterance', {
160203
'utterances': [self.user_utterance]}))
161204
self.tbxInput.setText('')
162205

163206
def on_mic_pressed(self, startup: bool = False):
207+
"""This runs when the user clicks the mic button
208+
209+
Args:
210+
startup (bool, optional): True if this is running at startup. Defaults to False.
211+
"""
164212
# Switch between muted and unmuted when the mic is pressed
165213
if self.mic_muted or startup:
166214
self.mic_muted = False
@@ -176,14 +224,19 @@ def on_mic_pressed(self, startup: bool = False):
176224
self.bus.emit(Message('mycroft.mic.mute'))
177225

178226
def on_skills_pressed(self):
227+
"""This runs when you press the "manage skills" button. Shows the new window
228+
"""
179229

180230
self.skills_dialog = QtWidgets.QDialog(self)
181231
self.skills_dialog.setWindowTitle('Mycroft Skills')
182232
self.skills_dialog.resize(600, 600)
183233

184-
self.pushButton_manage_skills = QtWidgets.QPushButton(self.skills_dialog)
185-
self.pushButton_manage_skills.setGeometry(QtCore.QRect(470, 10, 120, 40))
186-
self.pushButton_manage_skills.clicked.connect(self.on_manage_skills_pressed)
234+
self.pushButton_manage_skills = QtWidgets.QPushButton(
235+
self.skills_dialog)
236+
self.pushButton_manage_skills.setGeometry(
237+
QtCore.QRect(470, 10, 120, 40))
238+
self.pushButton_manage_skills.clicked.connect(
239+
self.on_manage_skills_pressed)
187240

188241
self.pushButton_manage_skills.setText(_("Save"))
189242

@@ -202,14 +255,17 @@ def on_skills_pressed(self):
202255
# Create checkboxes for every skill in self.active_skills
203256
for count, name in enumerate(self.active_skills):
204257
check_box = QtWidgets.QCheckBox(scroll_area_widget_skills)
205-
spacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
258+
spacer = QtWidgets.QSpacerItem(
259+
40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
206260
check_box.setText(name)
207261
check_box.setChecked(True)
208262
logo = QtWidgets.QLabel(scroll_area_widget_skills)
209263
if 'ubu' in name:
210-
logo.setPixmap(QtGui.QPixmap('UBUVoiceAssistant/imgs/ubu_logo.jpg').scaled(20, 20))
264+
logo.setPixmap(QtGui.QPixmap(
265+
'UBUVoiceAssistant/imgs/ubu_logo.jpg').scaled(20, 20))
211266
else:
212-
logo.setPixmap(QtGui.QPixmap('UBUVoiceAssistant/imgs/Mycroft_logo.png').scaled(20, 20))
267+
logo.setPixmap(QtGui.QPixmap(
268+
'UBUVoiceAssistant/imgs/Mycroft_logo.png').scaled(20, 20))
213269
self.active_skills_checkBoxes.append(check_box)
214270
skills_grid_layout.addWidget(logo, count, 0)
215271
skills_grid_layout.addWidget(check_box, count, 1)
@@ -221,9 +277,11 @@ def on_skills_pressed(self):
221277
check_box.setText(name)
222278
logo = QtWidgets.QLabel(scroll_area_widget_skills)
223279
if 'ubu' in name:
224-
logo.setPixmap(QtGui.QPixmap('UBUVoiceAssistant/imgs/ubu_logo.jpg').scaled(20, 20))
280+
logo.setPixmap(QtGui.QPixmap(
281+
'UBUVoiceAssistant/imgs/ubu_logo.jpg').scaled(20, 20))
225282
else:
226-
logo.setPixmap(QtGui.QPixmap('UBUVoiceAssistant/imgs/Mycroft_logo.png').scaled(20, 20))
283+
logo.setPixmap(QtGui.QPixmap(
284+
'UBUVoiceAssistant/imgs/Mycroft_logo.png').scaled(20, 20))
227285
self.inactive_skills_checkBoxes.append(check_box)
228286
skills_grid_layout.addWidget(logo, count, 0)
229287
skills_grid_layout.addWidget(check_box, count, 1)
@@ -233,31 +291,38 @@ def on_skills_pressed(self):
233291

234292
def on_manage_skills_pressed(self):
235293
""" Adds the checked skills to self.active_skills and the unchecked to
236-
self.inactive_skills and activates or deactivates those skills.
294+
self.inactive_skills and activates or deactivates those skills when pressing save.
237295
"""
238296
deactivated = []
239297
activated = []
240-
for cb in self.active_skills_checkBoxes:
241-
if not cb.isChecked():
242-
self.bus.emit(Message('skillmanager.deactivate', {'skill': cb.text()}))
243-
deactivated.append(cb.text())
244-
245-
for cb in self.inactive_skills_checkBoxes:
246-
if cb.isChecked():
247-
self.bus.emit(Message('skillmanager.activate', {'skill': cb.text()}))
248-
activated.append(cb.text())
249-
250-
self.active_skills = [skill for skill in self.active_skills if skill not in deactivated]
298+
for checkbox in self.active_skills_checkBoxes:
299+
if not checkbox.isChecked():
300+
self.bus.emit(
301+
Message('skillmanager.deactivate', {'skill': checkbox.text()}))
302+
deactivated.append(checkbox.text())
303+
304+
for checkbox in self.inactive_skills_checkBoxes:
305+
if checkbox.isChecked():
306+
self.bus.emit(
307+
Message('skillmanager.activate', {'skill': checkbox.text()}))
308+
activated.append(checkbox.text())
309+
310+
self.active_skills = [
311+
skill for skill in self.active_skills if skill not in deactivated]
251312
self.active_skills.extend(activated)
252313

253-
self.inactive_skills = [skill for skill in self.inactive_skills if skill not in activated]
314+
self.inactive_skills = [
315+
skill for skill in self.inactive_skills if skill not in activated]
254316
self.inactive_skills.extend(deactivated)
255317

256318
self.skills_dialog.hide()
257319
self.on_skills_pressed()
258320

259321

260322
class CloseMycroft(QtCore.QThread):
323+
"""Thread to close Mycroft"""
261324
def run(self):
325+
"""Closes Mycroft and emits a signal when finished
326+
"""
262327
subprocess.run("/usr/lib/mycroft-core/stop-mycroft.sh", shell=True)
263328
self.finished.emit()

src/UBUVoiceAssistant/GUI/link_mycroft.py

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
class LinkMycroft(QtWidgets.QMainWindow):
1919
"""Class for the linking Mycroft to web UI
2020
"""
21-
21+
2222
closed_signal = pyqtSignal()
2323

2424
def __init__(self, bus: MessageBusClient) -> None:
@@ -45,9 +45,10 @@ def __init__(self, bus: MessageBusClient) -> None:
4545

4646
self.file = open("/var/log/mycroft/skills.log", "r")
4747
self.file.seek(0, 2) # Goes to the end of the file
48-
self.bus.emit(Message("recognizer_loop:utterance",
49-
{'utterances': [_("pair my device")]}))
50-
# On other languages different than English, we must send again the phrase for it to start pairing
48+
self.bus.emit(Message("recognizer_loop:utterance",
49+
{'utterances': [_("pair my device")]}))
50+
# On other languages different than English, we must send again the phrase for it
51+
# to start pairing
5152
bus.on("configuration.updated", self.pairing_done)
5253
self.timer = QTimer()
5354
self.timer.timeout.connect(self.add_pairing_code) # type: ignore
@@ -58,30 +59,43 @@ def __init__(self, bus: MessageBusClient) -> None:
5859
self.setFixedSize(self.size())
5960

6061
def pairing_done(self, event):
62+
"""This function gets triggered when we finish pairing Mycroft.
63+
64+
Args:
65+
event: Mycroft pairing event
66+
"""
6167
self.done = True
6268
self.file.close()
6369
self.close()
6470

6571
def add_pairing_code(self):
72+
"""Sets the pairing code and shows it on the UI
73+
"""
6674
self.lblCode.setText(self.code)
6775

6876
def read_pairing_code(self):
77+
"""Reads the skills file and sets the pairing code to a variable
78+
"""
6979
while not self.done:
7080
print("Reading...")
7181
line = self.file.readline()
7282
if line:
7383
print(line)
7484
matches = re.findall(
75-
"(?<=" + re.escape("PairingSkill | ") + ")[a-zA-Z0-9 ]*: [A-Z0-9]{6}(?=\n)", line)
85+
"(?<=" + re.escape("PairingSkill | ") + ")[a-zA-Z0-9 ]*: [A-Z0-9]{6}(?=\n)",
86+
line)
7687
print(matches)
7788
if matches:
7889
self.code = matches[0][-6:]
7990
else:
8091
time.sleep(1)
8192

8293
def update_texts(self):
94+
"""Sets the localized texts in the UI
95+
"""
8396
self.lblWelcome.setText(_("Welcome!"))
84-
self.lblFirstRun.setText(_("It's your first time using Mycroft, so please follow these instructions"))
97+
self.lblFirstRun.setText(
98+
_("It's your first time using Mycroft, so please follow these instructions"))
8599
self.btnPrev.setText(_("Previous"))
86100
self.btnNext.setText(_("Next"))
87101
self.lblRegisterAddDevice.setText(
@@ -90,6 +104,8 @@ def update_texts(self):
90104
self.lblInfoCode.setText(_("Input this code on the website"))
91105

92106
def go_next(self):
107+
"""This function gets executed when the user clicks the next button
108+
"""
93109
self.hide_all_elements()
94110
self.page = min(2, self.page + 1)
95111
if self.page == 1:
@@ -105,6 +121,8 @@ def go_next(self):
105121
self.btnPrev.setEnabled(True)
106122

107123
def go_previous(self):
124+
"""This function gets executed when the user click the previous version
125+
"""
108126
self.hide_all_elements()
109127
self.page = max(0, self.page - 1)
110128
if self.page == 1:
@@ -119,6 +137,8 @@ def go_previous(self):
119137
self.btnNext.setEnabled(True)
120138

121139
def hide_all_elements(self):
140+
"""Hides all images and texts when switching pages
141+
"""
122142
self.imgSelectVoice.setVisible(False)
123143
self.imgAddDevice.setVisible(False)
124144
self.picInputCode.setVisible(False)
@@ -132,6 +152,11 @@ def hide_all_elements(self):
132152
self.btnNext.setEnabled(False)
133153

134154
def closeEvent(self, event: QtGui.QCloseEvent) -> None:
155+
"""This get triggered when closing the window
156+
157+
Args:
158+
event (QtGui.QCloseEvent): Qt Close event
159+
"""
135160
if self.done:
136161
self.closed_signal.emit()
137162
time.sleep(2) # type: ignore
@@ -144,7 +169,8 @@ def closeEvent(self, event: QtGui.QCloseEvent) -> None:
144169
print(self.close_res)
145170
if self.close_res == QtWidgets.QMessageBox.Yes:
146171
self.timer.stop()
147-
self.closing_window = ProgressBox(_("Closing Mycroft, please wait..."))
172+
self.closing_window = ProgressBox(
173+
_("Closing Mycroft, please wait..."))
148174
self.closing_window.show()
149175
self.closing_thread = CloseMycroft()
150176
self.closing_thread.finished.connect( # type: ignore
@@ -154,10 +180,16 @@ def closeEvent(self, event: QtGui.QCloseEvent) -> None:
154180
event.ignore()
155181

156182
def finish_exit(self):
183+
"""Exits the program
184+
"""
157185
sys.exit(0)
158186

159187

160188
class CloseMycroft(QThread):
189+
"""A thread to close Mycroft when exiting
190+
"""
161191
def run(self):
192+
"""Closes Mycroft and emits the event
193+
"""
162194
subprocess.run("/usr/lib/mycroft-core/stop-mycroft.sh", shell=True)
163195
self.finished.emit()

0 commit comments

Comments
 (0)