-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchub_ripper.py
More file actions
2580 lines (2297 loc) · 108 KB
/
chub_ripper.py
File metadata and controls
2580 lines (2297 loc) · 108 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
"""
Chub Ripper — downloads your Chub.ai cards, lorebooks, and chats.
Setup:
pip install Pillow PyQt6 requests playwright
playwright install chromium
"""
import base64
import ctypes
import ctypes.wintypes
import io
import json
import os
import queue
import re
import struct
import sys
import threading
import time
import zlib
from pathlib import Path
# ─── secure token storage (Windows DPAPI) ─────────────────────────────────────
class _DATA_BLOB(ctypes.Structure):
_fields_ = [("cbData", ctypes.wintypes.DWORD),
("pbData", ctypes.POINTER(ctypes.c_char))]
def _token_save(tok: str) -> None:
p = Path(__file__).parent
try:
buf = ctypes.create_string_buffer(tok.encode("utf-8"))
b_in = _DATA_BLOB(len(tok.encode("utf-8")), buf)
b_out = _DATA_BLOB()
if not ctypes.windll.Crypt32.CryptProtectData(
ctypes.byref(b_in), None, None, None, None, 0,
ctypes.byref(b_out)):
raise OSError("CryptProtectData failed")
enc = ctypes.string_at(b_out.pbData, b_out.cbData)
ctypes.windll.Kernel32.LocalFree(b_out.pbData)
(p / ".chub_token").write_bytes(base64.b64encode(enc))
except Exception:
(p / ".chub_token").write_text(tok, encoding="utf-8")
def _token_load() -> str:
path = Path(__file__).parent / ".chub_token"
if not path.exists():
return ""
try:
raw = base64.b64decode(path.read_bytes())
buf = ctypes.create_string_buffer(raw)
b_in = _DATA_BLOB(len(raw), buf)
b_out = _DATA_BLOB()
if not ctypes.windll.Crypt32.CryptUnprotectData(
ctypes.byref(b_in), None, None, None, None, 0,
ctypes.byref(b_out)):
raise OSError("CryptUnprotectData failed")
dec = ctypes.string_at(b_out.pbData, b_out.cbData)
ctypes.windll.Kernel32.LocalFree(b_out.pbData)
return dec.decode("utf-8").strip()
except Exception:
try:
return path.read_text(encoding="utf-8").strip()
except Exception:
return ""
# ─── config ───────────────────────────────────────────────────────────────────
CONFIG_FILE = Path(__file__).parent / ".chub_config.json"
def _config_load() -> dict:
try:
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
except Exception:
return {}
def _config_save(updates: dict) -> None:
try:
cfg = _config_load()
cfg.update(updates)
CONFIG_FILE.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8")
except Exception:
pass
# ─── dependency check ─────────────────────────────────────────────────────────
def _check_deps():
missing = []
for pkg, pip_name in [("PIL", "Pillow"), ("PyQt6", "PyQt6"),
("requests", "requests"), ("playwright", "playwright")]:
try:
__import__(pkg)
except ImportError:
missing.append(pip_name)
if missing:
import tkinter as _tk, tkinter.messagebox as _mb
_r = _tk.Tk(); _r.withdraw()
_mb.showerror("Missing packages",
f"pip install {' '.join(missing)}"
+ ("\n playwright install chromium" if "playwright" in missing else ""))
sys.exit(1)
_check_deps()
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGridLayout, QLabel, QPushButton, QLineEdit, QCheckBox,
QProgressBar, QScrollArea, QFrame, QStackedWidget, QMenu, QDialog,
QSizePolicy, QSpacerItem,
)
from PyQt6.QtCore import Qt, QTimer, QSize, QPoint, pyqtSignal
from PyQt6.QtGui import QPixmap, QImage, QColor, QFont, QCursor, QIcon
from PIL import Image, ImageDraw
# ─── paths ────────────────────────────────────────────────────────────────────
ROOT = Path(__file__).parent
CARDS_DIR = ROOT / "Cards"
LORE_DIR = ROOT / "Lorebooks"
CHATS_DIR = ROOT / "Chats"
PRESETS_DIR = ROOT / "Presets"
PERSONAS_DIR = ROOT / "Personas"
REPO_API = "https://ro.chub.ai"
GATEWAY_API = "https://gateway.chub.ai"
CDN_BASE = "https://avatars.charhub.io/avatars"
DELAY = 0.3
# ─── theme ────────────────────────────────────────────────────────────────────
BG = "#0d1117"
SURFACE = "#161b22"
CARD = "#1c2128"
BORDER = "#30363d"
TEXT = "#e6edf3"
MUTED = "#7d8590"
DIM = "#484f58"
ACCENT = "#2f81f7"
A_HOVER = "#1a6fd4"
GREEN = "#3fb950"
RED = "#f85149"
STATUS_FG = {
"queued": DIM,
"downloading": ACCENT,
"done": GREEN,
"skipped": DIM,
"failed": RED,
"unavailable": "#e3b341",
}
STATUS_LABEL = {
"queued": "Queued",
"downloading": "Downloading…",
"done": "✓ Done",
"skipped": "Already saved",
"failed": "✗ Failed",
"unavailable": "⚠ Unavailable",
}
TW, TH = 128, 168 # image dimensions
COLS = 6
PAGE = 100 # tiles per lazy-load batch
# ─── QSS stylesheet ───────────────────────────────────────────────────────────
STYLESHEET = f"""
QMainWindow, QDialog, QWidget {{
background-color: {BG};
color: {TEXT};
font-family: "Segoe UI";
font-size: 10pt;
}}
QLabel {{ background-color: transparent; color: {TEXT}; }}
QLabel#appTitle {{
font-size: 20pt;
font-weight: bold;
letter-spacing: -0.5px;
}}
QLabel#appSubtitle {{
color: {MUTED};
font-size: 10pt;
}}
QLabel#sectionLabel {{
color: {DIM};
font-size: 8pt;
font-weight: bold;
letter-spacing: 1.2px;
}}
QLabel#fmtLabel {{
color: {MUTED};
font-size: 9pt;
}}
QLabel#statusLbl {{ color: {MUTED}; font-size: 9pt; }}
QLabel#badge {{
background-color: {SURFACE};
color: {DIM};
border-radius: 5px;
padding: 2px 8px;
font-size: 9pt;
}}
QLabel#progLbl {{ color: {MUTED}; }}
QPushButton {{
background-color: {SURFACE};
color: {MUTED};
border: 1px solid {BORDER};
border-radius: 6px;
padding: 4px 10px;
min-height: 28px;
font-family: "Segoe UI";
font-size: 10pt;
}}
QPushButton:hover {{ background-color: {CARD}; color: {TEXT}; }}
QPushButton:disabled {{ color: {DIM}; }}
QPushButton:pressed {{ background-color: {BG}; }}
QPushButton#fetchBtn {{
background-color: {ACCENT}; color: {TEXT};
border: none; font-weight: bold; font-size: 10pt;
padding: 6px 18px;
}}
QPushButton#fetchBtn:hover {{ background-color: {A_HOVER}; }}
QPushButton#fetchBtn:disabled {{ background-color: {SURFACE}; color: {DIM}; }}
QPushButton#dlBtn {{
background-color: {GREEN}; color: {BG};
border: none; font-weight: bold; font-size: 11pt;
}}
QPushButton#dlBtn:hover {{ background-color: #2ea843; }}
QPushButton#retryBtn {{
background-color: {RED}; color: {TEXT};
border: none; font-weight: bold;
}}
QPushButton#retryBtn:hover {{ background-color: #c93f3a; }}
QPushButton#tabBtn {{
background-color: transparent;
color: {MUTED};
border: none;
border-bottom: 2px solid transparent;
border-radius: 0;
padding: 8px 14px 6px 14px;
min-height: 32px;
font-size: 10pt;
text-align: left;
}}
QPushButton#tabBtn:hover {{
color: {TEXT};
background-color: {CARD};
}}
QPushButton#tabBtn[active="true"] {{
color: {TEXT};
border-bottom: 2px solid {ACCENT};
font-weight: bold;
}}
QPushButton#folderBtn {{
background-color: transparent;
color: {DIM};
border: none;
border-radius: 4px;
padding: 0;
font-size: 11pt;
min-height: 26px;
}}
QPushButton#folderBtn:hover {{ background-color: {CARD}; color: {ACCENT}; }}
QPushButton#loadMoreBtn {{
background-color: {SURFACE}; color: {MUTED};
border: 1px solid {BORDER}; border-radius: 8px;
font-size: 10pt; min-height: 34px;
}}
QPushButton#loadMoreBtn:hover {{ background-color: {CARD}; color: {TEXT}; }}
QLineEdit {{
background-color: {SURFACE};
color: {TEXT};
border: 1px solid {BORDER};
border-radius: 6px;
padding: 6px 10px;
font-size: 10pt;
selection-background-color: {ACCENT};
}}
QLineEdit:focus {{ border-color: {ACCENT}; }}
QLineEdit#tokenEntry {{
font-family: "Consolas", "Menlo", monospace;
font-size: 10pt;
padding: 8px 12px;
}}
QLineEdit#searchEntry {{
padding: 4px 10px;
}}
QCheckBox {{ color: {TEXT}; spacing: 8px; font-size: 10pt; }}
QFrame#tile QCheckBox {{ spacing: 0px; }}
QCheckBox::indicator {{
width: 16px; height: 16px;
border: 1px solid {BORDER};
border-radius: 3px;
background-color: {SURFACE};
}}
QCheckBox::indicator:checked {{
background-color: {ACCENT};
border-color: {ACCENT};
}}
QCheckBox::indicator:hover {{ border-color: {ACCENT}; }}
QPushButton#dropBtn {{
background-color: {SURFACE};
color: {TEXT};
border: 1px solid {BORDER};
border-radius: 6px;
padding: 4px 12px;
min-height: 28px;
text-align: left;
}}
QPushButton#dropBtn:hover {{
background-color: {CARD};
border-color: {MUTED};
color: {TEXT};
}}
QProgressBar {{
background-color: {BORDER};
border: none;
border-radius: 3px;
max-height: 5px;
text-align: center;
}}
QProgressBar::chunk {{
background-color: {ACCENT};
border-radius: 3px;
}}
QScrollArea {{ background-color: {BG}; border: none; }}
QScrollBar:vertical {{
background-color: {SURFACE};
width: 10px; margin: 0;
}}
QScrollBar::handle:vertical {{
background-color: {BORDER};
border-radius: 5px;
min-height: 30px; margin: 2px;
}}
QScrollBar::handle:vertical:hover {{ background-color: {DIM}; }}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; border: none; }}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{ background: none; }}
QScrollBar:horizontal {{ height: 0; }}
QFrame#divider {{
background-color: {BORDER};
border: none;
max-height: 1px;
}}
QFrame#vsep {{
background-color: {BORDER};
border: none;
max-width: 1px;
}}
QWidget#surface {{ background-color: {SURFACE}; }}
QWidget#header {{ background-color: {BG}; }}
QWidget#settingsBar {{ background-color: {BG}; }}
QWidget#statusStrip {{ background-color: {BG}; }}
QWidget#toolBar {{ background-color: {BG}; }}
QWidget#footerBar {{ background-color: {BG}; border-top: 1px solid {BORDER}; }}
QWidget#tileContainer {{ background-color: {BG}; }}
QMenu {{
background-color: {SURFACE};
color: {TEXT};
border: 1px solid {BORDER};
}}
QMenu::item {{ padding: 4px 20px; }}
QMenu::item:selected {{ background-color: {ACCENT}; }}
QToolTip {{
background-color: {SURFACE};
color: {TEXT};
border: 1px solid {BORDER};
border-radius: 4px;
padding: 4px 8px;
font-size: 10pt;
}}
"""
_FORCE_ON = (
f"QPushButton {{ background-color: {ACCENT}; color: {TEXT}; border: none; "
f"border-radius: 6px; padding: 4px 10px; min-height: 28px; font-size: 10pt; }}"
f"QPushButton:hover {{ background-color: {A_HOVER}; }}"
)
# Tile frame stylesheets
_TILE_NORMAL = (
f"QFrame#tile {{ background-color: {CARD}; border: 1px solid {BORDER}; border-radius: 10px; }}"
)
_TILE_HOVER = (
f"QFrame#tile {{ background-color: {CARD}; border: 1px solid {ACCENT}; border-radius: 10px; }}"
)
# ─── placeholder pixmap ───────────────────────────────────────────────────────
_PH_PIX: QPixmap | None = None
def _hex_to_rgb(h: str) -> tuple:
h = h.lstrip("#")
return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
def _placeholder() -> QPixmap:
global _PH_PIX
if _PH_PIX is None:
cr, cg, cb = _hex_to_rgb(CARD)
br, bg_c, bb = _hex_to_rgb(BORDER)
dr, dg, db = _hex_to_rgb(DIM)
img = Image.new("RGB", (TW, TH), (cr, cg, cb))
draw = ImageDraw.Draw(img)
draw.rectangle([2, 2, TW - 3, TH - 3], outline=(br, bg_c, bb), width=1)
cx, cy = TW // 2, TH // 2
r = 20
draw.ellipse([cx-r, cy-r-12, cx+r, cy+r-12], outline=(dr, dg, db), width=2)
draw.rectangle([cx-r, cy+r-6, cx+r, cy+r+28], outline=(dr, dg, db), width=2)
_PH_PIX = _pil_to_pixmap(img)
return _PH_PIX
def _pil_to_pixmap(img: Image.Image) -> QPixmap:
rgb = img.convert("RGB")
data = rgb.tobytes("raw", "RGB")
qimg = QImage(data, rgb.width, rgb.height, rgb.width * 3, QImage.Format.Format_RGB888)
return QPixmap.fromImage(qimg)
def _make_app_icon() -> QIcon:
"""Build the app/window icon at runtime so we don't ship a binary file.
Rounded accent square with a white download arrow + baseline bar."""
icon = QIcon()
cr, cg, cb = _hex_to_rgb(ACCENT)
white = (255, 255, 255, 255)
for s in (16, 24, 32, 48, 64, 128, 256):
img = Image.new("RGBA", (s, s), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
radius = max(2, int(s * 0.22))
try:
d.rounded_rectangle([0, 0, s - 1, s - 1], radius=radius,
fill=(cr, cg, cb, 255))
except AttributeError:
d.rectangle([0, 0, s - 1, s - 1], fill=(cr, cg, cb, 255))
# Arrow shaft (centered vertical bar).
shaft_w = max(2, int(s * 0.14))
shaft_top = int(s * 0.22)
shaft_bot = int(s * 0.52)
d.rectangle(
[s // 2 - shaft_w // 2, shaft_top,
s // 2 + shaft_w // 2, shaft_bot],
fill=white,
)
# Arrowhead triangle.
head_top = shaft_bot - max(1, int(s * 0.02))
head_bot = int(s * 0.72)
head_w = max(4, int(s * 0.38))
d.polygon(
[(s // 2 - head_w // 2, head_top),
(s // 2 + head_w // 2, head_top),
(s // 2, head_bot)],
fill=white,
)
# Baseline bar (the “save-to-disk” line).
bar_pad = int(s * 0.22)
bar_y = int(s * 0.82)
bar_h = max(2, int(s * 0.07))
d.rectangle([bar_pad, bar_y, s - bar_pad, bar_y + bar_h], fill=white)
qimg = QImage(
img.tobytes("raw", "RGBA"),
s, s, s * 4,
QImage.Format.Format_RGBA8888,
)
icon.addPixmap(QPixmap.fromImage(qimg))
return icon
# ─── text helpers ─────────────────────────────────────────────────────────────
def _safe(s: str) -> str:
return re.sub(r'[<>:"/\\|?*]', "_", str(s)).strip() or "unknown"
def _lc_author(path: str) -> str:
parts = path.split("/", 1)
if len(parts) == 2:
return parts[0].lower() + "/" + parts[1]
return path.lower()
# ─── message / branch helpers ─────────────────────────────────────────────────
def _extract_messages(body) -> list:
if isinstance(body, list):
return body
if not isinstance(body, dict):
return []
for key in ("chatMessages", "messages", "results", "items"):
raw = body.get(key)
if isinstance(raw, list) and raw:
return raw
if isinstance(raw, dict) and raw:
msgs = [v for v in raw.values() if isinstance(v, dict)]
msgs.sort(key=lambda m: int(m.get("id", 0)))
return msgs
return []
def _build_branches(msg_map: dict) -> list:
if not msg_map:
return []
children: dict = {}
for mid, msg in msg_map.items():
pid = msg.get("parent_id")
if pid is None:
continue
try:
pid = int(pid)
except (ValueError, TypeError):
continue
if pid in msg_map:
children.setdefault(pid, []).append(mid)
def _is_root(msg):
pid = msg.get("parent_id")
if pid is None:
return True
try:
return int(pid) not in msg_map
except (ValueError, TypeError):
return True
root_ids = sorted(mid for mid, msg in msg_map.items() if _is_root(msg))
if not root_ids:
return [sorted(msg_map.values(), key=lambda m: int(m.get("id", 0)))]
branches = []
stack = [(rid, []) for rid in reversed(root_ids)]
while stack:
node_id, path = stack.pop()
if node_id not in msg_map:
continue
new_path = path + [msg_map[node_id]]
kids = sorted(children.get(node_id, []))
if not kids:
branches.append(new_path)
else:
for kid in reversed(kids):
stack.append((kid, new_path))
return branches or [sorted(msg_map.values(), key=lambda m: int(m.get("id", 0)))]
def _req(sess, method: str, url: str, max_retries: int = 3, **kwargs):
for attempt in range(max_retries + 1):
r = getattr(sess, method)(url, **kwargs)
if r.status_code != 429:
return r
time.sleep(2 ** attempt)
return r
def _item_already_saved(content_type: str, key: str, node: dict, card_fmt: str) -> bool:
if content_type == "cards":
fname = _safe(key.replace("/", "_"))
if card_fmt != "JSON" and (CARDS_DIR / f"{fname}.png").exists(): return True
if card_fmt != "PNG" and (CARDS_DIR / f"{fname}.json").exists(): return True
return False
if content_type == "lorebooks":
return (LORE_DIR / f"{_safe(node.get('name', key))}.json").exists()
if content_type == "presets":
return (PRESETS_DIR / f"{_safe(key.replace('/', '_'))}.json").exists()
if content_type == "personas":
chub_id = str(node.get("id", ""))
pname = node.get("name") or chub_id
folder = f"{_safe(pname)}_{chub_id}" if chub_id else _safe(pname)
return (PERSONAS_DIR / folder / f"{_safe(pname)}.json").exists()
if content_type == "chats":
d = CHATS_DIR / key
return d.exists() and any(d.iterdir())
return False
def _dir_size_str(path: Path) -> str:
try:
total = sum(f.stat().st_size for f in path.rglob("*") if f.is_file())
for unit in ("B", "KB", "MB", "GB"):
if total < 1024:
return f"{total:.0f} {unit}"
total /= 1024
return f"{total:.1f} TB"
except Exception:
return "?"
# ─── chat helpers ─────────────────────────────────────────────────────────────
def _chat_name(s: dict) -> str:
for f in ("character_name", "title"):
if s.get(f): return s[f]
if s.get("name"): return s["name"]
for nk in ("characters", "node", "character", "char"):
n = s.get(nk)
if isinstance(n, dict):
for f in ("name", "full_name", "displayName", "title", "project_name"):
if n.get(f): return n[f]
pip = s.get("primary_image_path")
if not pip:
chars = s.get("characters")
if isinstance(chars, dict):
pip = chars.get("full_path") or chars.get("fullPath")
if isinstance(pip, str) and pip:
slug = pip.rstrip("/").split("/")[-1]
if slug:
return slug.replace("-", " ").replace("_", " ").title()
return str(s.get("id", "unknown"))
def _char_folder_key(s: dict) -> tuple[str, str]:
char_id = str(s.get("character_id", "") or "")
chars_obj = s.get("characters")
char_name = ""
if isinstance(chars_obj, dict):
char_name = chars_obj.get("name") or ""
if not char_name:
fp = chars_obj.get("full_path") or chars_obj.get("fullPath") or ""
if fp:
char_name = fp.rstrip("/").split("/")[-1].replace("-", " ").replace("_", " ").title()
if not char_name:
char_name = char_id or "unknown"
folder_key = _safe(f"{char_name}_{char_id}" if char_id else char_name)
return char_name, folder_key
def _chat_avatar_url(s: dict) -> str | None:
for f in ("primary_image_path", "primary_image_url", "avatar_url", "avatar", "image_url"):
v = s.get(f)
if isinstance(v, str) and v.startswith("http"):
return v
for nk in ("characters", "node", "character", "char"):
n = s.get(nk)
if isinstance(n, dict):
av = n.get("avatar_url") or n.get("avatar")
if isinstance(av, str) and av.startswith("http"):
return av
fp = n.get("fullPath") or n.get("full_path")
if fp:
return f"{CDN_BASE}/{fp}/chara_card_v2.png"
return None
# ─── Tile ─────────────────────────────────────────────────────────────────────
class Tile(QFrame):
clicked = pyqtSignal()
def __init__(self, name: str, parent: QWidget | None = None):
super().__init__(parent)
self.setObjectName("tile")
self.setStyleSheet(_TILE_NORMAL)
self.setFixedWidth(TW + 20)
layout = QVBoxLayout(self)
layout.setContentsMargins(6, 8, 6, 6)
layout.setSpacing(2)
layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter)
self._img_lbl = QLabel()
self._img_lbl.setFixedSize(TW, TH)
self._img_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._img_lbl.setPixmap(_placeholder())
layout.addWidget(self._img_lbl, alignment=Qt.AlignmentFlag.AlignHCenter)
short = (name[:15] + "…") if len(name) > 16 else name
name_lbl = QLabel(short)
name_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
name_lbl.setWordWrap(True)
name_lbl.setStyleSheet(f"color: {TEXT}; font-size: 11pt;")
layout.addWidget(name_lbl)
self._badge = QLabel("Queued")
self._badge.setObjectName("badge")
self._badge.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self._badge)
self._chk = QCheckBox()
self._chk.setChecked(True)
layout.addWidget(self._chk, alignment=Qt.AlignmentFlag.AlignHCenter)
self.setToolTip(name)
def set_status(self, key: str):
self._badge.setText(STATUS_LABEL.get(key, key))
self._badge.setStyleSheet(
f"background-color: {SURFACE}; color: {STATUS_FG.get(key, MUTED)}; "
f"border-radius: 5px; padding: 2px 8px; font-size: 9pt;"
)
def set_badge_text(self, text: str):
self._badge.setText(text)
def set_image(self, raw: bytes):
try:
pil = Image.open(io.BytesIO(raw))
pil.thumbnail((TW, TH), Image.LANCZOS)
cr, cg, cb = _hex_to_rgb(CARD)
bg = Image.new("RGB", (TW, TH), (cr, cg, cb))
bg.paste(pil, ((TW - pil.width) // 2, (TH - pil.height) // 2))
self._img_lbl.setPixmap(_pil_to_pixmap(bg))
except Exception:
pass
def is_checked(self) -> bool:
return self._chk.isChecked()
def set_checked(self, val: bool):
self._chk.setChecked(val)
def enterEvent(self, event):
self.setStyleSheet(_TILE_HOVER)
super().enterEvent(event)
def leaveEvent(self, event):
self.setStyleSheet(_TILE_NORMAL)
super().leaveEvent(event)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
super().mousePressEvent(event)
# ─── TileGrid ─────────────────────────────────────────────────────────────────
class TileGrid(QScrollArea):
def __init__(self, kind: str, parent: QWidget | None = None):
super().__init__(parent)
self.kind = kind
self._click_cb = None
self.setWidgetResizable(True)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
self._container = QWidget()
self._container.setObjectName("tileContainer")
self._layout = QGridLayout(self._container)
self._layout.setContentsMargins(10, 10, 10, 10)
self._layout.setHorizontalSpacing(8)
self._layout.setVerticalSpacing(8)
self._layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter)
self.setWidget(self._container)
self._tiles: dict[str, Tile] = {}
self._names: dict[str, str] = {}
self._order: list[str] = []
self._visible: int = 0
self._cols: int = COLS
self._col: int = 0
self._row: int = 0
self._bulk_state: bool = True
self._sort_keys: dict[str, str] = {}
self._statuses: dict[str, str] = {}
self._msg_counts: dict[str, int] = {}
self._force_keys: set[str] = set()
self._load_btn: QPushButton | None = None
self._reflow_timer = QTimer(self)
self._reflow_timer.setSingleShot(True)
self._reflow_timer.timeout.connect(self._reflow)
def resizeEvent(self, event):
super().resizeEvent(event)
sb_w = self.verticalScrollBar().width() if self.verticalScrollBar().isVisible() else 12
slot_w = TW + 32
new_cols = max(1, (event.size().width() - sb_w - 12) // slot_w)
if new_cols != self._cols:
self._cols = new_cols
self._reflow_timer.start(120)
def _reflow(self):
self._container.setUpdatesEnabled(False)
try:
while self._layout.count():
self._layout.takeAt(0)
self._col = self._row = 0
for key in self._order[:self._visible]:
t = self._tiles[key]
if t.isVisible():
self._layout.addWidget(t, self._row, self._col)
self._col += 1
if self._col >= self._cols:
self._col = 0; self._row += 1
self._sync_load_btn()
finally:
self._container.setUpdatesEnabled(True)
def _place(self, t: Tile):
self._layout.addWidget(t, self._row, self._col)
self._col += 1
if self._col >= self._cols:
self._col = 0; self._row += 1
def _sync_load_btn(self):
remaining = len(self._order) - self._visible
if remaining <= 0:
if self._load_btn:
self._layout.removeWidget(self._load_btn)
self._load_btn.hide()
return
if self._load_btn is None:
self._load_btn = QPushButton()
self._load_btn.setObjectName("loadMoreBtn")
self._load_btn.clicked.connect(self._load_more)
self._load_btn.setParent(self._container)
n = min(PAGE, remaining)
self._load_btn.setText(f"Load {n} more ({remaining} remaining)")
self._load_btn.show()
btn_row = self._row + (1 if self._col > 0 else 0)
self._layout.addWidget(self._load_btn, btn_row, 0, 1, max(self._cols, 1))
def _load_more(self):
if self._load_btn:
self._layout.removeWidget(self._load_btn)
self._load_btn.hide()
start = self._visible
end = min(start + PAGE, len(self._order))
self._container.setUpdatesEnabled(False)
try:
for i in range(start, end):
key = self._order[i]
t = self._tiles[key]
t.show()
self._place(t)
self._visible = end
self._sync_load_btn()
finally:
self._container.setUpdatesEnabled(True)
def add(self, key: str, name: str):
if key in self._tiles:
return
t = Tile(name, self._container)
t.set_checked(self._bulk_state)
# Right-click context menu
t.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
def _ctx(pos, _k=key, _t=t):
menu = QMenu(_t)
if _k in self._force_keys:
act = menu.addAction("✓ Force re-download (on — click to disable)")
act.triggered.connect(lambda: self._force_keys.discard(_k))
else:
act = menu.addAction("↺ Force re-download this item")
act.triggered.connect(lambda: self._force_keys.add(_k))
menu.exec(_t.mapToGlobal(pos))
t.customContextMenuRequested.connect(_ctx)
if self.kind == "chats" and self._click_cb is not None:
t.clicked.connect(lambda _k=key: self._click_cb(_k))
self._tiles[key] = t
self._names[key] = name.lower()
self._order.append(key)
if self._visible < PAGE:
self._place(t)
self._visible += 1
else:
t.hide()
self._sync_load_btn()
def set_status(self, key: str, s: str):
self._statuses[key] = s
if t := self._tiles.get(key):
t.set_status(s)
def set_image(self, key: str, raw: bytes):
if t := self._tiles.get(key):
t.set_image(raw)
def set_badge(self, key: str, text: str):
if t := self._tiles.get(key):
t.set_badge_text(text)
def set_sort_key(self, key: str, date_str: str):
self._sort_keys[key] = date_str
def set_msg_count(self, key: str, count: int):
self._msg_counts[key] = count
def count(self) -> int:
return len(self._tiles)
def select_all(self, val: bool = True):
self._bulk_state = val
for t in self._tiles.values():
t.set_checked(val)
def get_checked(self) -> set[str]:
rendered = set(self._order[:self._visible])
checked = {k for k in rendered if self._tiles[k].is_checked()}
if self._bulk_state:
checked |= set(self._order[self._visible:])
return checked
def filter(self, query: str):
q = query.strip().lower()
if q and self._visible < len(self._order):
self._container.setUpdatesEnabled(False)
try:
for i in range(self._visible, len(self._order)):
t = self._tiles[self._order[i]]
t.show()
self._place(t)
self._visible = len(self._order)
finally:
self._container.setUpdatesEnabled(True)
if not q:
for t in self._tiles.values():
t.show()
self._reflow()
return
while self._layout.count():
self._layout.takeAt(0)
self._col = self._row = 0
for key in self._order:
t = self._tiles[key]
if q in self._names.get(key, ""):
t.show()
self._layout.addWidget(t, self._row, self._col)
self._col += 1
if self._col >= self._cols:
self._col = 0; self._row += 1
else:
t.hide()
if self._load_btn:
self._layout.removeWidget(self._load_btn)
self._load_btn.hide()
def filter_by_status(self, allowed: set | None):
if self._visible < len(self._order):
self._container.setUpdatesEnabled(False)
try:
for i in range(self._visible, len(self._order)):
t = self._tiles[self._order[i]]
t.show()
self._place(t)
self._visible = len(self._order)
finally:
self._container.setUpdatesEnabled(True)
for key in self._order:
t = self._tiles[key]
st = self._statuses.get(key, "queued")
if allowed is None or st in allowed:
t.show()
else:
t.hide()
self._reflow()
def sort_by_date(self, newest_first: bool = True):
self._order.sort(key=lambda k: self._sort_keys.get(k, ""), reverse=newest_first)
self._force_render_all()
self._reflow()
def sort_by_msgs(self, descending: bool = True):
self._order.sort(key=lambda k: self._msg_counts.get(k, 0), reverse=descending)
self._force_render_all()
self._reflow()
def _force_render_all(self):
if self._visible < len(self._order):
self._container.setUpdatesEnabled(False)
try:
for i in range(self._visible, len(self._order)):
t = self._tiles[self._order[i]]
t.show()
self._visible = len(self._order)
finally:
self._container.setUpdatesEnabled(True)
def clear(self):
self._container.setUpdatesEnabled(False)
try:
while self._layout.count():
self._layout.takeAt(0)
for t in self._tiles.values():
t.deleteLater()
self._tiles.clear()
self._names.clear()
self._order.clear()
self._visible = 0
self._col = 0
self._row = 0
self._bulk_state = True
self._sort_keys.clear()
self._statuses.clear()
self._msg_counts.clear()
self._force_keys.clear()
if self._load_btn:
self._load_btn.hide()
finally:
self._container.setUpdatesEnabled(True)
# ─── Dropdown button (QPushButton + QMenu, visible ▾) ─────────────────────────
class _DropBtn(QPushButton):