-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdialog_manager.py
More file actions
1794 lines (1540 loc) · 69.9 KB
/
dialog_manager.py
File metadata and controls
1794 lines (1540 loc) · 69.9 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
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
from typing import List, Tuple, Set, Optional
import webbrowser
import os
import logging
import time
from PyQt6.QtWidgets import (
QDialog,
QVBoxLayout,
QHBoxLayout,
QLabel,
QPushButton,
QCheckBox,
QMessageBox,
QFrame,
QGridLayout,
QSpacerItem,
QComboBox,
QSizePolicy,
QScrollArea,
QListWidget,
QListWidgetItem,
QStyle,
QRadioButton,
QSlider,
QLineEdit,
QPlainTextEdit,
QSpinBox,
)
from PyQt6.QtCore import Qt, QSize, QUrl, QEventLoop, QThread
from PyQt6.QtGui import QIcon, QDesktopServices
from core.app_settings import (
get_rotation_confirm_lossy,
get_preview_cache_size_gb,
get_exif_cache_size_mb,
)
from core.image_processing.raw_image_processor import is_raw_extension
from core.image_features.model_rotation_detector import (
ModelRotationDetector,
ModelNotFoundError,
)
from workers.thumbnail_preload_worker import ThumbnailPreloadWorker
logger = logging.getLogger(__name__)
class DialogManager:
"""A manager class for handling the creation of dialogs."""
THUMBNAIL_PRELOAD_ASYNC_THRESHOLD = 20
def __init__(self, parent):
"""
Initialize the DialogManager.
Args:
parent: The parent widget, typically the MainWindow.
"""
self.parent = parent
# Instance-level placeholder for non-blocking About dialog reference
self._about_dialog_ref = None
def _should_apply_raw_processing(self, file_path: str) -> bool:
"""Determine if RAW processing should be applied to the given file."""
if not file_path:
return False
ext = os.path.splitext(file_path)[1].lower()
return is_raw_extension(ext)
def _has_raw_images(self, file_paths: List[str]) -> bool:
"""Check if any of the provided file paths are RAW image files."""
for path in file_paths:
if self._should_apply_raw_processing(path):
return True
return False
def show_about_dialog(self, block: bool = True):
"""Show the 'About' dialog.
Args:
block: If True (default) runs dialog.exec() modally. If False, uses
dialog.show() and returns immediately (useful for tests).
"""
logger.info("Showing about dialog")
dialog = QDialog(self.parent)
dialog.setWindowTitle("About PhotoSort")
dialog.setObjectName("aboutDialog")
dialog.setModal(True)
dialog.setFixedSize(480, 420)
dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
# Make window frameless for a cleaner UI
dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowType.FramelessWindowHint)
# Main layout
main_layout = QVBoxLayout(dialog)
main_layout.setSpacing(15)
main_layout.setContentsMargins(25, 25, 25, 25)
# Compact header section
header_frame = QFrame()
header_frame.setObjectName("aboutHeader")
header_layout = QHBoxLayout(header_frame)
header_layout.setSpacing(15)
header_layout.setContentsMargins(20, 15, 20, 15)
# Enable dragging the frameless window by the header
_drag_state = {"offset": None}
def _header_mouse_press(e):
if e.button() == Qt.MouseButton.LeftButton:
_drag_state["offset"] = (
e.globalPosition().toPoint() - dialog.frameGeometry().topLeft()
)
e.accept()
def _header_mouse_move(e):
if (e.buttons() & Qt.MouseButton.LeftButton) and _drag_state[
"offset"
] is not None:
dialog.move(e.globalPosition().toPoint() - _drag_state["offset"])
e.accept()
# Assign simple drag handlers to the header frame
header_frame.mousePressEvent = _header_mouse_press # type: ignore[assignment]
header_frame.mouseMoveEvent = _header_mouse_move # type: ignore[assignment]
# App info (left side)
app_info_layout = QVBoxLayout()
app_info_layout.setSpacing(3)
title_label = QLabel("PhotoSort")
title_label.setObjectName("aboutTitle")
app_info_layout.addWidget(title_label)
# Version label (populated only in packaged builds)
version_text = None
try:
# Populated by CI during packaged builds in core/build_info.py
from core.build_info import VERSION # type: ignore
version_text = str(VERSION).strip() or None
except (ImportError, AttributeError):
version_text = None
version_label = QLabel()
version_label.setObjectName("aboutVersion")
if version_text:
version_label.setText(f"Version {version_text}")
version_label.setVisible(True)
else:
# In local dev runs (python src/main.py), no version is shown
version_label.setVisible(False)
app_info_layout.addWidget(version_label)
header_layout.addLayout(app_info_layout)
header_layout.addStretch()
main_layout.addWidget(header_frame)
# Content section
content_layout = QVBoxLayout()
content_layout.setSpacing(15)
# Technology section
tech_title = QLabel("Technology Stack")
tech_title.setObjectName("aboutSectionTitle")
content_layout.addWidget(tech_title)
# Tech details in a more compact grid
tech_frame = QFrame()
tech_frame.setObjectName("aboutTechFrame")
tech_layout = QVBoxLayout(tech_frame)
tech_layout.setSpacing(6)
tech_layout.setContentsMargins(15, 10, 15, 10)
clustering_info = "Clustering Algorithm: DBSCAN (scikit-learn)"
# Get ONNX provider information
try:
model_detector = ModelRotationDetector()
# Lazy detector exposes provider via internal state after load attempt
onnx_provider = (
getattr(model_detector._state, "provider_name", None)
or "N/A (model not loaded)"
)
except ModelNotFoundError:
onnx_provider = "N/A (model not found)"
except Exception:
onnx_provider = "N/A (error)"
embeddings_label_ref = None
tech_items = [
"🧠 Embeddings: SentenceTransformer (CLIP)",
f"🤖 Rotation Model: ONNX Runtime on {onnx_provider}",
f"🔍 {clustering_info}",
"📋 Metadata: pyexiv2 • 🎨 Interface: PyQt6 • 🐍 Runtime: Python",
]
for i, item in enumerate(tech_items):
item_label = QLabel(item)
item_label.setObjectName("aboutTechItem")
item_label.setWordWrap(True)
tech_layout.addWidget(item_label)
if i == 0: # Embeddings item
embeddings_label_ref = item_label
content_layout.addWidget(tech_frame)
# Actions row: Open Models + Logs + GitHub
actions_layout = QHBoxLayout()
actions_layout.addStretch()
# Open Models Folder button
models_button = QPushButton("📦 Open Models Folder")
models_button.setObjectName("aboutModelsButton")
models_button.setToolTip(
"Open the folder where ONNX rotation models are stored"
)
models_button.clicked.connect(self._open_models_folder)
actions_layout.addWidget(models_button)
# Open Logs Folder button
logs_button = QPushButton("🗂️ Open Logs Folder")
logs_button.setObjectName("aboutLogsButton")
logs_button.setToolTip("Open the folder where PhotoSort writes its log file")
logs_button.clicked.connect(self._open_logs_folder)
actions_layout.addWidget(logs_button)
# GitHub button
github_button = QPushButton("🔗 View on GitHub")
github_button.setObjectName("aboutGithubButton")
github_button.clicked.connect(
lambda: webbrowser.open("https://github.com/duartebarbosadev/PhotoSort")
)
actions_layout.addWidget(github_button)
content_layout.addLayout(actions_layout)
# Add content to main layout
main_layout.addLayout(content_layout)
# Spacer
main_layout.addSpacerItem(
QSpacerItem(
20, 20, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding
)
)
# Footer with close button
footer_layout = QHBoxLayout()
footer_layout.addStretch()
close_button = QPushButton("Close")
close_button.setObjectName("aboutCloseButton")
close_button.clicked.connect(dialog.accept)
close_button.setDefault(True)
footer_layout.addWidget(close_button)
main_layout.addLayout(footer_layout)
# Styling is handled by dark_theme.qss
# Start CUDA detection worker
worker_manager = self.parent.app_controller.worker_manager
if embeddings_label_ref:
def update_embeddings_label(available):
try:
if embeddings_label_ref:
embeddings_label_ref.setText(
f"🧠 Embeddings: SentenceTransformer (CLIP) on {'GPU (CUDA)' if available else 'CPU'}"
)
except RuntimeError:
pass # Label has been deleted
worker_manager.cuda_detection_finished.connect(update_embeddings_label)
worker_manager.start_cuda_detection()
if block:
dialog.exec()
logger.info("Closed about dialog")
else: # non-blocking path for automated tests
# Keep a reference to prevent garbage collection in tests
self._about_dialog_ref = dialog # type: ignore[attr-defined]
dialog.show()
logger.info("Showing about dialog (non-blocking mode)")
def _open_logs_folder(self):
"""Open the application's logs directory in the system file browser."""
try:
logs_dir = os.path.join(os.path.expanduser("~"), ".photosort_logs")
os.makedirs(logs_dir, exist_ok=True)
url = QUrl.fromLocalFile(logs_dir)
opened = QDesktopServices.openUrl(url)
if not opened:
logger.warning(
"QDesktopServices failed to open logs folder: %s", logs_dir
)
except Exception:
logger.error("Failed to open logs folder", exc_info=True)
def _open_models_folder(self):
"""Open the models directory (where ONNX model files live) in the system file browser.
Strategy:
- Prefer ./models next to the running app (CWD/models), creating it if missing.
- Fallback to project-root/models (useful in dev), creating if needed.
"""
try:
cwd_models = os.path.join(os.getcwd(), "models")
project_root = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
dev_models = os.path.join(project_root, "models")
# Choose the best target: existing CWD/models, else existing dev models, else create CWD/models
target = (
cwd_models
if os.path.isdir(cwd_models)
else (dev_models if os.path.isdir(dev_models) else cwd_models)
)
os.makedirs(target, exist_ok=True)
url = QUrl.fromLocalFile(os.path.abspath(target))
opened = QDesktopServices.openUrl(url)
if not opened:
logger.warning(
"QDesktopServices failed to open models folder: %s", target
)
except Exception:
logger.error("Failed to open models folder", exc_info=True)
def show_lossy_rotation_confirmation_dialog(
self, filename: str, rotation_type: str
) -> Tuple[bool, bool]:
"""
Show a confirmation dialog for lossy rotation with a 'never ask again' option.
Args:
filename: The name of the file being rotated.
rotation_type: A description of the rotation (e.g., "90° clockwise").
Returns:
A tuple containing (proceed_with_rotation: bool, never_ask_again: bool).
"""
logger.info(f"Showing lossy rotation confirmation dialog for {filename}")
if not get_rotation_confirm_lossy():
logger.info(
"Lossy rotation confirmation disabled, proceeding without asking"
)
return True, False # Proceed without asking if the setting is disabled
dialog = QDialog(self.parent)
dialog.setWindowTitle("Confirm Lossy Rotation")
dialog.setObjectName("lossyRotationDialog")
dialog.setModal(True)
dialog.setFixedSize(480, 200)
# Frameless window for fancy UI
dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowType.FramelessWindowHint)
layout = QVBoxLayout(dialog)
layout.setSpacing(20)
layout.setContentsMargins(25, 25, 25, 25)
message_text = f"Lossless rotation failed for:\n{filename}"
warning_text = f"Proceed with lossy rotation {rotation_type}?\nThis will re-encode the image and may reduce quality."
if "images" in filename.lower(): # Batch operation
warning_text = f"Proceed with lossy rotation {rotation_type} for all selected images?\nThis will re-encode the images and may reduce quality."
message_label = QLabel(message_text)
message_label.setObjectName("lossyRotationMessageLabel")
message_label.setWordWrap(True)
layout.addWidget(message_label)
warning_label = QLabel(warning_text)
warning_label.setObjectName("lossyRotationWarningLabel")
warning_label.setWordWrap(True)
layout.addWidget(warning_label)
never_ask_checkbox = QCheckBox("Don't ask again for lossy rotations")
never_ask_checkbox.setObjectName("neverAskAgainCheckbox")
layout.addWidget(never_ask_checkbox)
button_layout = QHBoxLayout()
button_layout.addStretch()
cancel_button = QPushButton("Cancel")
cancel_button.setObjectName("lossyRotationCancelButton")
cancel_button.clicked.connect(dialog.reject)
button_layout.addWidget(cancel_button)
proceed_button = QPushButton("Proceed with Lossy Rotation")
proceed_button.setObjectName("lossyRotationProceedButton")
proceed_button.clicked.connect(dialog.accept)
proceed_button.setDefault(True)
button_layout.addWidget(proceed_button)
layout.addLayout(button_layout)
# Styling is handled by dark_theme.qss
result = dialog.exec()
proceed = result == QDialog.DialogCode.Accepted
never_ask_again = never_ask_checkbox.isChecked()
logger.info(
f"User {'proceeded' if proceed else 'cancelled'} lossy rotation dialog, "
f"never ask again: {never_ask_again}"
)
return proceed, never_ask_again
def show_preferences_dialog(self):
"""Show the application preferences dialog."""
from core.app_settings import (
PerformanceMode,
get_performance_mode,
set_performance_mode,
get_custom_thread_count,
set_custom_thread_count,
get_best_shot_engine,
set_best_shot_engine,
get_best_shot_batch_size,
set_best_shot_batch_size,
get_openai_config,
set_openai_config,
DEFAULT_OPENAI_API_KEY,
DEFAULT_OPENAI_MODEL,
DEFAULT_OPENAI_BASE_URL,
DEFAULT_OPENAI_MAX_TOKENS,
DEFAULT_OPENAI_TIMEOUT,
DEFAULT_OPENAI_MAX_WORKERS,
)
from core.ai.best_shot_pipeline import (
DEFAULT_BEST_SHOT_PROMPT,
DEFAULT_RATING_PROMPT,
)
logger.info("Showing preferences dialog")
dialog = QDialog(self.parent)
dialog.setWindowTitle("Preferences")
dialog.setObjectName("preferencesDialog")
dialog.setModal(True)
dialog.resize(640, 600)
dialog.setMinimumSize(520, 480)
# Frameless window for consistent UI
dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowType.FramelessWindowHint)
main_layout = QVBoxLayout(dialog)
main_layout.setSpacing(20)
main_layout.setContentsMargins(25, 25, 25, 25)
# Title
title_label = QLabel("Preferences")
title_label.setObjectName("aboutTitle")
main_layout.addWidget(title_label)
scroll_area = QScrollArea()
scroll_area.setObjectName("preferencesScrollArea")
scroll_area.setWidgetResizable(True)
main_layout.addWidget(scroll_area)
content_frame = QFrame()
content_layout = QVBoxLayout(content_frame)
content_layout.setSpacing(20)
content_layout.setContentsMargins(0, 0, 0, 0)
scroll_area.setWidget(content_frame)
# Performance Mode Section
perf_section_label = QLabel("Performance Mode")
perf_section_label.setObjectName("preferencesSectionLabel")
perf_section_label.setStyleSheet("font-weight: bold; font-size: 13px;")
content_layout.addWidget(perf_section_label)
# Description
desc_label = QLabel(
"Control how many CPU threads PhotoSort uses for processing:"
)
desc_label.setWordWrap(True)
content_layout.addWidget(desc_label)
# Radio buttons for performance mode
balanced_radio = QRadioButton("Balanced (Recommended)")
balanced_radio.setObjectName("balancedRadio")
balanced_desc = QLabel(" Uses 85% of CPU cores to keep system responsive")
balanced_desc.setObjectName("radioDescription")
balanced_desc.setStyleSheet("color: #888; font-size: 11px; margin-left: 20px;")
performance_radio = QRadioButton("Performance")
performance_radio.setObjectName("performanceRadio")
perf_desc = QLabel(" Uses all available CPU cores for maximum speed")
perf_desc.setObjectName("radioDescription")
perf_desc.setStyleSheet("color: #888; font-size: 11px; margin-left: 20px;")
custom_radio = QRadioButton("Custom")
custom_radio.setObjectName("customRadio")
# Custom thread count slider in a horizontal layout
custom_control_layout = QVBoxLayout()
custom_control_layout.setContentsMargins(20, 5, 0, 0)
custom_control_layout.setSpacing(5)
# Get system CPU count
max_threads = os.cpu_count() or 4
# Label showing current value and range
current_thread_count = min(get_custom_thread_count(), max_threads)
thread_count_label = QLabel(
f"Thread count: {current_thread_count} (max: {max_threads})"
)
thread_count_label.setObjectName("threadCountLabel")
thread_count_label.setStyleSheet("color: #888; font-size: 11px;")
custom_control_layout.addWidget(thread_count_label)
# Slider
thread_count_slider = QSlider(Qt.Orientation.Horizontal)
thread_count_slider.setObjectName("threadCountSlider")
thread_count_slider.setMinimum(1)
thread_count_slider.setMaximum(max_threads)
thread_count_slider.setValue(current_thread_count)
thread_count_slider.setTickPosition(QSlider.TickPosition.TicksBelow)
# Set tick interval based on max threads (show ~8 ticks)
tick_interval = max(1, max_threads // 8)
thread_count_slider.setTickInterval(tick_interval)
thread_count_slider.setEnabled(False)
# Update label when slider changes
def on_slider_changed(value):
thread_count_label.setText(f"Thread count: {value} (max: {max_threads})")
thread_count_slider.valueChanged.connect(on_slider_changed)
custom_control_layout.addWidget(thread_count_slider)
# Set current mode
current_mode = get_performance_mode()
if current_mode == PerformanceMode.BALANCED:
balanced_radio.setChecked(True)
elif current_mode == PerformanceMode.PERFORMANCE:
performance_radio.setChecked(True)
else: # CUSTOM
custom_radio.setChecked(True)
thread_count_slider.setEnabled(True)
# Enable/disable slider based on custom radio selection
def on_custom_toggled(checked):
thread_count_slider.setEnabled(checked)
thread_count_label.setEnabled(checked)
custom_radio.toggled.connect(on_custom_toggled)
on_custom_toggled(custom_radio.isChecked())
# Add all radio options to layout
content_layout.addWidget(balanced_radio)
content_layout.addWidget(balanced_desc)
content_layout.addWidget(performance_radio)
content_layout.addWidget(perf_desc)
content_layout.addWidget(custom_radio)
content_layout.addLayout(custom_control_layout)
# Note
note_label = QLabel("Note: Changes take effect immediately for new operations.")
note_label.setWordWrap(True)
note_label.setStyleSheet(
"color: #888; font-style: italic; font-size: 11px; margin-top: 10px;"
)
content_layout.addWidget(note_label)
# AI Engine Section
ai_section_label = QLabel("AI Rating Engine")
ai_section_label.setObjectName("preferencesSectionLabel")
ai_section_label.setStyleSheet("font-weight: bold; font-size: 13px;")
content_layout.addWidget(ai_section_label)
ai_desc_label = QLabel(
"Choose between the on-device model and the OpenAI LLM for image ranking and ratings."
)
ai_desc_label.setWordWrap(True)
content_layout.addWidget(ai_desc_label)
engine_combo = QComboBox()
engine_combo.setObjectName("bestShotEngineCombo")
engine_combo.addItem("Local (on-device models)", "local")
engine_combo.addItem("OpenAI (LLM)", "llm")
content_layout.addWidget(engine_combo)
openai_config = get_openai_config()
api_key_value = openai_config.get("api_key") or DEFAULT_OPENAI_API_KEY
model_value = openai_config.get("model") or DEFAULT_OPENAI_MODEL
base_url_value = openai_config.get("base_url") or DEFAULT_OPENAI_BASE_URL
try:
max_tokens_value = int(
openai_config.get("max_tokens") or DEFAULT_OPENAI_MAX_TOKENS
)
except (TypeError, ValueError):
max_tokens_value = DEFAULT_OPENAI_MAX_TOKENS
try:
timeout_value = int(openai_config.get("timeout") or DEFAULT_OPENAI_TIMEOUT)
except (TypeError, ValueError):
timeout_value = DEFAULT_OPENAI_TIMEOUT
try:
max_workers_value = int(
openai_config.get("max_workers") or DEFAULT_OPENAI_MAX_WORKERS
)
except (TypeError, ValueError):
max_workers_value = DEFAULT_OPENAI_MAX_WORKERS
best_prompt_value = (
openai_config.get("best_shot_prompt") or DEFAULT_BEST_SHOT_PROMPT
)
rating_prompt_value = (
openai_config.get("rating_prompt") or DEFAULT_RATING_PROMPT
)
current_engine = (get_best_shot_engine() or "local").lower()
index = engine_combo.findData(current_engine)
if index >= 0:
engine_combo.setCurrentIndex(index)
openai_frame = QFrame()
openai_frame.setObjectName("openAISettingsFrame")
openai_frame.setFrameShape(QFrame.Shape.StyledPanel)
openai_layout = QVBoxLayout(openai_frame)
openai_layout.setSpacing(12)
openai_layout.setContentsMargins(15, 12, 15, 12)
openai_info_label = QLabel(
"Configure OpenAI access used by the LLM engine. Leave prompts blank to use defaults."
)
openai_info_label.setWordWrap(True)
openai_info_label.setStyleSheet("color: #888; font-size: 11px;")
openai_layout.addWidget(openai_info_label)
openai_form = QGridLayout()
openai_form.setHorizontalSpacing(12)
openai_form.setVerticalSpacing(12)
api_key_label = QLabel("API Key")
api_key_input = QLineEdit()
api_key_input.setObjectName("openAIKeyInput")
api_key_input.setEchoMode(QLineEdit.EchoMode.Password)
api_key_input.setPlaceholderText("sk-...")
api_key_input.setClearButtonEnabled(True)
api_key_input.setText(api_key_value)
openai_form.addWidget(api_key_label, 0, 0)
openai_form.addWidget(api_key_input, 0, 1)
model_label = QLabel("Model")
model_combo = QComboBox()
model_combo.setObjectName("openAIModelCombo")
model_combo.setEditable(True)
model_combo.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
model_combo.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed
)
if model_value:
model_combo.addItem(model_value)
model_combo.setCurrentText(model_value)
else:
model_combo.setCurrentText(DEFAULT_OPENAI_MODEL)
fetch_models_button = QPushButton("Fetch Models")
fetch_models_button.setObjectName("openAIFetchModelsButton")
model_row = QHBoxLayout()
model_row.setContentsMargins(0, 0, 0, 0)
model_row.setSpacing(6)
model_row.addWidget(model_combo)
model_row.addWidget(fetch_models_button)
openai_form.addWidget(model_label, 1, 0)
openai_form.addLayout(model_row, 1, 1)
base_url_label = QLabel("Base URL")
base_url_input = QLineEdit()
base_url_input.setObjectName("openAIBaseUrlInput")
base_url_input.setPlaceholderText(DEFAULT_OPENAI_BASE_URL)
base_url_input.setClearButtonEnabled(True)
base_url_input.setText(base_url_value)
openai_form.addWidget(base_url_label, 2, 0)
openai_form.addWidget(base_url_input, 2, 1)
max_tokens_label = QLabel("Max Tokens")
max_tokens_spin = QSpinBox()
max_tokens_spin.setObjectName("openAIMaxTokensSpin")
max_tokens_spin.setRange(64, 32768)
max_tokens_spin.setSingleStep(64)
max_tokens_spin.setValue(max_tokens_value)
openai_form.addWidget(max_tokens_label, 3, 0)
openai_form.addWidget(max_tokens_spin, 3, 1)
timeout_label = QLabel("Timeout (s)")
timeout_spin = QSpinBox()
timeout_spin.setObjectName("openAITimeoutSpin")
timeout_spin.setRange(10, 600)
timeout_spin.setSingleStep(5)
timeout_spin.setValue(timeout_value)
openai_form.addWidget(timeout_label, 4, 0)
openai_form.addWidget(timeout_spin, 4, 1)
max_workers_label = QLabel("Concurrent Workers")
max_workers_spin = QSpinBox()
max_workers_spin.setObjectName("openAIMaxWorkersSpin")
max_workers_spin.setRange(1, 16)
max_workers_spin.setValue(max_workers_value)
openai_form.addWidget(max_workers_label, 5, 0)
openai_form.addWidget(max_workers_spin, 5, 1)
best_shot_batch_label = QLabel("Best-shot Batch Size")
best_shot_batch_spin = QSpinBox()
best_shot_batch_spin.setObjectName("bestShotBatchSpin")
best_shot_batch_spin.setRange(2, 12)
best_shot_batch_spin.setValue(get_best_shot_batch_size())
openai_form.addWidget(best_shot_batch_label, 6, 0)
openai_form.addWidget(best_shot_batch_spin, 6, 1)
best_prompt_label = QLabel("Best Shot Prompt")
best_prompt_edit = QPlainTextEdit()
best_prompt_edit.setObjectName("openAIBestPromptEdit")
best_prompt_edit.setPlaceholderText(
"Leave blank to use the default best-shot prompt."
)
best_prompt_edit.setPlainText(best_prompt_value)
best_prompt_edit.setMinimumHeight(80)
openai_form.addWidget(best_prompt_label, 7, 0, Qt.AlignmentFlag.AlignTop)
openai_form.addWidget(best_prompt_edit, 7, 1)
rating_prompt_label = QLabel("Rating Prompt")
rating_prompt_edit = QPlainTextEdit()
rating_prompt_edit.setObjectName("openAIRatingPromptEdit")
rating_prompt_edit.setPlaceholderText(
"Leave blank to use the default rating prompt."
)
rating_prompt_edit.setPlainText(rating_prompt_value)
rating_prompt_edit.setMinimumHeight(80)
openai_form.addWidget(rating_prompt_label, 8, 0, Qt.AlignmentFlag.AlignTop)
openai_form.addWidget(rating_prompt_edit, 8, 1)
test_connection_button = QPushButton("Test Connection")
test_connection_button.setObjectName("openAITestConnectionButton")
def _resolve_or_default(value: str, default_value: str) -> str:
stripped = value.strip()
return stripped or default_value
def _create_openai_client():
try:
from openai import OpenAI # type: ignore
except ImportError:
QMessageBox.warning(
dialog,
"OpenAI Package Missing",
"Install the 'openai' package to test the connection.",
)
return None
try:
return OpenAI(
api_key=_resolve_or_default(
api_key_input.text(), DEFAULT_OPENAI_API_KEY
),
base_url=_resolve_or_default(
base_url_input.text(), DEFAULT_OPENAI_BASE_URL
),
timeout=timeout_spin.value(),
)
except Exception as exc: # pragma: no cover - defensive
QMessageBox.critical(
dialog,
"Client Creation Failed",
f"Unable to create OpenAI client:\n{exc}",
)
return None
def _extract_model_ids(response) -> Set[str]:
model_ids: Set[str] = set()
data = getattr(response, "data", None)
if data is None and isinstance(response, dict):
data = response.get("data")
if not data:
return model_ids
for entry in data:
if isinstance(entry, dict):
identifier = entry.get("id") or entry.get("name")
else:
identifier = getattr(entry, "id", None) or getattr(
entry, "name", None
)
if identifier:
model_ids.add(str(identifier))
return model_ids
def handle_test_connection():
client = _create_openai_client()
if client is None:
return
test_connection_button.setEnabled(False)
fetch_models_button.setEnabled(False)
try:
probe_timeout = min(timeout_spin.value(), 30)
probe_client = (
client.with_options(timeout=probe_timeout)
if hasattr(client, "with_options")
else client
)
models_start = time.perf_counter()
response = probe_client.models.list()
models_duration = time.perf_counter() - models_start
model_ids = _extract_model_ids(response)
test_model = _resolve_or_default(
model_combo.currentText(), DEFAULT_OPENAI_MODEL
)
completion_duration: Optional[float] = None
completion_error: Optional[Exception] = None
try:
completion_client = (
client.with_options(timeout=probe_timeout)
if hasattr(client, "with_options")
else client
)
completion_start = time.perf_counter()
completion_client.chat.completions.create(
model=test_model,
messages=[
{
"role": "user",
"content": "PhotoSort connectivity check.",
}
],
max_tokens=8,
)
completion_duration = time.perf_counter() - completion_start
except Exception as exc: # pragma: no cover - network dependent
completion_error = exc
if completion_error is None:
QMessageBox.information(
dialog,
"Connection Successful",
(
f"Models endpoint responded in {models_duration:.2f}s ("
f"{len(model_ids)} models).\n"
f"Chat completion succeeded in {completion_duration:.2f}s using '{test_model}'."
),
)
else:
QMessageBox.warning(
dialog,
"Partial Success",
(
f"Models endpoint responded in {models_duration:.2f}s ("
f"{len(model_ids)} models).\n"
f"Chat completion failed for '{test_model}':\n{completion_error}"
),
)
except Exception as exc: # pragma: no cover - network dependent
QMessageBox.critical(
dialog,
"Connection Failed",
f"Connection test failed:\n{exc}",
)
finally:
test_connection_button.setEnabled(True)
fetch_models_button.setEnabled(True)
def handle_fetch_models():
client = _create_openai_client()
if client is None:
return
test_connection_button.setEnabled(False)
fetch_models_button.setEnabled(False)
start = time.perf_counter()
try:
probe_client = (
client.with_options(timeout=min(timeout_spin.value(), 30))
if hasattr(client, "with_options")
else client
)
response = probe_client.models.list()
duration = time.perf_counter() - start
model_ids = _extract_model_ids(response)
if not model_ids:
QMessageBox.information(
dialog,
"No Models Found",
"The endpoint is reachable but returned no models.",
)
else:
existing_text = model_combo.currentText().strip()
sorted_ids = sorted(model_ids)
model_combo.blockSignals(True)
model_combo.clear()
for identifier in sorted_ids:
model_combo.addItem(identifier)
if existing_text and existing_text in model_ids:
model_combo.setCurrentText(existing_text)
else:
model_combo.setCurrentText(sorted_ids[0])
if existing_text and existing_text not in model_ids:
model_combo.insertItem(0, existing_text)
model_combo.setCurrentIndex(0)
model_combo.blockSignals(False)
QMessageBox.information(
dialog,
"Models Retrieved",
(
f"Loaded {len(model_ids)} models in {duration:.2f}s.\n"
"You can pick one from the dropdown."
),
)
except Exception as exc: # pragma: no cover - network dependent
QMessageBox.critical(
dialog,
"Fetch Models Failed",
f"Failed to fetch models:\n{exc}",
)
finally:
fetch_models_button.setEnabled(True)
test_connection_button.setEnabled(True)
fetch_models_button.clicked.connect(handle_fetch_models)
test_connection_button.clicked.connect(handle_test_connection)
openai_layout.addLayout(openai_form)
buttons_row = QHBoxLayout()
buttons_row.setContentsMargins(0, 0, 0, 0)
buttons_row.setSpacing(6)
buttons_row.addWidget(test_connection_button)
buttons_row.addStretch()
openai_layout.addLayout(buttons_row)
content_layout.addWidget(openai_frame)
def update_openai_visibility():
openai_frame.setVisible(engine_combo.currentData() == "llm")
engine_combo.currentIndexChanged.connect(update_openai_visibility)
update_openai_visibility()
content_layout.addStretch()
# Buttons
button_layout = QHBoxLayout()
button_layout.addStretch()
cancel_button = QPushButton("Cancel")
cancel_button.setObjectName("preferencesCancelButton")
cancel_button.clicked.connect(dialog.reject)
button_layout.addWidget(cancel_button)
save_button = QPushButton("Save")
save_button.setObjectName("preferencesSaveButton")
save_button.setDefault(True)
def save_preferences():
if balanced_radio.isChecked():
set_performance_mode(PerformanceMode.BALANCED)
elif performance_radio.isChecked():
set_performance_mode(PerformanceMode.PERFORMANCE)
else: # custom_radio.isChecked()
set_performance_mode(PerformanceMode.CUSTOM)
set_custom_thread_count(thread_count_slider.value())
set_best_shot_engine(engine_combo.currentData())
api_key_text = api_key_input.text().strip()
base_url_text = base_url_input.text().strip()
model_text = model_combo.currentText().strip()
max_tokens_value = max_tokens_spin.value()
timeout_value = timeout_spin.value()
max_workers_value = max_workers_spin.value()
best_shot_batch_value = best_shot_batch_spin.value()
best_prompt_text = best_prompt_edit.toPlainText()
rating_prompt_text = rating_prompt_edit.toPlainText()
def _value_or_none(value: str, default_value: str) -> Optional[str]:
trimmed = value.strip()
if not trimmed or trimmed == default_value:
return ""
return trimmed
set_openai_config(
api_key=_value_or_none(api_key_text, DEFAULT_OPENAI_API_KEY),
model=_value_or_none(model_text, DEFAULT_OPENAI_MODEL),
base_url=_value_or_none(base_url_text, DEFAULT_OPENAI_BASE_URL),
max_tokens=None
if max_tokens_value == DEFAULT_OPENAI_MAX_TOKENS
else max_tokens_value,
timeout=None
if timeout_value == DEFAULT_OPENAI_TIMEOUT
else timeout_value,
max_workers=None
if max_workers_value == DEFAULT_OPENAI_MAX_WORKERS
else max_workers_value,
best_shot_prompt=None
if best_prompt_text.strip() == DEFAULT_BEST_SHOT_PROMPT.strip()
else best_prompt_text.strip() or None,
rating_prompt=None
if rating_prompt_text.strip() == DEFAULT_RATING_PROMPT.strip()