forked from byte-engineer/PoemSplitter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
260 lines (185 loc) · 8.32 KB
/
Copy pathmain.py
File metadata and controls
260 lines (185 loc) · 8.32 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
import sys
# import time
from PyQt6 import QtWidgets
from PyQt6.QtGui import QKeyEvent
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QTextEdit, QPushButton
from PyQt6.QtGui import QTextCharFormat, QTextCursor, QColor
from PyQt6 import QtGui
from PyQt6.QtGui import QTextCursor
from settings import *
import re
#> use this command to run the file
#> uv run python main.py
class App(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initUi()
self.renderUi()
def initUi(self):
self.setWindowTitle(strings.windowTitle)
self.setGeometry(250, 250, 350, 350)
self.setFixedSize(350, 350)
self.centralWidget = QtWidgets.QWidget()
self.setCentralWidget(self.centralWidget)
self.mainGrid = QtWidgets.QVBoxLayout()
self.centralWidget.setLayout(self.mainGrid)
dbg("Rendering UI: initUi()")
def renderUi(self):
# main Text Edit
self.poemInput = QTextEdit()
self.bottomGridLayout = QtWidgets.QGridLayout(self) # Bottom grid layout
leftCopyButton = QPushButton(strings.leftBtn)
rightCopyButton = QPushButton(strings.rightBtn)
copyAsTable = QPushButton(strings.copyAsTable)
self.clipboardCheckBox = QtWidgets.QCheckBox(strings.clipbrdckbox)
self.logToFileCheckBox = QtWidgets.QCheckBox(strings.logToFileCheckBox)
self.mainGrid.addWidget(self.poemInput)
self.mainGrid.addLayout(self.bottomGridLayout)
self.bottomGridLayout.addWidget(leftCopyButton, 1, 1)
self.bottomGridLayout.addWidget(rightCopyButton, 1, 2)
self.bottomGridLayout.addWidget(self.clipboardCheckBox, 1, 3)
self.bottomGridLayout.addWidget(self.logToFileCheckBox, 2, 3)
self.bottomGridLayout.addWidget(copyAsTable, 2, 1, 1, 2)
leftCopyButton.clicked.connect (lambda: self.processText(self.poemInput.toPlainText(), 'left'))
rightCopyButton.clicked.connect(lambda: self.processText(self.poemInput.toPlainText(), 'right'))
copyAsTable.clicked.connect(self.copyAsTableimpl)
dbg("Rendering UI: renderUi()")
def processText(self, text: str, side: str):
lines = text.split('\n')
result_lines = []
# Clear old highlights and selection
self.poemInput.setExtraSelections([])
self.highlights = []
cursor = self.poemInput.textCursor()
cursor.clearSelection()
self.poemInput.setTextCursor(cursor)
for lineNumber, line in enumerate(lines):
match = re.match(r'^(.*?)\s*(?:\s{2,}|\.+|~+|-+|=+)\s*(.*)$', line)
if match:
dbg(f"Matched '{match.group()}' at index {match.start()} to {match.end()}")
right, left = match.group(1).strip(), match.group(2).strip()
result_lines.append(left if side == 'left' else right)
self.highLightText(match, side)
else:
if lineNumber % 2 == (1 if side == 'left' else 0):
self.highlight_lines(mode='even' if side == 'left' else 'odd')
result_lines.append(line)
final_output = '\n'.join(result_lines)
if self.logToFileCheckBox.isChecked():
with open("OutputFile.txt", 'w') as file:
file.write(final_output)
dbg(final_output, "\n--- Logged to a File ---")
if self.clipboardCheckBox.isChecked():
QtWidgets.QApplication.clipboard().setText(final_output)
dbg(final_output, "\n--- Copied to Clipboard ---")
def _copyAsTableimpl(self):
dbg('copyAsTableimpl')
lines = self.poemInput.toPlainText().split('\n')
ResultLines = []
finalLineString = []
rightLine = None
for lineNumber, line in enumerate(lines):
match = re.match(r'^(.*?)\s*(?:\s{2,}|\.+|~+|-+|=+)\s*(.*)$', line)
if match:
dbg(f"Matched '{match.group()}' at index {match.start()} to {match.end()}")
pair = (match.group(2).strip(), match.group(1).strip())
ResultLines.append(pair)
else:
if lineNumber % 2 == 1:
rightLine = line if line else '?'
elif lineNumber % 2 == 0:
ResultLines.append((rightLine, line))
else:
ResultLines = '?'
dbg("WTF")
for rhtLn, lftLn in ResultLines:
finalLineString.append(rhtLn + '\t' + lftLn)
QtWidgets.QApplication.clipboard().setText('\n'.join(finalLineString))
dbg('\n'.join(finalLineString))
dbg("--- text Copied ---")
def copyAsTableimpl(self):
dbg('copyAsTableimpl')
lines = self.poemInput.toPlainText().split('\n')
ResultLines = []
finalLineString = []
rightLine = None
for lineNumber, line in enumerate(lines):
match = re.match(r'^(.*?)\s*(?:\s{2,}|\.+|~+|-+|=+)\s*(.*)$', line)
if match:
dbg(f"Matched '{match.group()}' at index {match.start()} to {match.end()}")
# Assuming left side is match.group(1), right is match.group(2)
left = match.group(1).strip()
right = match.group(2).strip()
ResultLines.append((right, left)) # Swap if intentional
else:
if lineNumber % 2 == 0:
rightLine = line.strip() if line.strip() else '???'
elif lineNumber % 2 == 1:
leftLine = line.strip() if line.strip() else '???'
if rightLine is None:
rightLine = '???'
ResultLines.append((leftLine, rightLine))
for rhtLn, lftLn in ResultLines:
finalLineString.append(rhtLn + '\t' + lftLn)
QtWidgets.QApplication.clipboard().setText('\n'.join(finalLineString))
dbg('\n'.join(finalLineString))
dbg("--- text Copied ---")
def highlight_lines(self, mode='even'): # mode can be 'even' or 'odd'
self.poemInput.setExtraSelections([]) # clear previous
self.highlights = []
fullText = self.poemInput.toPlainText()
lines = fullText.split('\n')
pos = 0
for index, line in enumerate(lines):
line_len = len(line)
if mode == 'even' and index % 2 == 0:
self._addHighlight(pos, pos + line_len)
elif mode == 'odd' and index % 2 == 1:
self._addHighlight(pos, pos + line_len)
pos += line_len + 1 # +1 for '\n'
self.poemInput.setExtraSelections(self.highlights)
def _addHighlight(self, start, end):
fmt = QTextCharFormat()
fmt.setBackground(QColor("lightgreen"))
cursor = self.poemInput.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor)
selection = QTextEdit.ExtraSelection()
selection.cursor = cursor
selection.format = fmt
self.highlights.append(selection)
def highLightText(self, match: re.Match[str], side):
fullText = self.poemInput.toPlainText()
matchedText = match.group(1 if side == 'left' else 2)
startIdx = fullText.find(matchedText)
if startIdx == -1:
return # Not found, skip
endIdx = startIdx + len(matchedText)
# Create highlight format
fmt = QtGui.QTextCharFormat()
fmt.setBackground(QtGui.QColor("blue"))
# Create cursor and apply selection
cursor = self.poemInput.textCursor()
cursor.setPosition(startIdx)
cursor.setPosition(endIdx, QTextCursor.MoveMode.KeepAnchor)
selection = QtWidgets.QTextEdit.ExtraSelection()
selection.cursor = cursor
selection.format = fmt
# Store all highlights (this is important!)
if not hasattr(self, 'highlights'):
self.highlights = []
self.highlights.append(selection)
self.poemInput.setExtraSelections(self.highlights)
def keyReleaseEvent(self, event):
if isinstance(event, QKeyEvent) and event.key() == Qt.Key.Key_Escape:
self.close()
def main():
app = QtWidgets.QApplication(sys.argv)
app.setStyle('windows11')
win = App()
win.show()
sys.exit(app.exec())
dbg("Done . . .")
if __name__ == "__main__":
main()