-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyGUI.py
More file actions
276 lines (223 loc) · 9.44 KB
/
myGUI.py
File metadata and controls
276 lines (223 loc) · 9.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import os
import sys
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout,
QPushButton, QTableWidget, QTableWidgetItem, QHeaderView, QComboBox,
QHBoxLayout, QLabel, QGridLayout, QPlainTextEdit
)
from PyQt5.QtCore import Qt, pyqtSignal, QObject
from PyQt5.QtGui import QIcon
import sounddevice as sd
import myStream
from pywhispercpp.model import Segment
import pywhispercpp.utils as utils
from datetime import datetime
import logging
from pathlib import Path
logging.basicConfig(level=logging.INFO)
STYLESHEET = """
QHeaderView::section {
background-color: #e8e8e8;
}
QTableWidget::item {
padding: 8px;
}
QPlainTextEdit {
background-color: #1e1e1e;
color: #ffffff;
padding: 8px;
}
"""
class EmittingStream(QObject):
text_written = pyqtSignal(str)
def write(self, text):
self.text_written.emit(str(text))
def flush(self): # needed for compatibility
pass
class QtHandler(logging.Handler, QObject):
log_signal = pyqtSignal(str)
def __init__(self):
logging.Handler.__init__(self)
QObject.__init__(self)
def emit(self, record):
msg = self.format(record)
self.log_signal.emit(msg)
class mySegment():
def __init__(self, start, end, text):
self.start = start
self.end = end
self.text = text
class TranscriberUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Transcriber by Faith Lawrence Escano")
self.setGeometry(200, 200, 1000, 800)
self.setStyleSheet(STYLESHEET)
def resource_path(relative_path):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
self.setWindowIcon(QIcon(resource_path("icon.ico")))
self.input_dropdown = None # Holds the input device
self.model_dropdown = None # Holds the model selection
self.status_label = None # Status label at the bottom
self.table = None # Table to show transcriptions
self.lastTime = None # Last time a segment was added
self.segments = [] # Holds the segments for export
self.streamer = None # Will hold the streaming object
sys.stdout = EmittingStream(text_written=self._append_terminal)
sys.stderr = EmittingStream(text_written=self._append_terminal)
handler = QtHandler()
handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
handler.log_signal.connect(self._append_terminal)
logging.getLogger().handlers.clear()
logging.getLogger().addHandler(handler)
# Central widget and layout
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
# Grid layout for labels and dropdowns
grid_layout = QGridLayout()
grid_layout.setColumnStretch(0, 0) # label column stays compact
grid_layout.setColumnStretch(1, 1) # dropdown column expands
# Input Device
input_label = QLabel("Input Device:")
self.input_dropdown = QComboBox()
self._populate_device_inputs()
grid_layout.addWidget(input_label, 0, 0)
grid_layout.addWidget(self.input_dropdown, 0, 1)
# Model
model_label = QLabel("Model:")
self.model_dropdown = QComboBox()
self.model_dropdown.addItems(["tiny", "base"])
grid_layout.addWidget(model_label, 1, 0)
grid_layout.addWidget(self.model_dropdown, 1, 1)
# Add grid layout to main vertical layout
main_layout.addLayout(grid_layout)
# Transcribe and clear button
controls_layout = QHBoxLayout()
self.transcribe_button = QPushButton("Transcribe")
self.transcribe_button.clicked.connect(self._toggle_transcribe)
controls_layout.addWidget(self.transcribe_button, stretch=1)
self.clearButton = QPushButton("Clear Output")
self.clearButton.clicked.connect(self.clear_output)
controls_layout.addWidget(self.clearButton)
# Export button
self.export_button = QPushButton("Export as TXT")
self.export_button.clicked.connect(self.export_txt)
controls_layout.addWidget(self.export_button)
main_layout.addLayout(controls_layout)
# Output table
self.table = QTableWidget(0, 3) # start with 0 rows, 3 columns
self.table.setHorizontalHeaderLabels(["Start time", "End time", "Text Output"])
self.table.verticalHeader().setVisible(False)
self.table.setWordWrap(True)
self.table.setEditTriggers(QTableWidget.NoEditTriggers) # make table read-only
# Make third column stretch more
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QHeaderView.Stretch)
# Allow vertical scrolling (independent of button)
self.table.setVerticalScrollMode(QTableWidget.ScrollPerPixel)
main_layout.addWidget(self.table)
# Output terminal
self.terminal = QPlainTextEdit()
self.terminal.setReadOnly(True)
self.terminal.setFixedHeight(200)
main_layout.addWidget(self.terminal)
def _append_terminal(self, text):
self.terminal.appendPlainText(text)
self.terminal.verticalScrollBar().setValue(self.terminal.verticalScrollBar().maximum())
# Add device inputs with MME host API
def _populate_device_inputs(self):
devices = sd.query_devices()
host_apis = sd.query_hostapis()
for idx, dev in enumerate(devices):
if dev["max_input_channels"] > 0:
api_name = host_apis[dev["hostapi"]]["name"]
if "MME" in api_name: # only show MME inputs
try:
sd.check_input_settings(device=idx, samplerate=16000, channels=1)
self.input_dropdown.addItem(f"{dev['name']} ({api_name})", idx)
except Exception:
continue
self.input_dropdown.setCurrentIndex(2) # select the Stereo Mix if available
def _toggle_transcribe(self):
if self.transcribe_button.text() == "Transcribe":
self.transcribe_button.setText("Stop")
self._start_transcription()
self.lastTime = datetime.now()
else:
self.transcribe_button.setText("Transcribe")
self._stop_transcription()
def _on_new_segment(self, segment: Segment):
row_position = self.table.rowCount()
self.table.insertRow(row_position)
timenow = datetime.now()
start_time_str = self.lastTime.strftime("%H:%M:%S")
end_time_str = timenow.strftime("%H:%M:%S")
self.lastTime = timenow
start_time = QTableWidgetItem(start_time_str)
start_time.setTextAlignment(Qt.AlignCenter)
end_time = QTableWidgetItem(end_time_str)
end_time.setTextAlignment(Qt.AlignCenter)
text_output = QTableWidgetItem(segment.text.strip())
self.table.setItem(row_position, 0, start_time)
self.table.setItem(row_position, 1, end_time)
self.table.setItem(row_position, 2, text_output)
self.table.resizeRowsToContents()
self.table.scrollToBottom()
my_segment = mySegment(start_time_str, end_time_str, segment.text.strip())
self.segments.append(my_segment)
def _start_transcription(self):
if self.streamer is None:
print("Loading model...")
self.streamer = myStream.Streaming(
model=self.model_dropdown.currentText(),
input_device=self.input_dropdown.currentData(),
segment_callback=self._on_new_segment
)
self.streamer.start()
print("Transcription started.")
else:
print("Transcription already running.")
def _stop_transcription(self):
if self.streamer is not None:
self.streamer.stop()
self.streamer = None
print("Transcription stopped.")
else:
print("Transcription not running.")
def clear_output(self):
self.table.setRowCount(0)
self.segments = []
print("Output cleared.")
def export_txt(self):
if not self.segments:
print("No segments to export.")
return
date_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
output_filename = f"transcription_{date_time}.txt"
self.output_txt(output_filename)
print(f"Transcription exported to {output_filename}")
def output_txt(self, output_file_path: str) -> str:
"""
Creates a raw text from a list of segments
Implementation from `whisper.cpp/examples/main`
:param segments: list of segments
:return: path of the file
"""
if not output_file_path.endswith('.txt'):
output_file_path = output_file_path + '.txt'
absolute_path = Path(output_file_path).absolute()
with open(str(absolute_path), 'w') as file:
for seg in self.segments:
file.write(f"[{seg.start}] " + seg.text)
file.write('\n\n')
return absolute_path
if __name__ == "__main__":
app = QApplication(sys.argv)
window = TranscriberUI()
window.show()
sys.exit(app.exec_())