-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspmf-gui.py
More file actions
2188 lines (1940 loc) · 91.2 KB
/
Copy pathspmf-gui.py
File metadata and controls
2188 lines (1940 loc) · 91.2 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# spmf-gui.py
# GUI client for SPMF-Server
#
# Copyright (C) 2026 Philippe Fournier-Viger
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
spmf-gui.py — Graphical client for SPMF-Server.
Requirements:
pip install requests
tkinter (bundled with standard CPython on Windows / macOS / most Linux)
Usage:
python spmf-gui.py
"""
import base64
import json
import sys
import time
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from pathlib import Path
from typing import Optional, Dict, List
try:
import requests
except ImportError:
_r = tk.Tk()
_r.withdraw()
messagebox.showerror(
"Missing Dependency",
"'requests' is not installed.\n\nRun: pip install requests")
sys.exit(1)
# ── Constants ──────────────────────────────────────────────────────────────────
VERSION = "2.0.0"
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 8585
CONFIG_FILE = Path.home() / ".spmf_client_config.json"
MAX_LOG_LINES = 500
POLL_STATES = ("DONE", "FAILED", "CANCELLED")
# ── Colour palette ─────────────────────────────────────────────────────────────
DARK_BG = "#1e1e2e"
PANEL_BG = "#2a2a3e"
HEADER_BG = "#12121e"
ACCENT = "#7c6af7"
ACCENT_HOVER = "#9d8fff"
SUCCESS = "#50fa7b"
ERROR_COL = "#ff5555"
WARNING = "#ffb86c"
INFO_COL = "#8be9fd"
TEXT_PRIMARY = "#f8f8f2"
TEXT_SEC = "#aaaacc"
TEXT_DIM = "#666688"
ENTRY_BG = "#13131f"
BORDER = "#3a3a5c"
TAG_BG = "#3d3560"
CONSOLE_FG = "#a8ff80"
DANGER_BG = "#44273a"
SAFE_BG = "#1e3a44"
FAV_COL = "#ffb86c"
# ── Tooltip ────────────────────────────────────────────────────────────────────
class Tooltip:
_DELAY = 600
def __init__(self, widget: tk.Widget, text: str):
self._widget = widget
self._text = text
self._job_id = None
self._top = None
widget.bind("<Enter>", self._schedule, add="+")
widget.bind("<Leave>", self._cancel, add="+")
widget.bind("<Button>", self._cancel, add="+")
def _schedule(self, _=None):
self._cancel()
self._job_id = self._widget.after(self._DELAY, self._show)
def _cancel(self, _=None):
if self._job_id:
self._widget.after_cancel(self._job_id)
self._job_id = None
if self._top:
self._top.destroy()
self._top = None
def _show(self):
x = self._widget.winfo_rootx() + 20
y = self._widget.winfo_rooty() + self._widget.winfo_height() + 4
self._top = tw = tk.Toplevel(self._widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{x}+{y}")
tk.Label(tw, text=self._text, bg="#ffffcc", fg="#111111",
relief="solid", bd=1, padx=6, pady=3,
font=("Segoe UI", 8), justify="left",
wraplength=320).pack()
# ── Config ─────────────────────────────────────────────────────────────────────
class Config:
_DEFAULTS: Dict[str, object] = {
"host": DEFAULT_HOST,
"port": str(DEFAULT_PORT),
"apikey": "",
"poll_interval": "1.0",
"timeout": "300",
"auto_refresh": False,
"refresh_every": "10",
"favorites": [],
"last_algo": "",
"last_file": "",
"wrap_result": False,
}
def __init__(self):
self._data: dict = dict(self._DEFAULTS)
self.load()
def load(self):
try:
if CONFIG_FILE.exists():
loaded = json.loads(CONFIG_FILE.read_text("utf-8"))
self._data.update(loaded)
except Exception:
pass
def save(self):
try:
CONFIG_FILE.write_text(json.dumps(self._data, indent=2), "utf-8")
except Exception:
pass
def get(self, key: str, default=None):
return self._data.get(key, self._DEFAULTS.get(key, default))
def set(self, key: str, value):
self._data[key] = value
def toggle_favorite(self, name: str) -> bool:
favs: list = self._data.setdefault("favorites", [])
if name in favs:
favs.remove(name)
return False
favs.append(name)
return True
def is_favorite(self, name: str) -> bool:
return name in self._data.get("favorites", [])
# ── HTTP helpers ───────────────────────────────────────────────────────────────
def _headers(apikey: str) -> dict:
h = {"Content-Type": "application/json"}
if apikey:
h["X-API-Key"] = apikey
return h
def _base_url(host: str, port: int) -> str:
return f"http://{host}:{port}"
def api_get(host, port, apikey, path, timeout=15):
return requests.get(
_base_url(host, port) + path,
headers=_headers(apikey), timeout=timeout)
def api_post(host, port, apikey, path, payload, timeout=30):
return requests.post(
_base_url(host, port) + path,
headers=_headers(apikey),
data=json.dumps(payload), timeout=timeout)
def api_delete(host, port, apikey, path, timeout=15):
return requests.delete(
_base_url(host, port) + path,
headers=_headers(apikey), timeout=timeout)
def _safe_json_error(resp) -> str:
try:
if "json" in resp.headers.get("content-type", ""):
return resp.json().get("error", resp.text)
except Exception:
pass
return resp.text
# ── Widget helpers ─────────────────────────────────────────────────────────────
def styled_button(parent, text: str, command,
bg=ACCENT, fg=TEXT_PRIMARY,
width=None, font_size: int = 10,
tooltip: str = "") -> tk.Button:
kw = dict(
text=text, command=command, bg=bg, fg=fg,
relief="flat", cursor="hand2",
font=("Segoe UI", font_size, "bold"),
padx=12, pady=6, bd=0,
activebackground=ACCENT_HOVER,
activeforeground=TEXT_PRIMARY,
)
if width:
kw["width"] = width
btn = tk.Button(parent, **kw)
btn.bind("<Enter>", lambda _: btn.config(
bg=ACCENT_HOVER if bg == ACCENT else bg))
btn.bind("<Leave>", lambda _: btn.config(bg=bg))
if tooltip:
Tooltip(btn, tooltip)
return btn
def icon_button(parent, text: str, command,
tooltip: str = "", fg=TEXT_SEC) -> tk.Button:
btn = tk.Button(parent, text=text, command=command,
bg=PANEL_BG, fg=fg, relief="flat", cursor="hand2",
font=("Segoe UI", 11), padx=4, pady=2, bd=0,
activebackground=TAG_BG,
activeforeground=TEXT_PRIMARY)
if tooltip:
Tooltip(btn, tooltip)
return btn
def card_frame(parent, **kw) -> tk.Frame:
return tk.Frame(parent, bg=PANEL_BG, bd=0,
highlightthickness=1,
highlightbackground=BORDER, **kw)
def section_label(parent, text: str):
tk.Label(parent, text=text, bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 11, "bold")).pack(
anchor="w", padx=16, pady=(12, 0))
ttk.Separator(parent).pack(fill="x", padx=10, pady=(4, 6))
def kv_row(parent, label: str, var: tk.StringVar,
label_width: int = 22, tooltip: str = ""):
row = tk.Frame(parent, bg=PANEL_BG)
row.pack(fill="x", padx=16, pady=2)
lbl = tk.Label(row, text=label + ":", bg=PANEL_BG, fg=TEXT_SEC,
font=("Segoe UI", 9), width=label_width, anchor="w")
lbl.pack(side="left")
val = tk.Label(row, textvariable=var, bg=PANEL_BG, fg=TEXT_PRIMARY,
font=("Consolas", 10), anchor="w")
val.pack(side="left", fill="x", expand=True)
if tooltip:
Tooltip(lbl, tooltip)
Tooltip(val, tooltip)
def styled_entry(parent, var: tk.Variable,
width: int = None, show: str = None,
font_size: int = 10) -> tk.Entry:
kw = dict(
textvariable=var, bg=ENTRY_BG, fg=TEXT_PRIMARY,
relief="flat", font=("Consolas", font_size),
insertbackground=TEXT_PRIMARY,
highlightthickness=1, highlightbackground=BORDER,
highlightcolor=ACCENT,
)
if width:
kw["width"] = width
if show:
kw["show"] = show
return tk.Entry(parent, **kw)
# ── About window ───────────────────────────────────────────────────────────────
class AboutWindow(tk.Toplevel):
_LICENSE = (
"This program is free software: you can redistribute it and/or\n"
"modify it under the terms of the GNU General Public License as\n"
"published by the Free Software Foundation, either version 3 of\n"
"the License, or (at your option) any later version.\n\n"
"This program is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
"GNU General Public License for more details.\n\n"
"You should have received a copy of the GNU General Public License\n"
"along with this program. If not, see:\n"
"https://www.gnu.org/licenses/gpl-3.0.html"
)
def __init__(self, parent: tk.Tk):
super().__init__(parent)
self.title("About SPMF Server Client")
self.resizable(False, False)
self.configure(bg=DARK_BG)
self.grab_set()
self.focus_set()
self._build()
self._center(parent)
def _build(self):
tk.Frame(self, bg=ACCENT, height=6).pack(fill="x")
logo = tk.Frame(self, bg=DARK_BG)
logo.pack(fill="x", padx=32, pady=(28, 0))
tk.Label(logo, text="⬡", bg=DARK_BG, fg=ACCENT,
font=("Segoe UI", 42)).pack(side="left", padx=(0, 16))
tb = tk.Frame(logo, bg=DARK_BG)
tb.pack(side="left", anchor="w")
tk.Label(tb, text="SPMF Server Client", bg=DARK_BG,
fg=TEXT_PRIMARY, font=("Segoe UI", 18, "bold"),
anchor="w").pack(anchor="w")
tk.Label(tb, text=f"Version {VERSION}", bg=DARK_BG,
fg=TEXT_DIM, font=("Segoe UI", 10),
anchor="w").pack(anchor="w")
tk.Frame(self, bg=BORDER, height=1).pack(fill="x", padx=24,
pady=(20, 0))
card = tk.Frame(self, bg=PANEL_BG,
highlightthickness=1, highlightbackground=BORDER)
card.pack(fill="x", padx=24, pady=16)
for lbl, val in [
("Author", "Philippe Fournier-Viger"),
("Website", "https://www.philippe-fournier-viger.com/spmf/"),
("License", "GNU General Public License v3.0 (GPLv3)"),
("Copyright", "© Philippe Fournier-Viger. All rights reserved."),
("Built with", "Python • tkinter • requests"),
]:
row = tk.Frame(card, bg=PANEL_BG)
row.pack(fill="x", padx=20, pady=5)
tk.Label(row, text=f"{lbl}:", bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 9, "bold"), width=12,
anchor="w").pack(side="left")
tk.Label(row, text=val, bg=PANEL_BG, fg=TEXT_PRIMARY,
font=("Segoe UI", 9), anchor="w").pack(side="left")
tk.Frame(self, bg=BORDER, height=1).pack(fill="x", padx=24,
pady=(0, 12))
tk.Label(self,
text=("SPMF Server Client is a graphical interface for the SPMF\n"
"data mining server — browse algorithms, submit jobs,\n"
"and view results without the command line."),
bg=DARK_BG, fg=TEXT_SEC, font=("Segoe UI", 9),
justify="left").pack(anchor="w", padx=32, pady=(0, 12))
tk.Label(self, text="License", bg=DARK_BG, fg=ACCENT,
font=("Segoe UI", 10, "bold")).pack(anchor="w", padx=32,
pady=(0, 4))
box = tk.Text(self, bg=ENTRY_BG, fg=TEXT_SEC,
font=("Consolas", 8), relief="flat", height=12,
wrap="word", cursor="arrow",
highlightthickness=1, highlightbackground=BORDER)
box.insert("1.0", self._LICENSE)
box.config(state="disabled")
box.pack(fill="x", padx=24, pady=(0, 12))
tk.Frame(self, bg=BORDER, height=1).pack(fill="x", padx=24)
bot = tk.Frame(self, bg=DARK_BG)
bot.pack(fill="x", padx=24, pady=12)
tk.Label(bot, text="SPMF — Sequential Pattern Mining Framework",
bg=DARK_BG, fg=TEXT_DIM,
font=("Segoe UI", 8, "italic")).pack(side="left")
tk.Button(bot, text="Close", command=self.destroy,
bg=ACCENT, fg=TEXT_PRIMARY, relief="flat",
cursor="hand2", font=("Segoe UI", 9, "bold"),
padx=20, pady=4,
activebackground=ACCENT_HOVER,
activeforeground=TEXT_PRIMARY).pack(side="right")
def _center(self, parent: tk.Tk):
self.update_idletasks()
w, h = self.winfo_width(), self.winfo_height()
px = parent.winfo_x() + (parent.winfo_width() // 2) - (w // 2)
py = parent.winfo_y() + (parent.winfo_height() // 2) - (h // 2)
self.geometry(f"+{px}+{py}")
# ── Settings window ────────────────────────────────────────────────────────────
class SettingsWindow(tk.Toplevel):
def __init__(self, parent, config: Config, on_save=None):
super().__init__(parent)
self.title("Settings")
self.resizable(False, False)
self.configure(bg=DARK_BG)
self.grab_set()
self.focus_set()
self._cfg = config
self._on_save = on_save
self._vars: Dict[str, tk.Variable] = {}
self._build()
self._center(parent)
def _build(self):
tk.Frame(self, bg=ACCENT, height=4).pack(fill="x")
tk.Label(self, text="⚙ Settings", bg=DARK_BG, fg=TEXT_PRIMARY,
font=("Segoe UI", 14, "bold")).pack(
anchor="w", padx=20, pady=(16, 4))
tk.Frame(self, bg=BORDER, height=1).pack(fill="x", padx=16,
pady=(0, 8))
card = card_frame(self)
card.pack(fill="x", padx=16, pady=4)
section_label(card, "Network")
self._str_row(card, "Default Host", "host")
self._str_row(card, "Default Port", "port")
section_label(card, "Job Defaults")
self._str_row(card, "Poll Interval (s)", "poll_interval")
self._str_row(card, "Timeout (s)", "timeout")
section_label(card, "Auto-Refresh")
self._bool_row(card, "Enable auto-refresh", "auto_refresh")
self._str_row(card, "Refresh every (s)", "refresh_every")
section_label(card, "Display")
self._bool_row(card, "Word-wrap result output", "wrap_result")
btns = tk.Frame(self, bg=DARK_BG)
btns.pack(fill="x", padx=16, pady=12)
styled_button(btns, "Save", self._save).pack(side="right",
padx=(4, 0))
styled_button(btns, "Cancel", self.destroy,
bg=PANEL_BG, fg=TEXT_SEC).pack(side="right")
def _str_row(self, parent, label: str, key: str):
row = tk.Frame(parent, bg=PANEL_BG)
row.pack(fill="x", padx=16, pady=3)
tk.Label(row, text=label + ":", bg=PANEL_BG, fg=TEXT_SEC,
font=("Segoe UI", 9), width=22,
anchor="w").pack(side="left")
var = tk.StringVar(value=str(self._cfg.get(key, "")))
self._vars[key] = var
styled_entry(row, var, width=20).pack(side="left")
def _bool_row(self, parent, label: str, key: str):
row = tk.Frame(parent, bg=PANEL_BG)
row.pack(fill="x", padx=16, pady=3)
var = tk.BooleanVar(value=bool(self._cfg.get(key, False)))
self._vars[key] = var
tk.Checkbutton(row, text=label, variable=var,
bg=PANEL_BG, fg=TEXT_PRIMARY,
selectcolor=ACCENT,
activebackground=PANEL_BG,
font=("Segoe UI", 9)).pack(anchor="w")
def _save(self):
for key, var in self._vars.items():
self._cfg.set(key, var.get())
self._cfg.save()
if self._on_save:
self._on_save()
self.destroy()
def _center(self, parent):
self.update_idletasks()
w, h = self.winfo_width(), self.winfo_height()
px = parent.winfo_x() + (parent.winfo_width() // 2) - (w // 2)
py = parent.winfo_y() + (parent.winfo_height() // 2) - (h // 2)
self.geometry(f"+{px}+{py}")
# ── Main application ───────────────────────────────────────────────────────────
class SPMFGui(tk.Tk):
def __init__(self):
super().__init__()
self.title("SPMF Server Client")
self.geometry("1380x860")
self.minsize(1000, 640)
self.configure(bg=DARK_BG)
self.protocol("WM_DELETE_WINDOW", self._on_close)
self._cfg = Config()
self._connected = False
self._algorithms: List[dict] = []
self._jobs: List[dict] = []
self._auto_after: Optional[str] = None
self._submit_thread: Optional[threading.Thread] = None
self._cancel_flag = threading.Event()
self._last_filtered: List[dict] = []
self._favs_only = False
self._jobs_sort_col = "submittedAt"
self._jobs_sort_rev = True
self._host = tk.StringVar(value=str(self._cfg.get("host")))
self._port = tk.StringVar(value=str(self._cfg.get("port")))
self._apikey = tk.StringVar(value=str(self._cfg.get("apikey")))
self._apply_ttk_style()
self._build_header()
self._build_main()
self._build_statusbar()
self._bind_shortcuts()
self.after(200, self._try_auto_connect)
def _on_close(self):
self._stop_auto_refresh()
self._cfg.set("host", self._host.get())
self._cfg.set("port", self._port.get())
self._cfg.set("apikey", self._apikey.get())
self._cfg.save()
self.destroy()
def _bind_shortcuts(self):
self.bind("<F5>", lambda _: self._smart_refresh())
self.bind("<Control-r>", lambda _: self._smart_refresh())
self.bind("<Control-Return>", lambda _: self._submit_job())
self.bind("<Control-k>", lambda _: self._clear_log())
self.bind("<Control-comma>", lambda _: self._open_settings())
self.bind("<F1>", lambda _: self._open_about())
def _smart_refresh(self):
tab = self._notebook.index(self._notebook.select())
{0: self._refresh_health,
1: self._refresh_algorithms,
3: self._refresh_jobs}.get(tab, lambda: None)()
def _apply_ttk_style(self):
s = ttk.Style(self)
s.theme_use("clam")
s.configure(".",
background=DARK_BG, foreground=TEXT_PRIMARY,
fieldbackground=ENTRY_BG, bordercolor=BORDER,
darkcolor=DARK_BG, lightcolor=PANEL_BG,
troughcolor=DARK_BG, focuscolor=ACCENT,
selectbackground=ACCENT, selectforeground=TEXT_PRIMARY,
font=("Segoe UI", 10))
s.configure("Treeview",
background=ENTRY_BG, foreground=TEXT_PRIMARY,
fieldbackground=ENTRY_BG, bordercolor=BORDER,
rowheight=26)
s.map("Treeview",
background=[("selected", ACCENT)],
foreground=[("selected", TEXT_PRIMARY)])
s.configure("Treeview.Heading",
background=PANEL_BG, foreground=ACCENT,
relief="flat", font=("Segoe UI", 9, "bold"))
s.map("Treeview.Heading", background=[("active", TAG_BG)])
s.configure("TNotebook",
background=DARK_BG, bordercolor=BORDER,
tabmargins=[2, 4, 0, 0])
s.configure("TNotebook.Tab",
background=PANEL_BG, foreground=TEXT_SEC,
padding=[16, 8], font=("Segoe UI", 10, "bold"))
s.map("TNotebook.Tab",
background=[("selected", DARK_BG)],
foreground=[("selected", ACCENT)],
expand=[("selected", [1, 1, 1, 0])])
s.configure("TCombobox",
fieldbackground=ENTRY_BG, background=ENTRY_BG,
foreground=TEXT_PRIMARY, arrowcolor=ACCENT,
bordercolor=BORDER, selectbackground=ACCENT)
s.map("TCombobox",
fieldbackground=[("readonly", ENTRY_BG)],
foreground=[("readonly", TEXT_PRIMARY)])
for orient in ("Vertical", "Horizontal"):
s.configure(f"{orient}.TScrollbar",
background=PANEL_BG, troughcolor=DARK_BG,
arrowcolor=ACCENT, bordercolor=BORDER, width=10)
s.configure("Horizontal.TProgressbar",
troughcolor=ENTRY_BG, background=ACCENT,
darkcolor=ACCENT, lightcolor=ACCENT_HOVER,
bordercolor=BORDER, thickness=8)
def _build_header(self):
hdr = tk.Frame(self, bg=HEADER_BG, height=60)
hdr.pack(fill="x", side="top")
hdr.pack_propagate(False)
left = tk.Frame(hdr, bg=HEADER_BG)
left.pack(side="left", fill="y")
tk.Label(left, text="⬡ SPMF Server Client", bg=HEADER_BG,
fg=TEXT_PRIMARY, font=("Segoe UI", 14, "bold")).pack(
side="left", padx=20, pady=10)
tk.Label(left, text=f"v{VERSION}", bg=HEADER_BG,
fg=TEXT_DIM, font=("Segoe UI", 9)).pack(
side="left", pady=10)
for text, cmd, tip in [
("ℹ About", self._open_about, "About (F1)"),
("⚙ Settings", self._open_settings, "Settings (Ctrl+,)"),
]:
tk.Button(left, text=text, command=cmd,
bg=HEADER_BG, fg=TEXT_SEC, relief="flat",
cursor="hand2", font=("Segoe UI", 9),
padx=10, pady=6, bd=0,
activebackground=TAG_BG,
activeforeground=TEXT_PRIMARY).pack(
side="left", padx=(4, 0), pady=10)
conn = tk.Frame(hdr, bg=HEADER_BG)
conn.pack(side="right", padx=16, pady=8)
for lbl, var, w, show, tip in [
("Host:", self._host, 12, None,
"Server hostname or IP"),
("Port:", self._port, 6, None,
"Server port (default 8585)"),
("API Key:", self._apikey, 12, "•",
"API key (leave empty if not required)"),
]:
tk.Label(conn, text=lbl, bg=HEADER_BG, fg=TEXT_SEC,
font=("Segoe UI", 9)).pack(side="left", padx=(0, 3))
e = styled_entry(conn, var, width=w, show=show)
e.pack(side="left", padx=(0, 8))
Tooltip(e, tip)
self._conn_btn = tk.Button(
conn, text="Connect", command=self._on_connect,
bg=ACCENT, fg=TEXT_PRIMARY, relief="flat", cursor="hand2",
font=("Segoe UI", 10, "bold"), padx=14, pady=4,
activebackground=ACCENT_HOVER, activeforeground=TEXT_PRIMARY)
self._conn_btn.pack(side="left", padx=(0, 6))
Tooltip(self._conn_btn, "Connect to SPMF server")
self._disconn_btn = tk.Button(
conn, text="Disconnect", command=self._on_disconnect,
bg=PANEL_BG, fg=TEXT_SEC, relief="flat", cursor="hand2",
font=("Segoe UI", 9), padx=10, pady=4,
activebackground=DANGER_BG, activeforeground=TEXT_PRIMARY)
self._disconn_btn.pack(side="left")
Tooltip(self._disconn_btn, "Disconnect from server")
self._dot_lbl = tk.Label(hdr, text="●", bg=HEADER_BG,
fg=ERROR_COL, font=("Segoe UI", 16))
self._dot_lbl.pack(side="right", padx=(0, 6))
Tooltip(self._dot_lbl,
"Green = connected / Red = disconnected")
def _open_about(self):
AboutWindow(self)
def _open_settings(self):
SettingsWindow(self, self._cfg, on_save=self._on_settings_saved)
def _on_settings_saved(self):
self._log_write("Settings saved.", "ok")
if self._cfg.get("auto_refresh"):
self._start_auto_refresh()
else:
self._stop_auto_refresh()
wrap = "word" if self._cfg.get("wrap_result") else "none"
self._result_text.config(wrap=wrap)
self._console_text.config(wrap=wrap)
def _build_statusbar(self):
bar = tk.Frame(self, bg=HEADER_BG, height=28)
bar.pack(fill="x", side="bottom")
bar.pack_propagate(False)
self._status_var = tk.StringVar(value="Not connected.")
tk.Label(bar, textvariable=self._status_var, bg=HEADER_BG,
fg=TEXT_DIM, font=("Segoe UI", 8), anchor="w").pack(
side="left", padx=10, fill="y")
tk.Label(bar,
text="F5=Refresh • Ctrl+Enter=Submit • "
"Ctrl+K=Clear Log • F1=About",
bg=HEADER_BG, fg=TEXT_DIM,
font=("Segoe UI", 7)).pack(side="right", padx=12)
self._busy_lbl = tk.Label(bar, text="", bg=HEADER_BG,
fg=WARNING, font=("Segoe UI", 8))
self._busy_lbl.pack(side="right", padx=10)
def _set_status(self, msg: str, colour: str = TEXT_DIM):
self._status_var.set(msg)
def _set_busy(self, msg: str = ""):
self._busy_lbl.config(text=msg)
def _build_main(self):
self._notebook = ttk.Notebook(self)
self._notebook.pack(fill="both", expand=True, padx=8, pady=(6, 0))
self._tab_dashboard = tk.Frame(self._notebook, bg=DARK_BG)
self._tab_algorithms = tk.Frame(self._notebook, bg=DARK_BG)
self._tab_run = tk.Frame(self._notebook, bg=DARK_BG)
self._tab_jobs = tk.Frame(self._notebook, bg=DARK_BG)
self._tab_result = tk.Frame(self._notebook, bg=DARK_BG)
self._notebook.add(self._tab_dashboard, text=" Dashboard ")
self._notebook.add(self._tab_algorithms, text=" Algorithms ")
self._notebook.add(self._tab_run, text=" Run Job ")
self._notebook.add(self._tab_jobs, text=" Jobs ")
self._notebook.add(self._tab_result, text=" Result ")
self._build_tab_dashboard()
self._build_tab_algorithms()
self._build_tab_run()
self._build_tab_jobs()
self._build_tab_result()
# ── TAB: Dashboard ────────────────────────────────────────────────────────
def _build_tab_dashboard(self):
tab = self._tab_dashboard
tab.columnconfigure(0, weight=1)
tab.columnconfigure(1, weight=1)
tab.rowconfigure(1, weight=1)
hc = card_frame(tab)
hc.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
section_label(hc, "Server Health")
self._health_vars: Dict[str, tk.StringVar] = {}
for key, lbl, tip in [
("status", "Status", "UP = healthy"),
("version", "Version", "SPMF version"),
("spmfAlgorithmsLoaded", "Algorithms Loaded", "Total algorithms"),
("uptimeSeconds", "Uptime (s)", "Seconds since start"),
("activeJobs", "Active Jobs", "Running now"),
("queuedJobs", "Queued Jobs", "Waiting to run"),
("totalJobsInRegistry", "In Registry", "All tracked jobs"),
]:
v = tk.StringVar(value="—")
self._health_vars[key] = v
kv_row(hc, lbl, v, tooltip=tip)
br = tk.Frame(hc, bg=PANEL_BG)
br.pack(fill="x", padx=16, pady=12)
styled_button(br, "↺ Refresh Health",
self._refresh_health,
tooltip="Reload server health (F5)").pack(side="left")
ic = card_frame(tab)
ic.grid(row=0, column=1, padx=10, pady=10, sticky="nsew")
section_label(ic, "Server Configuration")
self._info_vars: Dict[str, tk.StringVar] = {}
for key, lbl, tip in [
("version", "Version", "SPMF library version"),
("port", "Port", "Listening port"),
("host", "Host", "Bound interface"),
("coreThreads", "Core Threads", "Pool core size"),
("maxThreads", "Max Threads", "Pool maximum"),
("jobTtlMinutes", "Job TTL (min)", "How long jobs are kept"),
("maxQueueSize", "Max Queue", "Max waiting jobs"),
("workDir", "Work Dir", "Job working directory"),
("maxInputSizeMb", "Max Input (MB)", "Upload size limit"),
("apiKeyEnabled", "API Key", "Auth enabled?"),
("logLevel", "Log Level", "Server log verbosity"),
]:
v = tk.StringVar(value="—")
self._info_vars[key] = v
kv_row(ic, lbl, v, label_width=18, tooltip=tip)
br2 = tk.Frame(ic, bg=PANEL_BG)
br2.pack(fill="x", padx=16, pady=12)
styled_button(br2, "↺ Refresh Info",
self._refresh_info,
tooltip="Reload server configuration").pack(side="left")
lc = card_frame(tab)
lc.grid(row=1, column=0, columnspan=2,
padx=10, pady=(0, 10), sticky="nsew")
hdr2 = tk.Frame(lc, bg=PANEL_BG)
hdr2.pack(fill="x", padx=16, pady=(10, 0))
tk.Label(hdr2, text="Activity Log", bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 11, "bold")).pack(side="left")
styled_button(hdr2, "💾 Export", self._export_log,
bg=PANEL_BG, fg=TEXT_DIM, font_size=8,
tooltip="Save log to file").pack(side="right")
styled_button(hdr2, "Clear", self._clear_log,
bg=PANEL_BG, fg=TEXT_DIM, font_size=8,
tooltip="Clear log (Ctrl+K)").pack(
side="right", padx=(0, 4))
self._log = scrolledtext.ScrolledText(
lc, bg=ENTRY_BG, fg=TEXT_PRIMARY,
font=("Consolas", 9), relief="flat",
wrap="word", state="disabled", height=8)
self._log.pack(fill="both", expand=True, padx=8, pady=(4, 8))
for tag, col in [("ok", SUCCESS), ("err", ERROR_COL),
("warn", WARNING), ("info", TEXT_SEC),
("dim", TEXT_DIM)]:
self._log.tag_config(tag, foreground=col)
def _log_write(self, msg: str, tag: str = "info"):
self._log.config(state="normal")
lines = int(self._log.index("end-1c").split(".")[0])
if lines > MAX_LOG_LINES:
self._log.delete("1.0", f"{lines - MAX_LOG_LINES}.0")
ts = time.strftime("%H:%M:%S")
self._log.insert("end", f"[{ts}] ", "dim")
self._log.insert("end", msg + "\n", tag)
self._log.see("end")
self._log.config(state="disabled")
def _clear_log(self):
self._log.config(state="normal")
self._log.delete("1.0", "end")
self._log.config(state="disabled")
def _export_log(self):
content = self._log.get("1.0", "end")
if not content.strip():
messagebox.showinfo("Empty Log", "Nothing to export.")
return
path = filedialog.asksaveasfilename(
title="Export activity log", defaultextension=".log",
filetypes=[("Log files", "*.log"), ("Text files", "*.txt")])
if path:
Path(path).write_text(content, "utf-8")
messagebox.showinfo("Exported", f"Log saved to:\n{path}")
# ── TAB: Algorithms ───────────────────────────────────────────────────────
def _build_tab_algorithms(self):
tab = self._tab_algorithms
tab.columnconfigure(0, weight=1)
tab.columnconfigure(1, weight=2)
tab.rowconfigure(0, weight=1)
left = card_frame(tab)
left.grid(row=0, column=0, padx=(10, 4), pady=10, sticky="nsew")
left.rowconfigure(3, weight=1)
left.columnconfigure(0, weight=1)
hdr = tk.Frame(left, bg=PANEL_BG)
hdr.grid(row=0, column=0, sticky="ew", padx=8, pady=(8, 0))
tk.Label(hdr, text="Algorithm List", bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 11, "bold")).pack(side="left")
styled_button(hdr, "↺", self._refresh_algorithms,
font_size=9,
tooltip="Reload algorithms (F5)").pack(side="right")
icon_button(hdr, "★", self._toggle_favorites_only,
tooltip="Show favorites only",
fg=FAV_COL).pack(side="right", padx=(0, 4))
flt = tk.Frame(left, bg=PANEL_BG)
flt.grid(row=1, column=0, sticky="ew", padx=8, pady=4)
tk.Label(flt, text="🔍", bg=PANEL_BG, fg=TEXT_SEC,
font=("Segoe UI", 10)).pack(side="left", padx=(0, 3))
self._algo_search = tk.StringVar()
self._algo_search.trace_add("write",
lambda *_: self._filter_algorithms())
styled_entry(flt, self._algo_search).pack(
side="left", fill="x", expand=True, padx=(0, 6))
self._algo_cat_var = tk.StringVar(value="All Categories")
self._algo_cat_combo = ttk.Combobox(
flt, textvariable=self._algo_cat_var,
state="readonly", width=18, font=("Segoe UI", 8))
self._algo_cat_combo["values"] = ["All Categories"]
self._algo_cat_combo.bind("<<ComboboxSelected>>",
lambda _: self._filter_algorithms())
self._algo_cat_combo.pack(side="left")
Tooltip(self._algo_cat_combo, "Filter by category")
self._algo_count_var = tk.StringVar(value="0 algorithms")
tk.Label(left, textvariable=self._algo_count_var,
bg=PANEL_BG, fg=TEXT_DIM,
font=("Segoe UI", 8)).grid(row=2, column=0,
sticky="w", padx=10)
tf = tk.Frame(left, bg=PANEL_BG)
tf.grid(row=3, column=0, sticky="nsew", padx=8, pady=(2, 8))
tf.rowconfigure(0, weight=1)
tf.columnconfigure(0, weight=1)
self._algo_tree = ttk.Treeview(
tf, columns=("fav", "name", "category"),
show="headings", selectmode="browse")
self._algo_tree.heading("fav", text="★")
self._algo_tree.heading("name", text="Algorithm")
self._algo_tree.heading("category", text="Category")
self._algo_tree.column("fav", width=28, minwidth=28,
stretch=False)
self._algo_tree.column("name", width=190, minwidth=120)
self._algo_tree.column("category", width=150, minwidth=100)
self._algo_tree.grid(row=0, column=0, sticky="nsew")
self._algo_tree.bind("<<TreeviewSelect>>", self._on_algo_select)
self._algo_tree.bind("<Double-1>",
lambda _: self._use_algo_in_run())
self._algo_tree.tag_configure("fav", foreground=FAV_COL)
vsb = ttk.Scrollbar(tf, orient="vertical",
command=self._algo_tree.yview)
vsb.grid(row=0, column=1, sticky="ns")
self._algo_tree.configure(yscrollcommand=vsb.set)
right = card_frame(tab)
right.grid(row=0, column=1, padx=(4, 10), pady=10, sticky="nsew")
right.rowconfigure(7, weight=1)
right.columnconfigure(0, weight=1)
hdr2 = tk.Frame(right, bg=PANEL_BG)
hdr2.grid(row=0, column=0, sticky="ew", padx=16, pady=(12, 0))
tk.Label(hdr2, text="Algorithm Details", bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 11, "bold")).pack(side="left")
self._fav_btn = icon_button(hdr2, "☆",
self._toggle_current_fav,
tooltip="Add/remove from favorites",
fg=FAV_COL)
self._fav_btn.pack(side="right")
self._detail_vars: Dict[str, tk.StringVar] = {}
for i, (key, lbl, tip) in enumerate([
("name", "Name",
"Algorithm name"),
("algorithmCategory", "Category",
"Algorithm family"),
("implementationAuthorNames", "Author(s)",
"Implementation credit"),
("algorithmType", "Type",
"Output type"),
("documentationURL", "Documentation",
"Paper / web page"),
], start=1):
row = tk.Frame(right, bg=PANEL_BG)
row.grid(row=i, column=0, sticky="ew", padx=16, pady=2)
tk.Label(row, text=lbl + ":", bg=PANEL_BG, fg=TEXT_SEC,
font=("Segoe UI", 9), width=14,
anchor="w").pack(side="left")
v = tk.StringVar(value="—")
self._detail_vars[key] = v
lw = tk.Label(row, textvariable=v, bg=PANEL_BG,
fg=TEXT_PRIMARY, font=("Consolas", 9),
anchor="w", wraplength=420, justify="left")
lw.pack(side="left", fill="x", expand=True)
Tooltip(lw, tip)
tk.Label(right, text="Parameters & I/O", bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 10, "bold")).grid(
row=6, column=0, sticky="w", padx=16, pady=(10, 2))
self._detail_text = scrolledtext.ScrolledText(
right, bg=ENTRY_BG, fg=TEXT_PRIMARY, font=("Consolas", 9),
relief="flat", state="disabled", wrap="word", height=14)
self._detail_text.grid(row=7, column=0, sticky="nsew",
padx=10, pady=(0, 8))
self._detail_text.tag_config("label", foreground=ACCENT)
self._detail_text.tag_config("header", foreground=INFO_COL)
self._detail_text.tag_config("mand", foreground=ERROR_COL)
self._detail_text.tag_config("opt", foreground=TEXT_DIM)
br = tk.Frame(right, bg=PANEL_BG)
br.grid(row=8, column=0, sticky="ew", padx=16, pady=(0, 12))
styled_button(br, "▶ Use in Run Job",
self._use_algo_in_run,
tooltip="Load into Run Job tab").pack(side="left")
styled_button(br, "⧉ Copy Name",
self._copy_algo_name,
bg=PANEL_BG, fg=TEXT_SEC, font_size=9,
tooltip="Copy algorithm name to clipboard").pack(
side="left", padx=(8, 0))
def _toggle_favorites_only(self):
self._favs_only = not self._favs_only
self._filter_algorithms()
def _toggle_current_fav(self):
name = self._detail_vars.get("name", tk.StringVar()).get()
if not name or name == "—":
return
added = self._cfg.toggle_favorite(name)
self._cfg.save()
self._fav_btn.config(text="★" if added else "☆")
self._log_write(
f"{'Added' if added else 'Removed'} '{name}' "
f"{'to' if added else 'from'} favorites.", "info")
self._render_algo_tree(self._last_filtered)
def _copy_algo_name(self):
name = self._detail_vars.get("name", tk.StringVar()).get()
if name and name != "—":
self.clipboard_clear()
self.clipboard_append(name)
self._log_write(f"Copied: {name}", "info")
# ── TAB: Run Job ──────────────────────────────────────────────────────────
def _build_tab_run(self):
tab = self._tab_run
tab.columnconfigure(0, weight=1)
tab.columnconfigure(1, weight=1)
tab.rowconfigure(1, weight=1)
left = card_frame(tab)
left.grid(row=0, column=0, rowspan=2, padx=(10, 4),
pady=10, sticky="nsew")
left.columnconfigure(1, weight=1)
tk.Label(left, text="Job Configuration", bg=PANEL_BG, fg=ACCENT,
font=("Segoe UI", 11, "bold")).grid(
row=0, column=0, columnspan=3, sticky="w",
padx=16, pady=(12, 4))
ttk.Separator(left).grid(row=1, column=0, columnspan=3,
sticky="ew", padx=10, pady=(0, 8))
tk.Label(left, text="Algorithm:", bg=PANEL_BG, fg=TEXT_SEC,
font=("Segoe UI", 9), anchor="w").grid(
row=2, column=0, sticky="w", padx=16, pady=4)
self._run_algo_var = tk.StringVar(
value=str(self._cfg.get("last_algo", "")))
self._run_algo_combo = ttk.Combobox(