-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
368 lines (312 loc) · 12.3 KB
/
app.py
File metadata and controls
368 lines (312 loc) · 12.3 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
import sys
import os
import dotenv
from PySide6.QtWidgets import (
QApplication,
QWidget,
QVBoxLayout,
QHBoxLayout,
QPushButton,
QFileDialog,
QLabel,
QMessageBox,
QTextEdit,
QSizePolicy,
QDialog,
QLineEdit,
QComboBox,
)
from PySide6.QtGui import QIcon
from PySide6.QtCore import Qt, QThread, Signal
from PySide6.QtGui import QFont
from src.Sortly import Sortly
dotenv.load_dotenv(override=True)
print("Environment variables loaded.")
if not os.getenv("OPENAI_API_KEY"):
print("Warning: OPENAI_API_KEY is not set in the environment variables.")
QFont("Segoe UI", 22, QFont.Bold)
class SortWorker(QThread):
progress = Signal(str)
finished = Signal(str)
def __init__(self, folder_path, user_prompt, sortly):
super().__init__()
self.folder_path = folder_path
self.user_prompt = user_prompt
self.sortly = sortly
def run(self):
try:
chunk_size = 100 # Process files in chunks of 100
all_files = os.listdir(self.folder_path)
chunks = [all_files[i:i + chunk_size] for i in range(0, len(all_files), chunk_size)]
for idx, chunk in enumerate(chunks, start=1):
user_message = f"Sort this folder: {self.folder_path} with the contents: {chunk}."
if self.user_prompt:
user_message += f" {self.user_prompt}"
self.progress.emit(f"Processing chunk {idx} of {len(chunks)}...")
message = self.sortly.sort_folder(user_prompt=user_message)
if message is None:
self.progress.emit("Error: Failed to sort files. Check API key.")
return
self.progress.emit(f"Chunk {idx} done: {message}")
self.finished.emit("All chunks sorted.")
except Exception as e:
import traceback
error = f"Exception occurred:\n{traceback.format_exc()} api_key: {os.getenv('OPENAI_API_KEY')}\nError: {str(e)}"
self.progress.emit(error)
class SortlyApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Sortly")
self.setWindowIcon(QIcon("icons/sortly.png"))
self.setGeometry(100, 100, 800, 400)
self.is_dark = False
main_layout = QVBoxLayout()
main_layout.setContentsMargins(20, 20, 20, 20)
main_layout.setSpacing(15)
self.setLayout(main_layout)
# Title row layout with centered title and right-aligned theme button
title_row = QHBoxLayout()
# Title label (expand to fill space, centered alignment)
self.title_label = QLabel("Sortly: Your Folder Organizer Assistant")
self.title_label.setFont(QFont("Segoe UI", 22, QFont.Bold))
self.title_label.setAlignment(Qt.AlignCenter)
self.title_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
# Container layout to help keep alignment clean
title_container = QHBoxLayout()
title_container.addStretch()
title_container.addWidget(self.title_label)
title_container.addStretch()
# Theme toggle button
self.theme_button = QPushButton()
self.theme_button.setFont(QFont("Segoe UI Emoji", 16))
self.theme_button.setObjectName("theme_button")
self.theme_button.setIcon(QIcon("icons/moon.png"))
self.theme_button.setFixedSize(40, 40)
self.theme_button.clicked.connect(self.toggle_theme)
self.theme_button.setToolTip("Toggle Dark/Light Theme")
# Main title row with title in center and button on right
title_row.addLayout(title_container, stretch=8)
title_row.addWidget(self.theme_button, alignment=Qt.AlignRight)
# Add title row to the main layout
main_layout.addLayout(title_row)
title_separator = QLabel()
title_separator.setFixedHeight(1)
title_separator.setStyleSheet("background-color: #cccccc;" if not self.is_dark else "background-color: #555;")
main_layout.addWidget(title_separator)
self.current_key = os.getenv("OPENAI_API_KEY", "Please set your API key in the environment variables.")
# Prepare display key: first 4 chars + '******' if key is longer than 4, else show as is
api_row = QHBoxLayout()
if len(self.current_key) > 4 and "Please" not in self.current_key:
display_key = self.current_key[:4] + "******"
else:
display_key = self.current_key
# Create QLineEdit initialized with masked key
self.api_key_input = QLineEdit()
self.api_key_input.setText(display_key)
self.api_key_input.setPlaceholderText("Enter your API key here...")
self.api_key_input.setFixedHeight(30)
self.api_key_input.setMinimumWidth(250)
api_row.addWidget(self.api_key_input)
self.api_key_button = QPushButton("Set new API Key")
self.api_key_button.setFixedHeight(40)
self.api_key_button.clicked.connect(self.save_api_key)
api_row.addWidget(self.api_key_button)
option_label = QLabel("Select model:")
self.option_dropdown = QComboBox()
self.option_dropdown.addItems(self.supported_models.keys())
self.option_dropdown.setFixedWidth(140)
self.option_dropdown.currentTextChanged.connect(self.on_option_changed)
api_row.addStretch() # Push dropdown to right
api_row.addWidget(option_label)
api_row.addWidget(self.option_dropdown)
main_layout.addLayout(api_row)
self.folder_label = QLabel("No folder selected")
self.folder_label.setWordWrap(True)
self.folder_label.setAlignment(Qt.AlignCenter)
main_layout.addWidget(self.folder_label)
# Select folder button
self.select_button = QPushButton("Select Folder")
self.select_button.clicked.connect(self.select_folder)
main_layout.addWidget(self.select_button, alignment=Qt.AlignCenter)
# Text box
self.text_input = QTextEdit()
self.text_input.setPlaceholderText(
"Write your prompt here or just use the default one by clicking 'Sort..."
)
main_layout.addWidget(self.text_input)
self.sort_button = QPushButton("Sort")
self.sort_button.clicked.connect(self.sort_files)
main_layout.addWidget(self.sort_button, alignment=Qt.AlignCenter)
self.folder_path = None
self.model = "gemini-2.0-flash"
self.endpoint = self.supported_models.get(self.model, "https://generativelanguage.googleapis.com/v1beta/openai/")
self.files_content = []
self.apply_theme()
supported_models = {
"gemini-2.0-flash": "https://generativelanguage.googleapis.com/v1beta/openai/",
"gpt-4.1": "https://api.openai.com/v1/",
"gpt-4o": "https://api.openai.com/v1/",
"o4-mini": "https://api.openai.com/v1/",
"local_lm_studio": "localhost:1234/v1",
}
def save_api_key(self):
self.self.current_key = self.api_key_input.text().strip()
if self.current_key:
QMessageBox.information(self, "API Key Saved", "API key has been saved temporarily for this session.")
else:
QMessageBox.warning(self, "Invalid", "Please enter a valid API key.")
def on_option_changed(self, text):
print(f"Model option changed to: {text} the endpoint that will be used is: {self.supported_models.get(text)}")
self.model = text
self.endpoint = self.supported_models.get(text)
def toggle_theme(self):
self.is_dark = not self.is_dark
self.apply_theme()
if self.is_dark:
self.theme_button.setIcon(QIcon("icons/sun.png"))
else:
self.theme_button.setIcon(QIcon("icons/moon.png"))
def apply_theme(self):
if self.is_dark:
self.setStyleSheet(self.dark_theme())
else:
self.setStyleSheet(self.light_theme())
def select_folder(self):
folder = QFileDialog.getExistingDirectory(self, "Select Folder")
if folder:
self.folder_path = folder
self.folder_label.setText(f"Selected Folder:\n{folder}")
def show_long_message(self, title, message):
dialog = QDialog(self)
dialog.setWindowTitle(title)
dialog.setMinimumSize(500, 400)
layout = QVBoxLayout(dialog)
text_edit = QTextEdit()
text_edit.setReadOnly(True)
text_edit.setText(message)
layout.addWidget(text_edit)
close_button = QPushButton("Close")
close_button.clicked.connect(dialog.accept)
layout.addWidget(close_button)
dialog.exec()
def sort_files(self):
try:
if not self.folder_path:
QMessageBox.warning(self, "Warning", "Please select a folder first.")
return
self.text_input.append("Starting sort...")
user_prompt = self.text_input.toPlainText()
sortly = Sortly(os.getenv("OPENAI_API_KEY"), model=self.model, base_url=self.endpoint)
self.worker = SortWorker(self.folder_path, user_prompt, sortly)
self.worker.progress.connect(self.update_progress)
self.worker.finished.connect(self.sorting_finished)
self.worker.start()
except Exception as e:
QMessageBox.critical(self, "Error", f"An error occurred: {str(e)}")
self.text_input.append(f"Error: {str(e)}")
def update_progress(self, message):
self.text_input.append(message)
def sorting_finished(self, message):
self.text_input.append(message)
QMessageBox.information(self, "Done", message)
def dark_theme(self):
return """
QWidget {
background-color: #1e1e1e;
color: #e0e0e0;
font-family: 'Segoe UI', sans-serif;
font-size: 14px;
}
QTextEdit {
background-color: #2c2c2c;
color: #ffffff;
border: 1px solid #444444;
border-radius: 10px;
padding: 8px;
}
QLabel {
color: #e0e0e0;
}
QPushButton {
background-color: #3a6ea5;
color: white;
border: none;
padding: 10px 20px;
border-radius: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #558ed5;
}
QPushButton#theme_button {
background-color: transparent;
font-size: 20px;
border: none;
color: #e0e0e0;
}
QPushButton#theme_button:hover {
color: #ffffff;
}
QPushButton#theme_button {
background-color: #444444;
font-size: 20px;
border-radius: 6px;
color: white;
}
QPushButton#theme_button:hover {
background-color: #666666;
}
"""
def light_theme(self):
return """
QWidget {
background-color: #f9f9f9;
color: #202020;
font-family: 'Segoe UI', sans-serif;
font-size: 14px;
}
QTextEdit {
background-color: #ffffff;
color: #202020;
border: 1px solid #ccc;
border-radius: 10px;
padding: 8px;
}
QLabel {
color: #202020;
}
QPushButton {
background-color: #3a6ea5;
color: white;
border: none;
padding: 10px 20px;
border-radius: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #5b8fd1;
}
QPushButton#theme_button {
background-color: transparent;
font-size: 20px;
border: none;
color: #202020;
}
QPushButton#theme_button:hover {
color: #000000;
}
QPushButton#theme_button {
background-color: #e0e0e0;
font-size: 20px;
border-radius: 6px;
color: #333;
}
QPushButton#theme_button:hover {
background-color: #cfcfcf;
}
"""
if __name__ == "__main__":
app = QApplication(sys.argv)
window = SortlyApp()
window.show()
sys.exit(app.exec())