-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1400 lines (1171 loc) · 58.7 KB
/
app.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 sys
import atexit
import os
import logging
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, QPushButton, QComboBox, QLabel, QSpinBox, QCheckBox, QGroupBox, QGridLayout, QProgressBar, QDialog, QListWidget, QListWidgetItem, QMessageBox, QShortcut, QSlider, QLineEdit, QTabWidget
from PyQt5.QtGui import QIcon, QClipboard, QMovie, QTextCursor, QKeySequence
from PyQt5.QtCore import Qt, QTimer, pyqtSlot, QObject, QThread, pyqtSignal
import keyboard as kb
import requests
import time
import win32clipboard
import win32con
import json
import ctypes
from datetime import datetime
import speech_recognition as sr
import pyttsx3
# Setup logging configuration
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def cleanup_lock_file():
try:
if os.path.exists('writer_assistant.lock'):
os.remove('writer_assistant.lock')
except Exception:
pass
# Register the cleanup function to run on exit
atexit.register(cleanup_lock_file)
class TextAssistantApp(QObject):
def __init__(self):
super().__init__()
logger.info("Initializing Text Assistant Application")
# Initialize dark_mode with a default value
self.dark_mode = False
# Set the app ID before creating QApplication
myappid = 'sahil.textassistant.1.0' # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
# Create QApplication with sys.argv
self.app = QApplication(sys.argv)
# Set application icon
app_icon = QIcon("icon.png")
self.app.setWindowIcon(app_icon)
self.setup_tray()
# Initialize settings file path
self.settings_file = "settings.json"
# Initialize user details
self.user_details = {}
# Initialize the popup before loading settings
self.popup = AssistantPopup(self.app, self.user_details, self)
# Load settings after initializing the popup
self.load_settings()
self.setup_global_shortcut()
self._show_popup_impl()
logger.debug("Initial popup instance created")
def setup_tray(self):
logger.debug("Setting up system tray icon")
self.tray = QSystemTrayIcon()
try:
self.tray.setIcon(QIcon("icon.png"))
logger.debug("Tray icon loaded successfully")
except Exception as e:
logger.error(f"Failed to load tray icon: {str(e)}")
# Create tray menu
menu = QMenu()
open_action = menu.addAction("Open Assistant")
open_action.triggered.connect(self.trigger_popup)
quit_action = menu.addAction("Quit")
quit_action.triggered.connect(self.app.quit)
self.tray.setContextMenu(menu)
self.tray.show()
logger.debug("Tray menu setup completed")
# Connect the tray icon's activated signal
self.tray.activated.connect(self.on_tray_icon_activated)
def setup_global_shortcut(self):
logger.debug("Registering global hotkey (Ctrl+Shift+A)")
try:
# Remove any existing hotkey first
try:
kb.remove_hotkey('ctrl+shift+a')
except Exception as e:
logger.debug(f"Error removing existing hotkey: {str(e)}")
# Register the new hotkey
kb.add_hotkey(
'ctrl+shift+a',
self.trigger_popup,
suppress=False # Change to False to avoid suppressing key events
)
logger.info("Global hotkey registered successfully")
except Exception as e:
logger.error(f"Failed to register global hotkey: {str(e)}")
def trigger_popup(self):
"""Common method to trigger popup display"""
logger.debug("Trigger popup called")
# Use invokeMethod to ensure we're on the main thread
QTimer.singleShot(0, self._show_popup_impl)
@pyqtSlot()
def _show_popup_impl(self):
try:
logger.debug("Executing show popup implementation")
# Ensure popup exists
if not self.popup:
logger.debug("Creating new popup instance")
self.popup = AssistantPopup(self.app, self.user_details, self)
# Temporarily set window to stay on top
self.popup.setWindowFlags(
Qt.Window |
Qt.WindowCloseButtonHint |
Qt.WindowMinimizeButtonHint |
Qt.WindowStaysOnTopHint
)
# Force window to be visible and active
self.popup.show()
self.popup.setWindowState(self.popup.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)
# Reset window flags after a short delay
QTimer.singleShot(500, self._reset_window_flags)
logger.info("Popup window display triggered")
except Exception as e:
logger.error(f"Error showing popup: {str(e)}", exc_info=True)
def _reset_window_flags(self):
"""Reset window flags to normal after ensuring window is visible"""
self.popup.setWindowFlags(
Qt.Window |
Qt.WindowCloseButtonHint |
Qt.WindowMinimizeButtonHint
)
self.popup.show()
self.popup.raise_()
self.popup.activateWindow()
def run(self):
logger.info("Starting application main loop")
return self.app.exec_()
def on_tray_icon_activated(self, reason):
if reason == QSystemTrayIcon.Trigger: # Single click
self._show_popup_impl()
def save_settings(self):
settings = {
"dark_mode": self.dark_mode,
"last_options": self.get_current_options(),
"user_details": self.user_details,
"model_name": self.popup.model_combo.currentText(),
"last_profile": self.popup.profile_combo.currentText()
}
with open(self.settings_file, "w") as f:
json.dump(settings, f)
def load_settings(self):
if os.path.exists(self.settings_file):
with open(self.settings_file, "r") as f:
settings = json.load(f)
self.dark_mode = settings.get("dark_mode", False)
self.apply_dark_mode()
self.set_last_options(settings.get("last_options", {}))
self.user_details = settings.get("user_details", {})
# Load model name
model_name = settings.get("model_name", "mistral:7b")
if model_name in [self.popup.model_combo.itemText(i) for i in range(self.popup.model_combo.count())]:
self.popup.model_combo.setCurrentText(model_name)
# Load last used profile
last_profile = settings.get("last_profile", "<default>")
if last_profile in [self.popup.profile_combo.itemText(i) for i in range(self.popup.profile_combo.count())]:
self.popup.profile_combo.setCurrentText(last_profile)
def toggle_dark_mode(self):
self.dark_mode = not self.dark_mode
self.apply_dark_mode()
self.save_settings()
def apply_dark_mode(self):
if self.dark_mode:
self.popup.setStyleSheet("background-color: #1e1e1e; color: #FFFFFF;")
else:
self.popup.setStyleSheet("")
def get_current_options(self):
# Access UI elements from the AssistantPopup instance
return {
'tone': self.popup.tone_combo.currentText(),
'length': self.popup.length_combo.currentText(),
'format': self.popup.format_combo.currentText(),
'language': self.popup.language_combo.currentText(),
'fix_grammar': self.popup.fix_grammar.isChecked(),
'fix_spelling': self.popup.fix_spelling.isChecked(),
'improve_clarity': self.popup.improve_clarity.isChecked()
}
def set_last_options(self, options):
self.popup.tone_combo.setCurrentText(options.get('tone', 'Professional'))
self.popup.length_combo.setCurrentText(options.get('length', 'Keep Original'))
self.popup.format_combo.setCurrentText(options.get('format', 'Plain Text'))
self.popup.language_combo.setCurrentText(options.get('language', 'English'))
self.popup.fix_grammar.setChecked(options.get('fix_grammar', True))
self.popup.fix_spelling.setChecked(options.get('fix_spelling', True))
self.popup.improve_clarity.setChecked(options.get('improve_clarity', True))
def save_user_details(self, details):
self.user_details = details
self.save_settings()
def open_personalization_dialog(self):
dialog = PersonalizationDialog(self)
dialog.accepted.connect(self.load_profiles) # Connect accepted signal
dialog.rejected.connect(self.load_profiles) # Connect rejected signal
dialog.exec_()
class AssistantPopup(QWidget):
def __init__(self, app, user_details, main_app):
logger.debug("Initializing Assistant Popup")
super().__init__()
self.app = app
self.user_details = user_details
self.main_app = main_app # Store reference to main app
# Set application icon
app_icon = QIcon("icon.png")
self.app.setWindowIcon(app_icon)
# Set window-specific icon
self.setWindowIcon(app_icon)
self.setWindowFlags(
Qt.Window |
Qt.WindowCloseButtonHint |
Qt.WindowMinimizeButtonHint
)
self.recognizer = sr.Recognizer()
self.engine = pyttsx3.init()
self.init_ui()
# Store the original clipboard content
self.original_clipboard = None
self.clipboard = QApplication.clipboard()
self.is_getting_text = False
self.OLLAMA_API_URL = "http://localhost:11434/api"
self.is_generating = False
self.current_response = None
# Fetch available models when initializing
self.fetch_available_models()
# Add history related attributes
self.history_file = "enhancement_history.json"
self.max_history_items = 50
self.history_data = self.load_history()
def fetch_available_models(self):
"""Fetch available models from Ollama API"""
logger.debug("Fetching available Ollama models")
try:
response = requests.get(f"{self.OLLAMA_API_URL}/tags")
if response.status_code == 200:
models = [model['name'] for model in response.json().get('models', [])]
logger.debug(f"Found models: {models}")
self.model_combo.clear()
self.model_combo.addItems(models)
# Set default model if available
default_model = "mistral:7b"
if default_model in models:
self.model_combo.setCurrentText(default_model)
else:
logger.error(f"Failed to fetch models: {response.status_code}")
self.model_combo.addItem("mistral:7b") # Fallback option
except Exception as e:
logger.error(f"Error fetching models: {str(e)}")
self.model_combo.addItem("mistral:7b") # Fallback option
def init_ui(self):
logger.debug("Setting up popup UI")
self.setWindowTitle('Text Assistant by Sahil Powered by Ollama')
self.setWindowIcon(QIcon("icon.png"))
self.setGeometry(405, 140, 800, 800) # Center the window on a 1920x1080 screen
# Create main horizontal layout
main_layout = QHBoxLayout()
self.setLayout(main_layout)
# Left side layout
left_layout = QVBoxLayout()
# Personalization Section
personalization_layout = QHBoxLayout()
# Profile Selection
self.profile_combo = QComboBox()
self.profile_combo.addItem("<default>")
self.load_profiles()
personalization_layout.addWidget(QLabel("Profile:"))
personalization_layout.addWidget(self.profile_combo)
# User Personalization Button
self.personalization_btn = QPushButton("User Personalization")
self.personalization_btn.clicked.connect(self.open_personalization_dialog)
personalization_layout.addWidget(self.personalization_btn)
# Dark Mode Toggle Button
self.dark_mode_btn = QPushButton("Toggle Dark Mode")
self.dark_mode_btn.clicked.connect(self.main_app.toggle_dark_mode)
personalization_layout.addWidget(self.dark_mode_btn)
# Add personalization layout to left_layout
left_layout.addLayout(personalization_layout)
# Enhancement Options
controls_group = QGroupBox("Enhancement Options")
controls_layout = QVBoxLayout()
# Model Selection
model_layout = QHBoxLayout()
model_label = QLabel("Model:")
self.model_combo = QComboBox()
self.model_combo.addItem("Loading models...")
model_layout.addWidget(model_label)
model_layout.addWidget(self.model_combo)
controls_layout.addLayout(model_layout)
# Tone Selection
tone_layout = QHBoxLayout()
tone_label = QLabel("Tone:")
self.tone_combo = QComboBox()
self.tone_combo.addItems([
"Professional", "Casual", "Friendly", "Formal",
"Academic", "Creative", "Persuasive", "Enthusiastic"
])
tone_layout.addWidget(tone_label)
tone_layout.addWidget(self.tone_combo)
controls_layout.addLayout(tone_layout)
# Length Control
length_layout = QHBoxLayout()
length_label = QLabel("Target Length:")
self.length_combo = QComboBox()
self.length_combo.addItems([
"Keep Original", "Make Shorter", "Make Longer",
"Very Concise", "Detailed"
])
length_layout.addWidget(length_label)
length_layout.addWidget(self.length_combo)
controls_layout.addLayout(length_layout)
# Format Options
format_layout = QHBoxLayout()
format_label = QLabel("Format:")
self.format_combo = QComboBox()
self.format_combo.addItems([
"Plain Text", "Markdown", "HTML", "Email",
"Blog Post", "Social Media"
])
format_layout.addWidget(format_label)
format_layout.addWidget(self.format_combo)
controls_layout.addLayout(format_layout)
# Language Options
language_layout = QHBoxLayout()
language_label = QLabel("Language:")
self.language_combo = QComboBox()
self.language_combo.addItems([
"English", "Spanish", "French", "German",
"Chinese", "Japanese", "Korean"
])
language_layout.addWidget(language_label)
language_layout.addWidget(self.language_combo)
controls_layout.addLayout(language_layout)
# Additional Options
options_layout = QHBoxLayout()
self.fix_grammar = QCheckBox("Fix Grammar")
self.fix_spelling = QCheckBox("Fix Spelling")
self.improve_clarity = QCheckBox("Improve Clarity")
options_layout.addWidget(self.fix_grammar)
options_layout.addWidget(self.fix_spelling)
options_layout.addWidget(self.improve_clarity)
controls_layout.addLayout(options_layout)
# Add template feature
self.add_templates_feature(controls_layout)
controls_group.setLayout(controls_layout)
left_layout.addWidget(controls_group)
# Prompt Editor
prompt_group = QGroupBox("Prompt Editor")
prompt_layout = QVBoxLayout()
self.prompt_editor = QTextEdit()
self.prompt_editor.setPlaceholderText("The AI prompt will be displayed here based on your selected options...")
prompt_layout.addWidget(self.prompt_editor)
prompt_group.setLayout(prompt_layout)
left_layout.addWidget(prompt_group)
# Input Text Area
input_group = QGroupBox("Input Text")
input_layout = QVBoxLayout()
self.input_text = QTextEdit()
self.input_text.setPlaceholderText("Enter or paste your text here...")
input_layout.addWidget(self.input_text)
input_group.setLayout(input_layout)
left_layout.addWidget(input_group)
# Add left layout to main layout
main_layout.addLayout(left_layout)
# Right side layout for AI-generated response
right_layout = QVBoxLayout()
# Output Area
output_group = QGroupBox("Enhanced Text")
output_group.setFixedWidth(600) # Set fixed width for the right side
output_layout = QVBoxLayout()
self.output_text = QTextEdit()
self.output_text.setReadOnly(True)
output_layout.addWidget(self.output_text)
output_group.setLayout(output_layout)
right_layout.addWidget(output_group)
# Action Buttons
right_buttons_layout = QHBoxLayout()
# Add a spacer to push buttons to the right
right_buttons_layout.addStretch()
# Copy Button
self.copy_btn = QPushButton("Copy to Clipboard")
self.copy_btn.clicked.connect(self.copy_to_clipboard)
self.copy_btn.setFixedSize(150, 25)
right_buttons_layout.addWidget(self.copy_btn)
# Add voice output button
self.voice_output_btn = QPushButton("Voice Output")
self.voice_output_btn.clicked.connect(self.voice_output)
self.voice_output_btn.setFixedSize(150, 25)
right_buttons_layout.addWidget(self.voice_output_btn)
right_layout.addLayout(right_buttons_layout)
# Add right layout to main layout
main_layout.addLayout(right_layout)
# Action Buttons
buttons_layout = QHBoxLayout()
self.get_text_btn = QPushButton("Get Selected Text")
self.get_text_btn.clicked.connect(self.get_selected_text)
buttons_layout.addWidget(self.get_text_btn)
# Create enhance and stop buttons
self.enhance_btn = QPushButton("Enhance Text")
self.enhance_btn.clicked.connect(self.enhance_text)
buttons_layout.addWidget(self.enhance_btn)
self.stop_btn = QPushButton("Stop Generation")
self.stop_btn.clicked.connect(self.stop_generation)
self.stop_btn.setEnabled(False) # Disabled by default
buttons_layout.addWidget(self.stop_btn)
self.clear_btn = QPushButton("Clear")
self.clear_btn.clicked.connect(self.clear_text)
buttons_layout.addWidget(self.clear_btn)
# Add History button to buttons_layout
self.history_btn = QPushButton("History")
self.history_btn.clicked.connect(self.show_history)
buttons_layout.addWidget(self.history_btn)
# Add voice input button
self.voice_input_btn = QPushButton("Voice Input")
self.voice_input_btn.clicked.connect(self.voice_input)
buttons_layout.addWidget(self.voice_input_btn)
left_layout.addLayout(buttons_layout)
# Connect option changes to prompt update
self.model_combo.currentTextChanged.connect(self.update_prompt_preview)
self.tone_combo.currentTextChanged.connect(self.update_prompt_preview)
self.length_combo.currentTextChanged.connect(self.update_prompt_preview)
self.format_combo.currentTextChanged.connect(self.update_prompt_preview)
self.language_combo.currentTextChanged.connect(self.update_prompt_preview)
self.fix_grammar.stateChanged.connect(self.update_prompt_preview)
self.fix_spelling.stateChanged.connect(self.update_prompt_preview)
self.improve_clarity.stateChanged.connect(self.update_prompt_preview)
self.profile_combo.currentTextChanged.connect(self.update_prompt_preview)
# Set default options
self.fix_grammar.setChecked(True)
self.fix_spelling.setChecked(True)
self.improve_clarity.setChecked(True)
logger.debug("Popup UI setup completed")
def add_templates_feature(self, controls_layout):
"""Add a template selection feature to the UI."""
template_layout = QHBoxLayout()
template_label = QLabel("Templates:")
self.template_combo = QComboBox()
self.template_combo.addItems([
"Email Response",
"Professional Letter",
"Meeting Minutes",
"Blog Post",
"Social Media Post",
"Technical Documentation"
])
template_layout.addWidget(template_label)
template_layout.addWidget(self.template_combo)
controls_layout.addLayout(template_layout)
# Connect template selection to a method
self.template_combo.currentTextChanged.connect(self.apply_template)
def apply_template(self, template_name):
"""Apply structured writing templates for various formats."""
logger.debug(f"Applying template: {template_name}")
templates = {
"Email Response": "Dear [Name],\n\nThank you for your email. I will get back to you shortly.\n\nBest regards,\n[Your Name]",
"Professional Letter": "Dear [Recipient],\n\nI am writing to express my thoughts on...\n\nSincerely,\n[Your Name]",
"Meeting Minutes": "Meeting Date: [Date]\nAttendees: [Names]\n\nAgenda:\n1. [Topic]\n\nMinutes:\n- [Details]",
"Blog Post": "Title: [Title]\n\nIntroduction:\n[Introduction]\n\nMain Content:\n[Content]\n\nConclusion:\n[Conclusion]",
"Social Media Post": "[Your message here] #hashtag",
"Technical Documentation": "## [Feature Name]\n\n### Overview\n[Description]\n\n### Usage\n[Instructions]",
"Business Proposal": "## Executive Summary\n[Summary]\n\n## Objectives\n[Objectives]\n\n## Approach\n[Approach]\n\n## Conclusion\n[Conclusion]",
"Formal Report": "# [Report Title]\n\n## Introduction\n[Introduction]\n\n## Findings\n[Findings]\n\n## Conclusion\n[Conclusion]\n\n## Recommendations\n[Recommendations]"
}
self.input_text.setPlainText(templates.get(template_name, ""))
def get_selected_text(self):
"""
Gets selected text using Windows clipboard
"""
logger.debug("Getting selected text")
try:
# Store current clipboard content
win32clipboard.OpenClipboard()
try:
if win32clipboard.IsClipboardFormatAvailable(win32con.CF_UNICODETEXT):
self.original_clipboard = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
else:
self.original_clipboard = ""
except Exception as e:
logger.error(f"Clipboard error: {str(e)}")
finally:
win32clipboard.CloseClipboard()
# Hide window temporarily
self.hide()
# Longer delay to ensure window is hidden
time.sleep(0.3)
# Simulate Ctrl+C using a more reliable method
kb.press('ctrl')
time.sleep(0.1)
kb.press('c')
time.sleep(0.1)
kb.release('c')
kb.release('ctrl')
# Wait longer for clipboard to update
time.sleep(0.5)
# Get the copied text
win32clipboard.OpenClipboard()
try:
new_text = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
if new_text and new_text != self.original_clipboard:
logger.debug(f"Successfully got selected text: {new_text[:50]}...")
self.input_text.setPlainText(new_text)
else:
logger.debug("No text was selected")
except Exception as e:
logger.debug(f"Failed to get clipboard data: {str(e)}")
new_text = ""
finally:
win32clipboard.CloseClipboard()
# Restore original clipboard
if self.original_clipboard:
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(self.original_clipboard)
win32clipboard.CloseClipboard()
logger.debug("Restored original clipboard content")
except Exception as e:
logger.error(f"Error in get_selected_text: {str(e)}")
finally:
# Always show the window again
self.show()
self.activateWindow()
self.raise_()
def enhance_text(self):
"""Enhance the selected text using the AI model"""
try:
input_text = self.input_text.toPlainText().strip()
if not input_text:
QMessageBox.warning(self, "Warning", "Please enter some text to enhance.")
return
# Check if a custom prompt is provided in the prompt editor
custom_prompt = self.prompt_editor.toPlainText().strip()
if custom_prompt:
# Replace placeholder with actual input text
prompt = custom_prompt.replace("[Your text will appear here]", input_text)
logger.debug("Final Prompt: %s", prompt)
else:
QMessageBox.warning(self, "Warning", "Please enter some text to enhance.")
return
# Ensure options is defined before this point
if 'options' not in locals():
options = {} # or set a default value if necessary
# Clear previous output
self.output_text.clear()
self.is_generating = True
self.update_ui_state()
# Start streaming process in a separate thread
self.thread = QThread()
self.worker = StreamWorker(prompt)
self.worker.moveToThread(self.thread)
# Connect signals
self.thread.started.connect(self.worker.run)
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
# Connect streaming signal
self.worker.new_text.connect(self.update_output_text)
self.worker.finished.connect(lambda: self.generation_finished(input_text, options))
# Start the thread
self.thread.start()
except Exception as e:
logger.error(f"Error in enhance_text: {str(e)}", exc_info=True)
self.finish_generation()
def stop_generation(self):
"""Stop the current text generation"""
if hasattr(self, 'worker'):
self.worker.stop() # Call the stop method on the worker
if hasattr(self, 'thread') and self.thread.isRunning():
self.thread.quit()
self.is_generating = False
self.update_ui_state()
logger.debug("Text generation stopped by user")
def finish_generation(self):
"""Clean up after generation is complete"""
self.is_generating = False
self.current_response = None
self.enhance_btn.setEnabled(True)
self.stop_btn.setEnabled(False)
self.loading_label.hide()
self.loading_movie.stop()
self.app.processEvents()
def _construct_prompt(self, text, options):
"""Construct a refined prompt based on selected options"""
instructions = [
"You are a highly skilled Australian professional writer with expertise in structured writing frameworks, stylistic techniques, and content methodology. You specialize in creating high-quality, clear, and engaging text across various formats and tones. Follow professional writing best practices and ensure readability."
]
# Add user details to the prompt
if self.user_details:
instructions.append(f"Use necessary User Details: Name: {self.user_details.get('name', 'N/A')}, Position: {self.user_details.get('position', 'N/A')}, Email: {self.user_details.get('email', 'N/A')}, Phone: {self.user_details.get('phone', 'N/A')}, Project: {self.user_details.get('project', 'N/A')}")
# Add profile data to the prompt
selected_profile = self.profile_combo.currentText()
if selected_profile != "<default>":
profile_data = self.load_profile(selected_profile)
instructions.append(f"Profile: {profile_data}")
# Add tone instruction
tone_mapping = {
"Friendly": "Ensure the tone is warm, engaging, and conversational.",
"Casual": "Use a relaxed and informal tone with natural flow.",
"Formal": "Maintain a respectful and official tone appropriate for profe ssional settings.",
"Academic": "Ensure precise, well-structured writing with formal vocabulary.",
"Creative": "Incorporate engaging storytelling and imaginative elements.",
"Persuasive": "Use compelling language to convince and influence.",
"Enthusiastic": "Express excitement and positive energy in the writing."
}
if options['tone'] != "Professional": # Default is Professional
instructions.append(tone_mapping.get(options['tone'], "Use a professional and clear tone."))
else:
instructions.append("Ensure the tone remains neutral, clear, and professional.")
# Add length instruction
length_mapping = {
"Make Shorter": "Make the text more concise while retaining key points.",
"Make Longer": "Expand the content with additional relevant details while improving clarity.",
"Very Concise": "Eliminate all unnecessary words and make the text as brief yet meaningful as possible.",
"Detailed": "Elaborate on key points with supporting details and examples."
}
# Check for conflicting length options
if options['length'] in ["Make Shorter", "Very Concise"] and options['length'] in ["Make Longer", "Detailed"]:
instructions.append("Prioritize clarity while balancing brevity and detail as needed.")
else:
instructions.append(length_mapping.get(options['length'], "Keep the original length."))
# Update format instruction
format_mapping = {
"Email": "Ensure the response follows a well-structured email format with a proper greeting, body, and closing. Maintain professionalism and clarity.",
"Markdown": "Use proper Markdown formatting with headings, bullet points, and links where appropriate.",
"HTML": "Structure the text using HTML elements like <p>, <h1>, and <ul> as needed.",
"Blog Post": "Ensure engaging blog-style formatting with an introduction, main content, and conclusion.",
"Social Media": "Keep the format suitable for social media with hashtags, mentions, and engaging language."
}
if options['format'] != "Plain Text":
instructions.append(format_mapping.get(options['format'], "Use standard plain text formatting."))
# Add specific email formatting instructions
if options['format'] == "Email":
instructions.append("Maintain standard email etiquette: use a proper greeting, clear paragraphs, and an appropriate closing signature.")
# Add language instruction
if options['language'] != "English":
instructions.append(f"Translate the final result to {options['language']}.")
# Add optional improvements
if options['fix_grammar']:
instructions.append("Fix all grammar issues for proper readability.")
if options['improve_clarity']:
instructions.append("Ensure clarity by improving sentence structure and coherence.")
if options['fix_spelling']:
instructions.append("Correct any spelling mistakes while keeping appropriate terminology.")
# Add Do Not instructions to prevent unwanted modifications
instructions.append("Do not alter the meaning of the text or remove critical details.")
instructions.append("Ensure a natural and professional flow suitable for the context.")
# Add context instruction
if options['format'] == "Email":
instructions.append("Consider the full email conversation provided. Ensure the response aligns with prior messages and answers any outstanding questions.")
# Construct the final prompt
instruction_text = "\n- ".join(instructions) # Bullet point formatting
prompt = f"""Instructions:{instruction_text}\n\nPlease enhance the following text according to the above instructions:\n\n{text}"""
return prompt
def clear_text(self):
"""Clear the input and output text areas"""
self.input_text.clear()
self.output_text.clear()
logger.debug("Clear text triggered")
def copy_to_clipboard(self):
"""
Copy the enhanced text to clipboard and hide the popup
"""
logger.debug("Copying enhanced text to clipboard")
try:
text = self.output_text.toPlainText()
if text:
self.clipboard.setText(text)
logger.debug("Text successfully copied to clipboard")
self.hide() # Hide the popup after copying
logger.debug("Popup hidden after copying")
else:
logger.debug("No text to copy")
except Exception as e:
logger.error(f"Error copying to clipboard: {str(e)}")
def showEvent(self, event):
"""Ensure proper window display"""
super().showEvent(event)
self.setWindowState(Qt.WindowActive)
self.raise_()
self.activateWindow()
logger.debug("Popup show event processed")
def closeEvent(self, event):
"""Override close event to hide instead of close"""
event.ignore()
self.hide()
logger.debug("Popup hidden instead of closed")
def update_prompt_preview(self):
"""Update the prompt preview based on selected options"""
options = {
'tone': self.tone_combo.currentText(),
'length': self.length_combo.currentText(),
'format': self.format_combo.currentText(),
'language': self.language_combo.currentText(),
'fix_grammar': self.fix_grammar.isChecked(),
'fix_spelling': self.fix_spelling.isChecked(),
'improve_clarity': self.improve_clarity.isChecked()
}
# Use the existing _construct_prompt method with a placeholder text
preview_text = "[Your text will appear here]"
prompt = self._construct_prompt(preview_text, options)
self.prompt_editor.setPlainText(prompt)
def load_history(self):
"""Load history from JSON file"""
try:
if os.path.exists(self.history_file):
with open(self.history_file, 'r', encoding='utf-8') as f:
return json.load(f)
return []
except Exception as e:
logger.error(f"Error loading history: {str(e)}")
return []
def save_to_history(self, input_text, output_text, options):
"""Save enhancement to history"""
try:
history_entry = {
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'input_text': input_text[:200] + '...' if len(input_text) > 200 else input_text,
'output_text': output_text,
'options': options
}
self.history_data.insert(0, history_entry)
self.history_data = self.history_data[:self.max_history_items]
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump(self.history_data, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"Error saving to history: {str(e)}")
def show_history(self):
"""Show history dialog"""
history_dialog = QDialog(self)
history_dialog.setWindowTitle("Enhancement History")
history_dialog.setMinimumWidth(600)
history_dialog.setMinimumHeight(400)
layout = QVBoxLayout()
# Create search input
search_input = QLineEdit()
search_input.setPlaceholderText("Search history...")
layout.addWidget(search_input)
# Create list widget for history items
list_widget = QListWidget()
layout.addWidget(list_widget)
# Populate list widget with history data
def populate_list():
list_widget.clear()
for entry in self.history_data:
timestamp = entry['timestamp']
preview = entry['input_text'][:50] + '...'
item = QListWidgetItem(f"{timestamp} - {preview}")
item.setData(Qt.UserRole, entry)
list_widget.addItem(item)
populate_list()
# Add buttons
button_layout = QHBoxLayout()
load_btn = QPushButton("Load Selected")
delete_btn = QPushButton("Delete Selected")
clear_btn = QPushButton("Clear History")
button_layout.addWidget(load_btn)
button_layout.addWidget(delete_btn)
button_layout.addWidget(clear_btn)
layout.addLayout(button_layout)
history_dialog.setLayout(layout)
# Connect button actions
def load_selected():
current_item = list_widget.currentItem()
if current_item:
entry = current_item.data(Qt.UserRole)
self.input_text.setPlainText(entry['input_text'])
self.output_text.setPlainText(entry['output_text'])
# Restore options with default values if keys are missing
options = entry.get('options', {})
self.tone_combo.setCurrentText(options.get('tone', 'Professional'))
self.length_combo.setCurrentText(options.get('length', 'Keep Original'))
self.format_combo.setCurrentText(options.get('format', 'Plain Text'))
self.language_combo.setCurrentText(options.get('language', 'English'))
self.fix_grammar.setChecked(options.get('fix_grammar', True))
self.fix_spelling.setChecked(options.get('fix_spelling', True))
self.improve_clarity.setChecked(options.get('improve_clarity', True))
history_dialog.accept()
def delete_selected():
current_row = list_widget.currentRow()
if current_row >= 0:
list_widget.takeItem(current_row)
del self.history_data[current_row]
self.save_history()
def clear_history():
if QMessageBox.question(history_dialog, 'Clear History',
'Are you sure you want to clear all history?',
QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes:
list_widget.clear()
self.history_data.clear()
self.save_history()
load_btn.clicked.connect(load_selected)
delete_btn.clicked.connect(delete_selected)
clear_btn.clicked.connect(clear_history)
# Implement search functionality
def filter_history():
query = search_input.text().lower()
list_widget.clear()
for entry in self.history_data:
if query in entry['input_text'].lower() or query in entry['output_text'].lower():
item = QListWidgetItem(f"{entry['timestamp']} - {entry['input_text'][:50]}...")
item.setData(Qt.UserRole, entry)
list_widget.addItem(item)
search_input.textChanged.connect(filter_history)
history_dialog.exec_()
def update_output_text(self, new_text):
"""Update the output text with new streaming content"""
cursor = self.output_text.textCursor()
cursor.movePosition(QTextCursor.End)
cursor.insertText(new_text)
self.output_text.setTextCursor(cursor)
def generation_finished(self, input_text, options):
"""Handle completion of text generation"""
self.is_generating = False
self.update_ui_state()
# Save to history
self.save_to_history(
input_text,
self.output_text.toPlainText(),
options
)
def update_ui_state(self):
"""Update UI elements based on generation state"""
# Enable/disable buttons based on generation state
self.enhance_btn.setEnabled(not self.is_generating)
self.stop_btn.setEnabled(self.is_generating)
self.clear_btn.setEnabled(not self.is_generating)
self.get_text_btn.setEnabled(not self.is_generating)
# Update cursor
if self.is_generating:
QApplication.setOverrideCursor(Qt.WaitCursor)
else:
QApplication.restoreOverrideCursor()
def voice_input(self):
"""Capture voice input and set it to the input text area."""
try:
with sr.Microphone() as source:
self.recognizer.adjust_for_ambient_noise(source, duration=1) # Noise adaptation
logger.debug("Listening for voice input...")