-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sentence_Queuer.py
3875 lines (2937 loc) · 162 KB
/
Sentence_Queuer.py
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import argparse
import subprocess
import random
# Text stuff
import re
from ebooklib import epub, ITEM_DOCUMENT
from bs4 import BeautifulSoup
import PyPDF2
import time
from pathlib import Path
from PyQt5 import QtGui
from PyQt5.QtTest import QTest
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import shutil
from tkinter import filedialog
from tkinter import Tk
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QSizeGrip
import json
import datetime
from main_window import Ui_MainWindow
from session_display import Ui_session_display
import resources_config_rc
import sip
from send2trash import send2trash
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QHBoxLayout, QColorDialog, QWidget
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt
class MainApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None, show_main_window=False):
super().__init__(parent)
self.setupUi(self)
self.setWindowTitle('Reference Practice')
self.session_schedule = {}
# Define default shortcuts
self.default_shortcuts = {
"main_window": {
"start": "S",
"close": "Escape"
},
"session_window": {
"toggle_highlight": "G",
"toggle_text_field": "T",
"color_window": "F1",
"always_on_top": "A",
"prev_sentence": "Left",
"pause_timer": "Space",
"close": "Escape",
"next_sentence": "Right",
"open_folder": "O",
"copy_plain_text": "C",
"copy_highlighted_text": "Ctrl+C",
"toggle_clipboard": "Shift+C",
"toggle_metadata": "F2",
"delete_sentence": "Ctrl+D",
"zoom_in": "Q",
"zoom_out": "D",
"zoom_in_numpad": "+",
"zoom_out_numpad": "-",
"show_main_window": "Tab",
"add_30_seconds": "Up",
"add_60_seconds": "Ctrl+Up",
"restart_timer": "Ctrl+Shift+Up"
}
}
# Use the executable's directory for absolute paths
if getattr(sys, 'frozen', False): # Check if the application is frozen (compiled as an EXE)
self.base_dir = os.path.dirname(sys.executable)
self.temp_dir = sys._MEIPASS
else:
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.temp_dir = None
self.presets_dir = os.path.join(self.base_dir, 'writing_presets')
self.text_presets_dir = os.path.join(self.presets_dir, 'text_presets')
self.session_presets_dir = os.path.join(self.presets_dir, 'session_presets')
self.theme_presets_dir = os.path.join(self.presets_dir, 'theme_presets') # New directory for themes
self.default_themes_dir = os.path.join(self.base_dir,'default_themes') # Default themes directory
self.rainmeter_presets_dir = os.path.join(self.presets_dir,'rainmeter_presets')
self.rainmeter_files_dir = os.path.join(self.base_dir,'rainmeter_files')
self.rainmeter_deleted_files_dir = os.path.join(self.rainmeter_presets_dir,'Deleted Files')
self.default_themes = ['default_theme.txt','dark_theme.txt', 'light_theme.txt']
self.current_theme = "default_theme.txt"
print('------------------')
print(' Base Directory:', self.base_dir)
print(' Temporary Directory:', self.temp_dir)
print(' Default Themes Directory:', self.default_themes_dir)
print(' Theme Presets Directory:', self.theme_presets_dir)
print(' Rainmeter Presets Directory:', self.rainmeter_presets_dir)
print(' Rainmeter Files Directory:', self.rainmeter_files_dir)
print(' Rainmeter Deleted Files Directory:', self.rainmeter_deleted_files_dir)
print('------------------')
self.create_directories()
self.ensure_default_themes()
# Initialize the randomize_settings variable or False depending on your default
self.randomize_settings = True
self.clipboard_settings = False
self.auto_start_settings = False
# Initialize cache variables
self.sentence_names_cache = []
self.session_names_cache = []
self.sentence_selection_cache = -1
self.session_selection_cache = -1
# Init color settings
self.color_settings = {}
self.init_styles()
self.table_sentences_selection.setItem(0, 0, QTableWidgetItem('112'))
self.load_presets()
self.schedule = []
self.total_time = 0
self.selection = {'folders': [], 'files': []}
self.KEYWORDS_TYPES = {}
# Load session settings at startup
self.load_session_settings()
self.init_buttons()
self.apply_shortcuts_main_window()
# Hide the main window initially
#self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint)
self.display = None # Initialize with None
# Automatically start the session if auto_start is True
if self.auto_start_settings and (self.sentence_selection_cache >=0 and self.session_selection_cache >=0):
self.start_session_from_files()
# Show the main window if show_main_window is True
elif show_main_window == True:
self.show()
# Initialize position for dragging
self.oldPos = self.pos()
self.init_styles()
def init_message_boxes(self):
"""Initialize custom message box settings."""
self.message_box = QtWidgets.QMessageBox(self)
self.message_box.setIcon(QtWidgets.QMessageBox.NoIcon) # Set to no icon by default
def show_info_message(self, title, message):
"""Show an information message box without an icon."""
self.message_box.setWindowTitle(title)
self.message_box.setText(message)
self.message_box.exec_()
def ensure_default_themes(self):
"""Ensure default theme files are present in theme_presets_dir and replace any missing or corrupted files."""
self.current_theme = 'default_theme.txt'
# Determine the base directory based on whether the app is running as a PyInstaller bundle
if getattr(sys, 'frozen', False):
temp_dir = sys._MEIPASS
self.base_dir = os.path.dirname(sys.executable)
self.default_themes_dir = os.path.join(temp_dir, 'default_themes')
else:
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.default_themes_dir = os.path.join(self.base_dir, 'default_themes')
# Ensure the theme presets directory exists
os.makedirs(self.theme_presets_dir, exist_ok=True)
for theme_file in self.default_themes:
source_file = os.path.join(self.default_themes_dir, theme_file)
destination_file = os.path.join(self.theme_presets_dir, theme_file)
# If the destination file does not exist, or it's corrupted, replace it with the default theme
if not os.path.exists(destination_file):
self.copy_theme_file(source_file, destination_file)
else:
try:
# Check if the existing file is readable and not corrupted
with open(destination_file, 'r') as dst:
content = dst.read()
if not content.strip():
print(f"{theme_file} is empty or corrupted. Replacing with default.")
self.copy_theme_file(source_file, destination_file)
except Exception as e:
print(f"Error reading {theme_file}: {e}. Replacing with default.")
self.copy_theme_file(source_file, destination_file)
def copy_theme_file(self, source_file, destination_file):
"""Copy a theme file from source to destination."""
if os.path.exists(source_file):
try:
with open(source_file, 'r') as src:
content = src.read()
with open(destination_file, 'w') as dst:
dst.write(content)
print(f"Copied {source_file} to {destination_file}")
except Exception as e:
print(f"Error copying {source_file} to {destination_file}: {e}")
else:
print(f"Source theme file {source_file} does not exist.")
def reset_default_themes(self):
"""Replace corrupted or missing theme files in theme_presets_dir with default ones."""
self.current_theme = 'default_theme.txt'
# Determine the base directory based on whether the app is running as a PyInstaller bundle
if getattr(sys, 'frozen', False):
temp_dir = sys._MEIPASS
self.base_dir = self.base_dir = os.path.dirname(sys.executable)
self.default_themes_dir = os.path.join(temp_dir, 'default_themes')
else:
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.default_themes_dir = os.path.join(self.base_dir, 'default_themes')
for theme_file in self.default_themes:
source_file = os.path.join(self.default_themes_dir, theme_file)
destination_file = os.path.join(self.theme_presets_dir, theme_file)
# Remove the existing file if it exists
if os.path.exists(destination_file):
os.remove(destination_file)
# Read from the source file and write to the destination file
if os.path.exists(source_file):
try:
with open(source_file, 'r') as src:
content = src.read()
with open(destination_file, 'w') as dst:
dst.write(content)
print(f"THEME RESTAURED : Replaced {theme_file} in {self.theme_presets_dir}")
self.init_styles()
except Exception as e:
print(f"Error copying {theme_file}: {e}")
else:
print(f"Source theme file {source_file} does not exist.")
self.show_info_message( 'Invalid theme', f'Invalid theme file, theme restaured to default.')
def showEvent(self, event):
"""Override showEvent to control window visibility."""
if not self.isVisible():
event.ignore() # Ignore the event to keep the window hidden
else:
super().showEvent(event) # Otherwise, handle normally
def init_buttons(self):
# Buttons for selection
self.add_folders_button.clicked.connect(self.create_preset)
self.delete_sentences_preset.clicked.connect(self.delete_sentences_files)
# Buttons for preset
self.save_session_presets_button.clicked.connect(self.save_session_presets)
self.delete_session_preset.clicked.connect(self.delete_presets_files)
self.open_preset_button.clicked.connect(self.open_preset)
# Buttons for rainmeter
self.rainmeter_preset_button.clicked.connect(self.create_rainmeter_preset)
# Start session button with tooltip
self.start_session_button.clicked.connect(self.start_session_from_files)
self.start_session_button.setToolTip(f"[{self.shortcut_settings['main_window']['start']}] Start the session.")
# Close window button with tooltip
self.close_window_button.clicked.connect(self.save_session_settings)
self.close_window_button.clicked.connect(self.close)
self.close_window_button.setToolTip(f"[{self.shortcut_settings['main_window']['close']}] Close the setting window.")
# Toggles
self.randomize_toggle.stateChanged.connect(self.update_randomize_settings)
self.clipboard_toggle.stateChanged.connect(self.update_clipboard_settings)
self.auto_start_toggle.stateChanged.connect(self.update_auto_start_settings)
# Table selection handlers
self.table_sentences_selection.itemChanged.connect(self.rename_presets)
self.table_session_selection.itemChanged.connect(self.rename_presets)
# Theme selector button
self.theme_options_button.clicked.connect(self.open_theme_selector)
def init_styles(self, dialog=None, dialog_color=None, session=None):
"""
Initialize custom styles for various UI elements including buttons, spin boxes,
table widgets, checkboxes, dialogs, and the main window. Optionally apply styles
to a specific dialog or session window.
"""
# Load the selected theme file
selected_theme_path = os.path.join(self.theme_presets_dir, self.current_theme)
print('NOW LOADING THEME : ',selected_theme_path)
if selected_theme_path:
try:
with open(selected_theme_path, 'r') as f:
theme_styles = f.read()
except FileNotFoundError:
print("No theme selected or theme file not found. Applying default styles.")
self.ensure_default_themes()
return
try:
# Parse theme styles as JSON
styles_dict = json.loads(theme_styles)
# Apply styles to each element based on the keys in the theme file
for element_group, element_styles in styles_dict.items():
# Split group of elements (comma-separated)
element_names = [name.strip() for name in element_group.split(',')]
for element_name in element_names:
if hasattr(self, element_name):
element = getattr(self, element_name)
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
element.setStyleSheet(style_sheet)
elif element_name == "MainWindow":
# Apply style directly to the MainWindow
style_sheet = ""
for selector, style in element_styles.items():
if selector == "window_icon":
if self.temp_dir :
file_path = os.path.join(self.temp_dir, style)
else:
file_path = os.path.join(self.base_dir, style)
print(file_path)
self.setWindowIcon(QtGui.QIcon(file_path))
elif selector == "icon":
if self.temp_dir :
file_path = os.path.join(self.temp_dir, style)
else:
file_path = os.path.join(self.base_dir, style)
self.label.setText(f"<html><head/><body><p><img src=\"{file_path}\"/></p></body></html>")
else:
style_sheet += f"{selector} {{{style}}}\n"
self.setStyleSheet(style_sheet)
self.init_message_boxes()
elif dialog and element_name == "dialog_styles":
# Apply styles to the dialog if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
dialog.setStyleSheet(style_sheet)
elif dialog_color and element_name == "ColorPickerDialog":
# Apply styles specifically to ColorPickerDialog
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
dialog_color.setStyleSheet(style_sheet)
elif session and element_name == "session_display":
# Apply style to session_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
if selector == "window_icon":
if self.temp_dir :
file_path = os.path.join(self.temp_dir, style)
else:
file_path = os.path.join(self.base_dir, style)
session.setWindowIcon(QtGui.QIcon(file_path))
style_sheet += f"{style}\n"
session.setStyleSheet(style_sheet)
if "background:" not in session.styleSheet():
print('No background color')
session.setStyleSheet("background: rgb(0,0,0)")
elif element_name == "text_display":
if session:
# Apply style to text_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
if selector == "text_color":
session.color_settings[selector]=style
elif "highlight_color_" in selector:
session.color_settings[selector] = style
elif selector == "always_on_top_border":
session.color_settings["always_on_top_border"]=style
elif "metadata_" in selector:
session.color_settings[selector]=style
else:
style_sheet += f"{selector} {{{style}}}\n"
if hasattr(session, 'text_display'):
session.text_display.setStyleSheet(style_sheet)
else:
# Apply style to text_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
if selector == "text_color":
self.color_settings[selector]=style
elif "highlight_color_" in selector:
self.color_settings[selector] = style
elif session and element_name == "lineEdit":
# Apply style to text_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
if hasattr(session, 'lineEdit'):
session.lineEdit.setStyleSheet(style_sheet)
elif session and element_name == "session_display_labels":
session_display_label_styles = styles_dict["session_display_labels"]
for label_name in ["session_info", "timer_display"]:
if hasattr(session, label_name):
label = getattr(session, label_name)
style_sheet = ""
for selector, style in session_display_label_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
label.setStyleSheet(style_sheet)
# Apply font settings to session labels only if specified
if session and "label_fonts" in styles_dict:
font_settings = styles_dict["label_fonts"]
font = QtGui.QFont()
font.setFamily(font_settings.get("family", "Arial"))
font.setPointSize(font_settings.get("size", 10))
font.setBold(font_settings.get("bold", False))
font.setItalic(font_settings.get("italic", False))
font.setWeight(font_settings.get("weight", 50))
# Apply font only to session labels
for label_name in ["session_info", "timer_display"]:
if hasattr(session, label_name):
label = getattr(session, label_name)
label.setFont(font)
# Apply common button styles to QPushButton widgets
if "common_button_styles" in styles_dict:
button_styles = styles_dict["common_button_styles"]
for button_name in ["theme_options_button", "add_folders_button", "delete_sentences_preset", "open_preset_button","rainmeter_preset_button",
"delete_session_preset", "save_session_presets_button", "start_session_button", "close_window_button"]:
if hasattr(self, button_name):
button = getattr(self, button_name)
style_sheet = ""
for selector, style in button_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
button.setStyleSheet(style_sheet)
# Apply styles to other elements if needed
if "labels" in styles_dict:
label_styles = styles_dict["labels"]
for label_name in ["select_images", "label_7", "image_amount_label","sentence_amount_label", "duration_label", "label_5", "label_6"]:
if hasattr(self, label_name):
label = getattr(self, label_name)
style_sheet = ""
for selector, style in label_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
label.setStyleSheet(style_sheet)
if "common_spinbox_styles" in styles_dict:
spinbox_styles = styles_dict["common_spinbox_styles"]
for spinbox_name in ["set_seconds", "set_number_of_sentences", "set_minutes"]:
if hasattr(self, spinbox_name):
spinbox = getattr(self, spinbox_name)
style_sheet = ""
for selector, style in spinbox_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
spinbox.setStyleSheet(style_sheet)
if "common_checkbox_styles" in styles_dict:
checkbox_styles = styles_dict["common_checkbox_styles"]
style_sheet = ""
for selector, style in checkbox_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
# Assuming self has checkboxes that need styling
for checkbox_name in ["auto_start_toggle", "randomize_toggle","clipboard_toggle"]:
if hasattr(self, checkbox_name):
checkbox = getattr(self, checkbox_name)
checkbox.setStyleSheet(style_sheet)
if session and "session_buttons" in styles_dict:
button_styles = styles_dict["session_buttons"]
button_names = [
"grid_button", "toggle_highlight_button","color_text_button", "toggle_text_button",
"flip_horizontal_button", "flip_vertical_button",
"previous_sentence", "pause_timer", "stop_session",
"next_sentence", "copy_sentence_button", "clipboard_button","metadata_button",
"open_folder_button", "delete_sentence_button", "show_main_window_button"
]
for button_name in button_names:
if hasattr(session, button_name):
button = getattr(session, button_name)
style_sheet = ""
for selector, style in button_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
button.setStyleSheet(style_sheet)
except json.JSONDecodeError:
print("Error parsing theme file. Applying default styles.")
self.reset_default_themes()
else:
print("No theme selected or theme file not found. Applying default styles.")
self.reset_default_themes()
# Set item delegates and header settings for tables
max_length_delegate = MaxLengthDelegate(max_length=60)
self.table_sentences_selection.setItemDelegateForColumn(0, max_length_delegate)
self.table_session_selection.setItemDelegateForColumn(0, max_length_delegate)
# Prevent column resizing for table_sentences_selection
header_images = self.table_sentences_selection.horizontalHeader()
header_images.setSectionResizeMode(QHeaderView.Fixed)
header_images.setSectionsClickable(False) # Make header non-clickable
# Prevent column resizing for table_session_selection
header_session = self.table_session_selection.horizontalHeader()
header_session.setSectionResizeMode(QHeaderView.Fixed)
header_session.setSectionsClickable(False) # Make header non-clickable
# Ensure the selection behavior is correctly set after applying styles
self.table_session_selection.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.table_session_selection.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
def update_selection_cache(self):
"""
Initialize custom styles for the table widgets to change the selection color
and customize the header appearance.
"""
# Get the selected row
selected_sentence_row = self.table_sentences_selection.currentRow()
selected_preset_row = self.table_session_selection.currentRow()
self.sentence_selection_cache = selected_sentence_row
self.session_selection_cache = selected_preset_row
print("cache selected_sentence_row", selected_sentence_row)
print("cache session_selection_cache", selected_preset_row)
def create_preset(self, folder_list=None, keyword_profiles=None, preset_name="preset_output", highlight_keywords=True,
output_option="Single output", max_length=200, metadata_settings=True, output_folder=None, is_gui=True):
"""
Opens a dialog for folder selection, collects keyword profiles, and processes all EPUB, PDF, and TXT files
within the selected folders using the chosen profiles. Combines results from all folders.
"""
# Initialize selected_dirs
selected_dirs = folder_list if folder_list else []
if is_gui:
self.update_selection_cache()
preset_name = f'preset_{self.get_next_preset_number()}'
dialog = MultiFolderSelector(self, preset_name)
self.init_styles(dialog=dialog)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
selected_dirs = dialog.get_selected_folders()
highlight_keywords = dialog.get_highlight_keywords_option()
output_option = dialog.get_output_option()
metadata_settings = dialog.get_extract_metadata_option()
preset_name = dialog.get_preset_name()
max_length = dialog.get_max_length()
if not selected_dirs:
self.show_info_message('No Selection', 'No folders were selected.')
return
keyword_profiles = dialog.get_all_keyword_profiles()
else:
return
# Ensure we have directories to process
if not selected_dirs:
if is_gui:
self.show_info_message('No Selection', 'No folders were selected.')
return
# Dictionary to store all results
all_results = {}
total_sentences = 0 # Counter for total unique sentences
# Rest of the function remains the same...
for directory in selected_dirs:
if os.path.isdir(directory):
folder_results, folder_path = self.process_epub_folder(
directory, keyword_profiles, highlight_keywords,
output_option, preset_name, max_length, metadata_settings
)
# Merge results from this folder into all_results
for keyword, sentences in folder_results.items():
if keyword not in all_results:
all_results[keyword] = []
all_results[keyword].extend(sentences)
# Determine the output folder
target_folder = output_folder if output_folder else self.text_presets_dir
os.makedirs(target_folder, exist_ok=True)
# Create the combined output file and count unique sentences
combined_output_path = os.path.join(target_folder, f"{preset_name}.txt")
seen_sentences = set()
with open(combined_output_path, 'w', encoding='utf-8') as output_file:
for sentences in all_results.values():
for sentence, full_filepath in sentences:
sentence_key = (sentence, full_filepath)
if sentence_key not in seen_sentences:
seen_sentences.add(sentence_key)
total_sentences += 1
if metadata_settings:
try:
metadata = self.get_book_metadata(full_filepath)
output_file.write(f'["""{sentence}""","""{metadata}"""]\n\n')
except Exception as e:
print(f"Error extracting metadata from {os.path.basename(full_filepath)}: {e}")
output_file.write(f'{sentence}\n\n')
else:
output_file.write(f'{sentence}\n\n')
# If "All output" is selected, create individual keyword files
if output_option == "All output":
for keyword, sentences in all_results.items():
if sentences:
keyword_output_path = os.path.join(
target_folder, f"{preset_name}_{keyword}.txt"
)
with open(keyword_output_path, 'w', encoding='utf-8') as output_file:
for sentence, full_filepath in sentences:
if metadata_settings:
try:
metadata = self.get_book_metadata(full_filepath)
output_file.write(f'["""{sentence}""","""{metadata}"""]\n\n')
except Exception as e:
print(f"Error extracting metadata from {os.path.basename(full_filepath)}: {e}")
output_file.write(f'{sentence}\n\n')
else:
output_file.write(f'{sentence}\n\n')
print(f"Sentences for keyword '{keyword}' saved to {keyword_output_path}")
# Show summary message and reload presets if using GUI
summary_message = (f"Successfully extracted {total_sentences} unique sentences to: {combined_output_path}!")
if is_gui:
self.show_info_message('Extraction Complete', summary_message)
self.load_presets()
print(summary_message)
def create_keyword_profiles(self, keyword_input):
"""
Creates keyword profiles based on the user input.
"""
profiles = []
for kw in keyword_input:
if not kw.startswith(';'): # Ignore comments (those starting with ;)
profile = self.create_single_keyword_profile(kw) # Use a method to create a single keyword profile
profiles.append(profile)
return profiles
def create_single_keyword_profile(self, keyword):
"""
Creates a single keyword profile.
Modify this method based on how you want each keyword profile to be structured.
"""
# Example of simple profile creation
return {'keyword': keyword, 'options': {'highlight': True}} # Customize as necessary
########################################## TEXT PARSING ##########################################
########################################## TEXT PARSING ##########################################
########################################## TEXT PARSING ##########################################
def process_epub_folder(self, folder_path, keyword_profiles, highlight_keywords=True, output_option="Single output", preset_name="preset_output", max_length=200, metadata_settings=True):
"""
Process a folder of EPUB, PDF, or text files and return the extracted sentences.
Returns a tuple of (filtered_sentences, folder_path) where filtered_sentences is a dictionary
of keyword-sentence pairs with their complete file paths.
"""
"""
print("folder_path:", folder_path,
"profiles:", keyword_profiles,
"highlight_keywords:", highlight_keywords,
"output_option:", output_option,
"preset_name:", preset_name,
"max_length:", max_length)
"""
# Process ignored keywords
ignored_keywords = [
keyword[1:] for profile_keywords in keyword_profiles.values()
for keyword in profile_keywords if keyword.startswith('!')
]
for profile_keywords in keyword_profiles.values():
profile_keywords[:] = [keyword for keyword in profile_keywords if not keyword.startswith('!')]
# Remove duplicates across all profiles
seen_keywords = set()
for profile, keywords in keyword_profiles.items():
unique_keywords = []
for keyword in keywords:
if keyword not in seen_keywords:
unique_keywords.append(keyword)
seen_keywords.add(keyword)
keyword_profiles[profile] = unique_keywords
# Remove duplicates from ignored keywords
ignored_keywords = list(set(ignored_keywords))
print("Keywords by profile (unique):", keyword_profiles)
print("Ignored keywords (unique):", ignored_keywords)
# Gather all files in the specified folder
file_paths = [
os.path.join(folder_path, file) for file in os.listdir(folder_path)
if os.path.isfile(os.path.join(folder_path, file)) and
file.endswith(('.epub', '.pdf', '.txt'))
]
if not file_paths:
print(f"No supported files found in folder: {folder_path}")
return {}, folder_path
print(f"Found {len(file_paths)} files to process.")
# Initialize storage for combined sentences and processed keywords
combined_sentences = {
keyword: [] for keywords in keyword_profiles.values()
for keyword in keywords
}
processed_keywords = []
# Process all profiles and extract sentences
for profile_number, keywords in keyword_profiles.items():
if keywords:
self.extract_sentences_with_keywords(
file_paths, keywords, combined_sentences,
processed_keywords, max_length
)
# Filter out sentences with ignored keywords and store full file paths
filtered_sentences = {
keyword: [
(sentence, os.path.join(folder_path, filename))
for sentence, filename in sentences
if not self.contains_ignored_keyword(sentence, ignored_keywords)
]
for keyword, sentences in combined_sentences.items()
}
# Reset processed keywords for highlighting
processed_keywords = []
# Highlight keywords if requested
if highlight_keywords:
filtered_sentences = self.process_highlight_keywords(
filtered_sentences, keyword_profiles, processed_keywords
)
return filtered_sentences, folder_path
def get_book_metadata(self, file_path):
"""
Extract metadata from book files.
Returns a tuple of (title, author, date).
Falls back to filename for title if metadata unavailable.
"""
filename = os.path.basename(file_path)
filename_without_ext = os.path.splitext(filename)[0].replace('_', ' ')
# Default values
title = filename_without_ext
author = "Unknown Author"
date = "Unknown Date"
try:
if file_path.endswith('.epub'):
book = epub.read_epub(file_path)
# Get title
if book.get_metadata('DC', 'title'):
title = book.get_metadata('DC', 'title')[0][0]
# Get author
if book.get_metadata('DC', 'creator'):
author = book.get_metadata('DC', 'creator')[0][0]
# Get date
if book.get_metadata('DC', 'date'):
date = book.get_metadata('DC', 'date')[0][0]
# Try to extract just the year if it's a full date
year_match = re.search(r'\d{4}', date)
if year_match:
date = year_match.group(0)
elif file_path.endswith('.pdf'):
with open(file_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
if reader.metadata:
# Get title
if reader.metadata.get('/Title'):
title = reader.metadata['/Title']
# Get author
if reader.metadata.get('/Author'):
author = reader.metadata['/Author']
# Get date
if reader.metadata.get('/CreationDate'):
date_str = reader.metadata['/CreationDate']
# Try to extract year from PDF date format (D:YYYYMMDDHHmmSS)
year_match = re.search(r'D:(\d{4})', date_str)
if year_match:
date = year_match.group(1)
# Clean up any potential issues in the metadata
title = title.strip()
author = author.strip()
date = date.strip()
# If title is empty, use filename
if not title:
title = filename_without_ext
except Exception as e:
print(f"Error extracting metadata from {filename}: {str(e)}")
title = filename_without_ext
# Format the metadata string
metadata = f"{title}"
if author != "Unknown Author":
metadata += f" by {author}"
if date != "Unknown Date":
metadata += f" - {date}"
return metadata
def get_keyword_forms(self, keyword):
"""
Get the forms of a keyword, handling the '&' prefix and combined keywords.
Returns a list of forms and a boolean indicating if it's an exact match.
"""
if '+' in keyword:
# Split combined keywords and process each part
parts = [k.strip() for k in keyword.split('+')]
all_forms = []
exact_matches = []
for part in parts:
if part.startswith('&'):
all_forms.append([part[1:]]) # Exact form only
exact_matches.append(True)
else:
all_forms.append([self.get_singular_form(part), self.get_plural_form(part)])
exact_matches.append(False)
return all_forms, exact_matches
else:
if keyword.startswith('&'):
return [[keyword[1:]]], [True] # Single keyword, exact match
else:
return [[self.get_singular_form(keyword), self.get_plural_form(keyword)]], [False] # Single keyword, both forms
def contains_ignored_keyword(self, sentence, ignored_keywords):
for ignored_keyword in ignored_keywords:
# Handle cases with both forms ignored or only plural ignored
if ignored_keyword.startswith('!&'):
# Ignore only the plural form
base_ignored_keyword = ignored_keyword.lstrip('!&')
forms_to_ignore = [base_ignored_keyword] # Only plural form
else:
# Ignore both singular and plural forms
base_ignored_keyword = ignored_keyword.lstrip('!')
forms_to_ignore = self.get_keyword_forms(base_ignored_keyword) # Both forms
# Check if any form is present in the sentence
for form in forms_to_ignore:
if re.search(r'\b{}\b'.format(re.escape(form)), sentence, re.IGNORECASE):
return True
return False
def process_highlight_keywords(self, filtered_sentences, profiles, processed_keywords):
"""
Highlight keywords and their forms in sentences with the appropriate number of brackets based on the profile name.
"""
for profile_name, keywords in profiles.items():
# Extract the numeric part from the profile name (e.g., 'Keywords_1' -> 1)
match = re.search(r'(\d+)', profile_name)
bracket_count = int(match.group(1)) if match else 1 # Default to 1 if no number is found
# Construct the bracket style for this profile
left_bracket = "{" * bracket_count
right_bracket = "}" * bracket_count
# Process each keyword in the profile
for keyword in keywords:
# Get all forms of the keyword(s)
forms_list, exact_matches = self.get_keyword_forms(keyword)
# Flatten the forms list for highlighting
all_forms = [form for sublist in forms_list for form in sublist]
forms_lower = [form.lower() for form in all_forms]
if any(form in processed_keywords for form in forms_lower):
continue
# Create pattern to match any of the keyword forms
pattern = re.compile(
r'(?<!\w)({})\b'.format("|".join(map(re.escape, all_forms))),
re.IGNORECASE
)
# Highlight keywords in all sentences
for key, sentence_pairs in filtered_sentences.items():
for i, (sentence, filename) in enumerate(sentence_pairs):
def replace_func(match):
# Wrap the matched word in the appropriate brackets
original_word = match.group(0)
return f"{left_bracket}{original_word}{right_bracket}"