Repository navigation
Expand file tree
/
Copy pathsample_browser.py
More file actions
2865 lines (2575 loc) · 120 KB
/
Copy pathsample_browser.py
File metadata and controls
2865 lines (2575 loc) · 120 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
"""Sample Browser — a small sample browser for building Elektron Syntakt Twinshot kits.
- "+ Add folder" scans only that folder; results are cached in SQLite.
Later launches don't rescan; "Rescan" only looks at new/changed files.
- Sounds are categorized from file/folder names; if the name says nothing, from the sound itself (~).
- Click / arrow keys to audition. Space: play/stop. Enter: add to kit.
- Drag & drop into Transfer, Ableton, Explorer/Finder. With "Syntakt mode" on, dragged files are copies
converted to 48 kHz / 16-bit / mono / max 5 s (previews play that version too).
- UI languages: English (default), Turkish.
Requires: PyQt6, numpy, soundfile, sounddevice
"""
import hashlib
import io
import json
import math
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import threading
import time
import traceback
import zipfile
from collections import Counter, OrderedDict
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import numpy as np
import sounddevice as sd
import soundfile as sf
from PyQt6.QtCore import (QAbstractTableModel, QEvent, QMimeData, QModelIndex, QPointF, QRect, QRectF, QSettings, Qt,
QThread, QTimer, QUrl, pyqtSignal)
from PyQt6.QtGui import (QColor, QCursor, QDrag, QFont, QFontMetrics, QIcon, QKeySequence, QPainter, QPalette, QPen,
QPixmap, QShortcut)
from PyQt6.QtWidgets import (QAbstractItemView, QApplication, QCheckBox, QComboBox, QFileDialog, QHBoxLayout,
QHeaderView, QInputDialog, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMainWindow,
QMenu, QMessageBox, QProgressBar, QPushButton, QSlider, QSplitter, QStackedWidget,
QTableView, QToolButton, QToolTip, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget)
__version__ = "0.4.1"
def _data_dir():
if os.environ.get("SB_DATA_DIR"):
return Path(os.environ["SB_DATA_DIR"])
if getattr(sys, "frozen", False): # packaged app
if sys.platform == "darwin":
return Path.home() / "Library" / "Application Support" / "SyntaktSampleBrowser"
if os.name == "nt":
return Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "SyntaktSampleBrowser"
return Path.home() / ".local" / "share" / "SyntaktSampleBrowser"
# Running from source: keep data next to the script, not in AppData. Microsoft Store Python redirects
# AppData writes to a private folder, and Transfer/Ableton would then not find the files we drag to them.
return Path(__file__).resolve().parent / "data"
DATA_DIR = _data_dir()
FILE_MANAGER = "Finder" if sys.platform == "darwin" else "Explorer"
DB_PATH = DATA_DIR / "library.db"
CONVERT_DIR = DATA_DIR / "syntakt"
KIT_FILE = DATA_DIR / "current_kit.json"
KITS_DIR = DATA_DIR / "kits"
KIT_DRAG_DIR = DATA_DIR / "kit_drag" # numbered copies handed to Transfer by "Drag kit into Transfer"
LOG_FILE = DATA_DIR / "log.txt"
AUDIO_EXT = {".wav", ".aif", ".aiff", ".flac", ".mp3", ".ogg"}
TWINSHOT_SR = 48000
TWINSHOT_MAX_SEC = 5.0
TWINSHOT_SLOTS = 64
TWINSHOT_MEM = 32 * 1024 * 1024
FEATURES = ("dur", "sr", "ch", "peak_db", "centroid", "flatness", "low", "high", "decay")
MIME_PATHS = "application/x-sample-browser-paths"
# ---------------------------------------------------------------- i18n
# English is the main language; Turkish was the original UI copy.
LANGUAGES = {"en": "English", "tr": "Türkçe"}
STRINGS = {
"en": {
"window_title": "Sample Browser · Syntakt v{version}",
"search_placeholder": "Search name, folder, category, key (e.g. 'kick dark', 'pad fm')…",
"type_all": "All",
"type_oneshot": "One-shot",
"type_loop": "Loop",
"only5": "≤ 5 s only",
"syntakt_mode": "Syntakt mode",
"syntakt_mode_tip": "Previews and drags: 48 kHz · 16-bit · mono · max 5 s, leading/trailing silence "
"trimmed, normalized to -1 dB",
"autoplay": "Autoplay",
"volume": "Volume",
"output": "Output",
"default_output": "Default output",
"language": "Language",
"app_caption": "Twinshot kit builder",
"display_white": "White display",
"display_red": "Red display",
"folders": "Folders",
"add_folder": "+ Add folder",
"categories": "Categories",
"character": "Character",
"empty_state": "To get started, pick a sample folder with <b>+ Add folder</b> on the left.<br>"
"Only the folders you add are scanned, and results are saved.",
"close_similar": "× Close similar",
"similar_banner": "Sounds closest in character to: <b>{name}</b> (category and character filters are off)",
"kit_hint": "Drag samples here from the table, double-click, or press Enter. Drag to reorder. "
"To load the kit, drag the button at the bottom onto Transfer.",
"kit_empty": "Your kit is empty.\nDouble-click sounds or drag them here.",
"kit_remove": "Remove",
"kit_clear": "Clear",
"kit_saved_kits": "Saved kits…",
"kit_save_as": "Save as…",
"kit_more": "More kit actions",
"kit_load_folder": "Load kit from folder…",
"kit_import": "Import kit file…",
"kit_show_folder": "Show kits folder",
"kit_delete_saved": "Delete saved kit “{name}”",
"kit_delete_confirm": "Delete the saved kit “{name}”? (The samples themselves are not touched.)",
"kit_name_prompt": "Kit name:",
"kit_overwrite": "A kit called “{name}” already exists. Replace it?",
"kit_replace_title": "Replace kit?",
"kit_replace": "Replace the current kit ({n} samples)? It isn't saved under a name yet.",
"kit_loaded": "Loaded kit “{name}” ({n} samples)",
"kit_saved": "Saved kit “{name}”",
"kit_from_folder": "Loaded {n} samples from “{name}” in file order",
"kit_folder_empty": "No audio files in that folder.",
"kit_folder_too_many": "The folder has {n} audio files; only the first 64 were used.",
"kit_export_folder": "Export to folder…",
"kit_export_zip": "Export .zip…",
"zip_save_title": "Save kit as .zip",
"zip_done": "Saved {n} samples to:\n{file}\n\nGood for sharing and backups. Note: Transfer may not import "
"zips of Syntakt samples (it can hang on “Converting sample data”). To load the kit, use "
"“Drag kit into Transfer”, or unzip and drag the files.",
"kit_drag": "⠿ Drag kit into Transfer",
"kit_drag_tip": "Drag this onto Transfer (Drop or Explore page). Every kit sample goes along, numbered in "
"slot order and already in Syntakt format. Restart the Syntakt afterwards.",
"kit_drag_click": "Drag this button onto Transfer — clicking it does nothing.",
"slots_warning": "Make sure the Syntakt has at least {n} free sample slots (64 in total, shared by every "
"project). If it doesn't, free some up in Transfer → Explore → Samples first, otherwise "
"the transfer can hang.",
"menu_play": "Play",
"menu_loop": "Loop in slot 2 (pads)",
"loop_tip": "Makes a seamless loop from the sustained part of the sound (max 5 s). Twinshot loops the "
"sample in slot 2 when the AMP mode is ADSR, or AHD with HOLD set to NOTE.",
"loop_marker": "loop",
"kit_label": "Twinshot kit: {n}/{slots} slots · ≈{mb}/32 MB",
"kit_over": "Over the Twinshot limit (64 slots / 32 MB)",
"kit_added": "Added {n} to kit",
"kit_removed": "Removed {n} from kit",
"col_kit": "Kit",
"col_name": "Name",
"col_category": "Category",
"col_folder": "Folder",
"col_length": "Length",
"col_key": "Key",
"col_bpm": "BPM",
"col_character": "Character",
"seconds": "{s} s",
"wave_empty": "Select a sample",
"wave_limit": "5 s (Twinshot limit)",
"wave_syntakt": "Syntakt preview",
"wave_tip": "Click to play from here",
"all_count": "All ({n})",
"drag_count": "{n} samples",
"shortcuts": "Space play/stop · Enter add/remove · Ctrl+F search · Esc clear",
"pick_folder": "Choose sample folder",
"already_added_title": "Already added",
"already_added": "This folder is already in your library, inside:\n{root}",
"remove_folder_title": "Remove folder",
"remove_folder": "{root}\n\nRemove it from the library? (Files on disk won't be touched.)",
"status_finding": "{name}: finding files… {n}",
"status_analyzing": "{name}: analyzing {done}/{total}",
"status_scan_done": "{name}: scan done ({n} new/changed files)",
"status_showing": "Showing {shown} samples · {total} in library",
"err_read": "Couldn't read: {name} — {error}",
"err_play": "Couldn't play audio: {error}",
"menu_add_to_kit": "Add to kit",
"menu_remove_from_kit": "Remove from kit",
"menu_find_similar": "Find similar",
"menu_reveal": "Show in {fm}",
"menu_reveal_converted": "Show Syntakt copy in {fm}",
"menu_copy_path": "Copy path",
"menu_rescan": "Rescan (new/changed files)",
"menu_remove_folder": "Remove from library",
"menu_open_folder": "Open in {fm}",
"clear_kit_title": "Clear kit",
"clear_kit": "Remove all samples from the kit?",
"save_kit_title": "Save kit",
"open_kit_title": "Open kit",
"kit_file_filter": "Kit (*.json)",
"export_pick": "Export kit to…",
"export_done_title": "Export complete",
"export_done": "{n} files exported in Syntakt format:\n{folder}\n\n"
"After transferring them, restart the Syntakt so the new samples show up.",
"export_failed": "Couldn't export:",
"cat_crackle": "Vinyl/Crackle",
"cat_vocal": "Vocal",
"cat_kick": "Kick",
"cat_snare": "Snare",
"cat_clap": "Clap",
"cat_rim": "Rim",
"cat_hat_open": "Open hat",
"cat_hat_closed": "Closed hat",
"cat_cymbal": "Ride/Crash",
"cat_shaker": "Shaker/Tamb",
"cat_tom": "Tom",
"cat_perc": "Perc",
"cat_fill": "Fill",
"cat_drum_loop": "Drum loop",
"cat_bass": "Bass/Sub",
"cat_pad": "Pad/Chord",
"cat_keys": "Keys",
"cat_synth": "Synth",
"cat_atmos": "Atmosphere",
"cat_foley": "Foley",
"cat_fx": "FX",
"cat_other": "Other",
"tag_dark": "Dark",
"tag_bright": "Bright",
"tag_short": "Short",
"tag_tonal": "Tonal",
"tag_noisy": "Noisy",
"tag_sub": "Sub",
"tag_loop": "loop",
"tip_dark": "Mostly low frequencies",
"tip_bright": "Lots of high end",
"tip_short": "Shorter than 0.25 s",
"tip_tonal": "Has a clear pitch",
"tip_noisy": "Noise-like: hats, shakers, textures",
"tip_sub": "Heavy below 150 Hz",
},
"tr": {
"window_title": "Sample Browser · Syntakt v{version}",
"search_placeholder": "Ara: isim, klasör, kategori, ton (ör. 'kick karanlık', 'pad fm')…",
"type_all": "Hepsi",
"type_oneshot": "One-shot",
"type_loop": "Loop",
"only5": "Sadece ≤5 sn",
"syntakt_mode": "Syntakt modu",
"syntakt_mode_tip": "Önizleme ve sürükleme: 48 kHz · 16-bit · mono · en fazla 5 sn, baş/son sessizlik "
"kesilir, -1 dB normalize",
"autoplay": "Otomatik çal",
"volume": "Ses",
"output": "Çıkış",
"default_output": "Varsayılan çıkış",
"language": "Dil",
"app_caption": "Twinshot kit hazırlayıcı",
"display_white": "Beyaz ekran",
"display_red": "Kırmızı ekran",
"folders": "Klasörler",
"add_folder": "+ Klasör ekle",
"categories": "Kategori",
"character": "Karakter",
"empty_state": "Başlamak için soldan <b>+ Klasör ekle</b> ile bir sample klasörü seç.<br>"
"Sadece eklediğin klasör taranır, sonuçlar saklanır.",
"close_similar": "× Benzerleri kapat",
"similar_banner": "Ses karakteri en çok şuna benzeyenler: <b>{name}</b> "
"(kategori ve karakter filtreleri devre dışı)",
"kit_hint": "Tablodan buraya sürükle, çift tıkla ya da Enter. Sırayı sürükleyerek değiştir. "
"Kiti yüklemek için alttaki tuşu Transfer'e sürükle.",
"kit_empty": "Kit boş.\nSeslere çift tıkla ya da buraya sürükle.",
"kit_remove": "Çıkar",
"kit_clear": "Temizle",
"kit_saved_kits": "Kayıtlı kitler…",
"kit_save_as": "Farklı kaydet…",
"kit_more": "Diğer kit işlemleri",
"kit_load_folder": "Klasörden kit yükle…",
"kit_import": "Kit dosyası içe aktar…",
"kit_show_folder": "Kitler klasörünü göster",
"kit_delete_saved": "“{name}” kayıtlı kitini sil",
"kit_delete_confirm": "“{name}” kayıtlı kiti silinsin mi? (Sample'lara dokunulmaz.)",
"kit_name_prompt": "Kit adı:",
"kit_overwrite": "“{name}” adında bir kit zaten var. Üzerine yazılsın mı?",
"kit_replace_title": "Kit değiştirilsin mi?",
"kit_replace": "Mevcut kit ({n} sample) değiştirilsin mi? Henüz bir adla kaydedilmedi.",
"kit_loaded": "“{name}” kiti yüklendi ({n} sample)",
"kit_saved": "“{name}” kiti kaydedildi",
"kit_from_folder": "“{name}” klasöründen {n} sample dosya sırasıyla yüklendi",
"kit_folder_empty": "Bu klasörde ses dosyası yok.",
"kit_folder_too_many": "Klasörde {n} ses dosyası var; sadece ilk 64'ü alındı.",
"kit_export_folder": "Klasöre aktar…",
"kit_export_zip": ".zip olarak aktar…",
"zip_save_title": "Kiti .zip olarak kaydet",
"zip_done": "{n} sample şu dosyaya kaydedildi:\n{file}\n\nPaylaşmak ve yedeklemek için uygun. Not: Transfer "
"Syntakt sample'larını zip'ten almayabiliyor (“Converting sample data”da takılabiliyor). Kiti "
"yüklemek için “Kiti Transfer'e sürükle”yi kullan ya da zip'i açıp dosyaları sürükle.",
"kit_drag": "⠿ Kiti Transfer'e sürükle",
"kit_drag_tip": "Bunu Transfer'e (Drop ya da Explore sayfasına) sürükle. Kitteki tüm sample'lar slot sırasıyla "
"numaralanmış ve Syntakt formatında gider. Sonra Syntakt'ı yeniden başlat.",
"kit_drag_click": "Bu tuşu Transfer'e sürükle, tıklamak bir şey yapmaz.",
"slots_warning": "Syntakt'ta en az {n} boş sample slotu olduğundan emin ol (toplam 64, tüm projeler ortak "
"kullanır). Yoksa önce Transfer → Explore → Samples'tan yer aç, aksi halde aktarım "
"takılabilir.",
"menu_play": "Çal",
"menu_loop": "2. slotta loop (pad'ler)",
"loop_tip": "Sesin sürekli kısmından çıt sesi olmadan dönen bir loop yapar (en fazla 5 sn). Twinshot, AMP "
"modu ADSR ya da HOLD'u NOTE olan AHD iken 2. slottaki sample'ı loop'lar.",
"loop_marker": "loop",
"kit_label": "Twinshot kiti: {n}/{slots} slot · ≈{mb}/32 MB",
"kit_over": "Twinshot sınırı aşıldı (64 slot / 32 MB)",
"kit_added": "Kite {n} ses eklendi",
"kit_removed": "Kitten {n} ses çıkarıldı",
"col_kit": "Kit",
"col_name": "Ad",
"col_category": "Kategori",
"col_folder": "Klasör",
"col_length": "Süre",
"col_key": "Ton",
"col_bpm": "BPM",
"col_character": "Karakter",
"seconds": "{s} sn",
"wave_empty": "Bir sample seç",
"wave_limit": "5 sn (Twinshot sınırı)",
"wave_syntakt": "Syntakt önizleme",
"wave_tip": "Tıkla, buradan çalsın",
"all_count": "Tümü ({n})",
"drag_count": "{n} sample",
"shortcuts": "Boşluk çal/durdur · Enter ekle/çıkar · Ctrl+F ara · Esc temizle",
"pick_folder": "Sample klasörü seç",
"already_added_title": "Zaten ekli",
"already_added": "Bu klasör zaten ekli olan şu klasörün içinde:\n{root}",
"remove_folder_title": "Klasörü kaldır",
"remove_folder": "{root}\n\nKütüphaneden kaldırılsın mı? (Diskteki dosyalara dokunulmaz.)",
"status_finding": "{name}: dosyalar bulunuyor… {n}",
"status_analyzing": "{name}: analiz {done}/{total}",
"status_scan_done": "{name}: tarama bitti ({n} yeni/değişen dosya)",
"status_showing": "{shown} sample gösteriliyor · kütüphanede {total}",
"err_read": "Okunamadı: {name} — {error}",
"err_play": "Ses çalınamadı: {error}",
"menu_add_to_kit": "Kite ekle",
"menu_remove_from_kit": "Kitten çıkar",
"menu_find_similar": "Benzerlerini bul",
"menu_reveal": "{fm}'da göster",
"menu_reveal_converted": "Syntakt kopyasını {fm}'da göster",
"menu_copy_path": "Yolu kopyala",
"menu_rescan": "Yeniden tara (yeni/değişen dosyalar)",
"menu_remove_folder": "Kütüphaneden kaldır",
"menu_open_folder": "{fm}'da aç",
"clear_kit_title": "Kiti temizle",
"clear_kit": "Kitteki tüm sample'lar çıkarılsın mı?",
"save_kit_title": "Kiti kaydet",
"open_kit_title": "Kit aç",
"kit_file_filter": "Kit (*.json)",
"export_pick": "Kiti nereye aktarayım?",
"export_done_title": "Dışa aktarıldı",
"export_done": "{n} dosya Syntakt formatında aktarıldı:\n{folder}\n\n"
"Aktardıktan sonra yeni sample'ların görünmesi için Syntakt'ı yeniden başlat.",
"export_failed": "Aktarılamayanlar:",
"cat_crackle": "Cızırtı/Vinyl",
"cat_vocal": "Vokal",
"cat_kick": "Kick",
"cat_snare": "Snare",
"cat_clap": "Clap",
"cat_rim": "Rim",
"cat_hat_open": "Hat (açık)",
"cat_hat_closed": "Hat (kapalı)",
"cat_cymbal": "Ride/Crash",
"cat_shaker": "Shaker/Tamb",
"cat_tom": "Tom",
"cat_perc": "Perc",
"cat_fill": "Fill",
"cat_drum_loop": "Davul loop",
"cat_bass": "Bas/Sub",
"cat_pad": "Pad/Akor",
"cat_keys": "Keys",
"cat_synth": "Synth",
"cat_atmos": "Atmosfer",
"cat_foley": "Foley",
"cat_fx": "FX",
"cat_other": "Diğer",
"tag_dark": "Karanlık",
"tag_bright": "Parlak",
"tag_short": "Kısa",
"tag_tonal": "Tonal",
"tag_noisy": "Gürültülü",
"tag_sub": "Sub",
"tag_loop": "loop",
"tip_dark": "Çoğunlukla alçak frekanslar",
"tip_bright": "Tizi bol",
"tip_short": "0,25 sn'den kısa",
"tip_tonal": "Belirgin bir perdesi var",
"tip_noisy": "Gürültü benzeri: hat, shaker, doku",
"tip_sub": "150 Hz altı ağır",
},
}
LANG = "en"
def tr(key, **kw):
s = STRINGS.get(LANG, {}).get(key) or STRINGS["en"].get(key, key)
return s.format(**kw) if kw else s
def cat_name(cat):
return tr("cat_" + cat)
def secs(x):
return tr("seconds", s=f"{x:.2f}")
# ---------------------------------------------------------------- categorizing
def split_words(s):
"""'RKU_DST_HatOpen-01' -> ' rku dst hat open 01 '"""
s = re.sub(r"([a-z])([A-Z])", r"\1 \2", s)
s = re.sub(r"([A-Za-z])(\d)", r"\1 \2", s)
s = re.sub(r"[_\-\.\(\)\[\]&,+]+", " ", s)
return " " + re.sub(r"\s+", " ", s).strip().lower() + " "
def _rx(words):
return re.compile(r"(?<![a-z])(?:%s)(?![a-z])" % words)
# Order matters: the first matching rule wins (filename first, then folders from deepest up).
# The ids are language-neutral; the UI shows tr("cat_<id>").
CATEGORY_RULES = [
("crackle", _rx(r"vinyl|crackles?|hiss|tape noise")),
("vocal", _rx(r"vocals?|vox|voices?|acapellas?|adlibs?|chants?|spoken")),
("kick", _rx(r"kicks?|kik|kck|bd|bass ?drums?")),
("snare", _rx(r"snares?|snr|sd")),
("clap", _rx(r"claps?|handclaps?|cp")),
("rim", _rx(r"rims?|rimshots?|side ?sticks?|sticks?")),
("hat_open", _rx(r"open ?hi ?hats?|open ?hats?|hats? ?open|open ?hh|ohh?")),
("hat_closed", _rx(r"hi ?hats?|hats?|hh|chh?|closed ?hats?")),
("cymbal", _rx(r"rides?|crash(es)?|cymbals?|cym|splash|china")),
("shaker", _rx(r"shakers?|shkr|shake|tamb(ourine)?s?|maracas?|cabasa")),
("tom", _rx(r"toms?|floor ?tom")),
("perc", _rx(r"percs?|percussions?|congas?|bongos?|cowbells?|claves?|blocks?|wood|knocks?|clacks?|"
r"tablas?|djembes?|timbales?|snaps?|snappys?|clicks?|thuds?|clunks?")),
("fill", _rx(r"fills?|rolls?")),
("drum_loop", _rx(r"drums?|tops?|breaks?|breakbeats?|beats?|grooves?")),
("bass", _rx(r"bass(es)?|subs?|808s?|reeses?|wobbles?")),
("pad", _rx(r"pads?|chords?|stabs?|drones?|strings?|choirs?")),
("keys", _rx(r"keys?|pianos?|rhodes|organs?|wurli|epiano|bells?|mallets?|marimba|guitars?")),
("synth", _rx(r"synths?|leads?|plucks?|arps?|melod(y|ies|ic)|music")),
("atmos", _rx(r"atmos|atmospheres?|ambiences?|ambient|textures?|field|rain|nature|wind|room ?tone|"
r"soundscapes?")),
("foley", _rx(r"foley|animism|cutlery|silverware|coins?|paper|scraps?|swipes?|splats?|squish(es)?|drips?|"
r"scatter|splash(es)?")),
("fx", _rx(r"fx|sfx|risers?|rise|uplifters?|downlifters?|sweeps?|impacts?|whoosh|swoosh|noise|"
r"transitions?|reverse|downers?")),
]
CATEGORY_ORDER = [c for c, _ in CATEGORY_RULES] + ["other"]
TONAL_CATS = {"bass", "pad", "keys", "synth", "vocal"}
TAG_ROWS = (("dark", "bright", "short"), ("tonal", "noisy", "sub"))
PACK_MARKERS = re.compile(r" - |\bvol\b|vol\.|sample|pack|sounds|\bkit\b|collection|series|presents|edition|"
r"\bby\b|library|essentials|suite", re.I)
ONESHOT_RX = _rx(r"one ?shots?|oneshots?|hits?|shots?")
LOOP_RX = _rx(r"loops?|songstarters?|construction|grooves?")
KEY_RX = re.compile(r"^([A-Ga-g])(#|b|sharp|flat)?(m|min|minor|maj|major)?$")
NOTE_RX = re.compile(r"^([A-G])(#|b)?(-?\d)$")
def match_category(scopes):
for words in scopes:
for cat, rx in CATEGORY_RULES:
if rx.search(words):
return cat
return None
def guess_category(s):
if s.low > 0.55 and s.dur < 1.2:
return "kick"
if s.centroid > 6000 and s.dur < 0.5:
return "hat_closed"
if s.centroid > 5000 and s.flatness > 0.2:
return "hat_open" if s.dur < 1.5 else "atmos"
if s.flatness < 0.005 and s.dur > 0.8:
return "pad" if s.centroid < 2000 else "synth"
if s.dur < 0.5:
return "perc"
return "other"
def parse_bpm(name_words):
m = re.search(r"(?<!\d)(\d{2,3}) ?bpm", name_words)
if m:
return int(m.group(1))
for t in name_words.split():
if t.isdigit() and 60 <= int(t) <= 200:
return int(t)
return 0
def parse_key(stem, cat):
for t in reversed(re.split(r"[_\-\s\.\(\)\[\]]+", stem)):
m = NOTE_RX.match(t)
if m:
return t
m = KEY_RX.match(t)
if not m:
continue
letter, acc, q = m.groups()
if letter.islower() and not q:
continue
if not acc and not q and cat not in TONAL_CATS:
continue
acc = {"sharp": "#", "flat": "b"}.get(acc, acc or "")
minor = "m" if q in ("m", "min", "minor") else ""
return letter.upper() + acc + minor
return ""
def character_tags(s):
tags = []
if 0 < s.centroid < 700:
tags.append("dark")
elif s.centroid > 3500:
tags.append("bright")
if s.flatness < 0.005 and s.dur > 0.5 and s.low < 0.5:
tags.append("tonal")
elif s.flatness > 0.15:
tags.append("noisy")
if s.low > 0.5:
tags.append("sub")
if s.dur < 0.25:
tags.append("short")
return tags
class Sample:
__slots__ = ("path", "root", "name", "stem", "rel", "top", "sub", "dur", "sr", "ch", "peak_db", "centroid",
"flatness", "low", "high", "decay", "err", "category", "guessed", "is_loop", "key", "bpm", "tags",
"hay", "size", "mtime")
def make_sample(rec):
s = Sample()
s.path, s.root = rec["path"], rec["root"]
s.size, s.mtime = rec.get("size") or 0, rec.get("mtime") or 0
for k in FEATURES:
setattr(s, k, rec.get(k) or 0.0)
s.err = rec.get("err") or ""
s.name = os.path.basename(s.path)
s.stem = os.path.splitext(s.name)[0]
s.rel = os.path.relpath(s.path, s.root)
parts = Path(s.rel).parts
dirs = parts[:-1]
s.top = dirs[0] if dirs else ""
s.sub = dirs[-1] if len(dirs) > 1 else ""
name_words = split_words(s.stem)
dir_scopes = []
for i, d in reversed(list(enumerate(dirs))):
w = split_words(d)
if i == 0 and len(w.split()) >= 3 and PACK_MARKERS.search(d):
continue # product / pack name, not a sound type
dir_scopes.append(w)
cat = match_category([name_words] + dir_scopes)
s.guessed = cat is None
s.category = cat or guess_category(s)
if s.category == "other":
s.guessed = False
path_words = name_words + " ".join(dir_scopes)
s.bpm = parse_bpm(name_words)
if ONESHOT_RX.search(path_words):
s.is_loop = False
elif LOOP_RX.search(path_words):
s.is_loop = True
else:
s.is_loop = bool(s.bpm) and s.dur > 2.5
s.key = parse_key(s.stem, s.category)
s.tags = character_tags(s)
# searchable in every UI language: "kick dark" and "kick karanlık" both work
words = [s.rel, s.key, "loop" if s.is_loop else "oneshot one-shot"]
for table in STRINGS.values():
words.append(table.get("cat_" + s.category, ""))
words.extend(table.get("tag_" + t, "") for t in s.tags)
s.hay = " ".join(words).lower()
return s
def feature_vec(s):
return np.array([
math.log10(max(s.centroid, 30.0)) / 4.3 * 2.0,
math.sqrt(max(s.flatness, 0.0)) * 1.5,
s.low,
s.high,
(math.log10(max(s.dur, 0.01)) + 2) / 4,
min(s.decay, 3.0) / 3 * 0.8,
], dtype=np.float32)
# ---------------------------------------------------------------- audio
def analyze(path):
info = sf.info(path)
sr = info.samplerate or 1
dur = info.frames / sr
n = min(info.frames, int(sr * 3))
out = dict(dur=dur, sr=sr, ch=info.channels, peak_db=-120.0, centroid=0.0, flatness=0.0, low=0.0, high=0.0,
decay=0.0)
if n <= 0:
return out
x, _ = sf.read(path, frames=n, always_2d=True, dtype="float32")
m = x.mean(axis=1)
a = np.abs(m)
peak = float(a.max())
if peak <= 1e-6:
return out
win = max(1, int(sr * 0.01))
env = np.convolve(a, np.ones(win, dtype=np.float32) / win, mode="same")
ip = int(env.argmax())
below = np.flatnonzero(env[ip:] < env[ip] * 0.01)
decay = below[0] / sr if below.size else (env.size - ip) / sr
onset = int(np.flatnonzero(a > peak * 0.01)[0])
seg = m[onset:onset + sr]
if seg.size < 4096:
seg = np.pad(seg, (0, 4096 - seg.size))
p = np.abs(np.fft.rfft(seg * np.hanning(seg.size))) ** 2
f = np.fft.rfftfreq(seg.size, 1 / sr)
tot = float(p.sum()) + 1e-12
band = p[(f > 50) & (f < 16000)] + 1e-12
out.update(
peak_db=20 * math.log10(peak),
centroid=float((f * p).sum() / tot),
flatness=float(np.exp(np.mean(np.log(band))) / np.mean(band)),
low=float(p[f < 150].sum() / tot),
high=float(p[f > 5000].sum() / tot),
decay=float(decay),
)
return out
def analyze_safe(path):
try:
return analyze(path)
except Exception as e: # unreadable / unsupported file
return dict(err=str(e)[:200])
def resample(y, sr_in, sr_out):
"""FFT resampling (band-limited). Zero padding at both ends keeps the circular FFT from wrapping."""
if sr_in == sr_out or y.size == 0:
return y
pad = int(0.05 * sr_in)
z = np.concatenate([np.zeros(pad), y, np.zeros(pad)])
m = int(round(z.size * sr_out / sr_in))
out = np.fft.irfft(np.fft.rfft(z), m) * (m / z.size)
start = int(round(pad * sr_out / sr_in))
return out[start:start + int(round(y.size * sr_out / sr_in))]
def to_syntakt(path):
"""Mono, 48 kHz, silence-trimmed, max 5 s, peak -1 dBFS float32 array."""
info = sf.info(path)
n = min(info.frames, int(info.samplerate * 30))
x, sr = sf.read(path, frames=n, always_2d=True, dtype="float64")
y = x.mean(axis=1)
peak = float(np.abs(y).max()) if y.size else 0.0
if peak <= 1e-6:
return np.zeros(64, dtype=np.float32)
nz = np.flatnonzero(np.abs(y) > peak * 10 ** (-60 / 20))
y = y[max(0, nz[0] - int(0.001 * sr)):min(y.size, nz[-1] + int(0.01 * sr))]
y = y[:int((TWINSHOT_MAX_SEC + 0.05) * sr)] # cut before resampling, it's the slow part
y = resample(y, int(sr), TWINSHOT_SR)
cap = int(TWINSHOT_MAX_SEC * TWINSHOT_SR)
if y.size > cap:
y = y[:cap]
fade = int(0.35 * TWINSHOT_SR)
else:
fade = min(int(0.005 * TWINSHOT_SR), y.size)
if fade > 0:
y[-fade:] *= np.linspace(1.0, 0.0, fade) ** 2
pk = float(np.abs(y).max())
if pk > 0:
y *= 10 ** (-1 / 20) / pk
return y.astype(np.float32)
def safe_name(stem, limit=40):
s = re.sub(r"[^A-Za-z0-9 _\-#]+", "_", stem).strip(" _")
return (s or "sample")[:limit]
def loop_ready(path):
"""Seamless loop for Twinshot sample slot 2 (it loops when AMP mode is ADSR, or AHD with HOLD = NOTE).
Takes the sustained part of the sound (skips the attack swell and the release tail), max 5 s, and
crossfades its end into its start, so jumping from the last sample back to the first is continuous.
"""
info = sf.info(path)
n = min(info.frames, int(info.samplerate * 30))
x, sr = sf.read(path, frames=n, always_2d=True, dtype="float64")
y = x.mean(axis=1)
if y.size < 0.2 * sr or float(np.abs(y).max()) <= 1e-6:
return to_syntakt(path)
y = resample(y - y.mean(), int(sr), TWINSHOT_SR)
sr = TWINSHOT_SR
win = int(0.05 * sr)
env = np.sqrt(np.convolve(y ** 2, np.ones(win) / win, mode="same"))
loud = np.flatnonzero(env >= env.max() * 0.5)
a, b = int(loud[0]), int(loud[-1])
cap = int(TWINSHOT_MAX_SEC * sr)
xf = int(min(0.4 * sr, max((b - a) // 4, 0.02 * sr)))
seg = y[a:min(b, a + cap + xf)]
if seg.size < 2 * xf + int(0.1 * sr): # sustain too short: loop what we have from the loud point on
seg = y[a:a + cap + xf]
xf = max(1, min(xf, seg.size // 3))
body = seg.size - xf
out = seg[:body].copy()
t = np.linspace(0.0, 1.0, xf)
out[:xf] = seg[:xf] * np.sqrt(t) + seg[body:body + xf] * np.sqrt(1.0 - t)
pk = float(np.abs(out).max())
if pk > 0:
out *= 10 ** (-1 / 20) / pk
return out.astype(np.float32)
def kit_audio(path, loop=False):
return loop_ready(path) if loop else to_syntakt(path)
def write_syntakt(y, out):
"""16-bit / 48 kHz / mono WAV with TPDF dither; `out` is a path or a binary file object."""
d = (np.random.random(y.size) - np.random.random(y.size)) / 32768.0
z = np.clip(y.astype(np.float64) + d, -1.0, 1.0 - 1 / 32768)
if isinstance(out, (str, Path)):
sf.write(str(out), z, TWINSHOT_SR, subtype="PCM_16")
else:
sf.write(out, z, TWINSHOT_SR, format="WAV", subtype="PCM_16")
def kit_file_name(index, s, loop=False):
return f"{index:02d}_{safe_name(s.stem, 28)}{'_loop' if loop else ''}.wav"
def syntakt_file(s, loop=False):
"""Converted copy in the cache; the file keeps the sample's own name (Transfer uses it)."""
h = hashlib.sha1(f"{s.path}|{s.size}|{s.mtime}|{loop}".encode("utf-8", "replace")).hexdigest()[:12]
out = CONVERT_DIR / h / (safe_name(s.stem) + ("_loop" if loop else "") + ".wav")
if not out.exists():
out.parent.mkdir(parents=True, exist_ok=True)
write_syntakt(kit_audio(s.path, loop), out)
return out
def natural_key(s):
return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s.lower())]
# ---------------------------------------------------------------- database / scanning
def db_connect():
DATA_DIR.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(str(DB_PATH), timeout=30)
con.execute("PRAGMA journal_mode=WAL")
con.execute("CREATE TABLE IF NOT EXISTS roots(path TEXT PRIMARY KEY, added REAL, scanned REAL)")
con.execute("CREATE TABLE IF NOT EXISTS samples(path TEXT PRIMARY KEY, root TEXT, size INTEGER, mtime REAL, "
"dur REAL, sr INTEGER, ch INTEGER, peak_db REAL, centroid REAL, flatness REAL, low REAL, "
"high REAL, decay REAL, err TEXT)")
con.execute("CREATE INDEX IF NOT EXISTS ix_root ON samples(root)")
return con
SAMPLE_COLS = ("path", "root", "size", "mtime") + FEATURES + ("err",)
class Scanner(QThread):
progress = pyqtSignal(str, int, int) # root, done, total (total < 0 while counting files)
batch = pyqtSignal(object) # list[dict]
removed = pyqtSignal(object) # list[str]
root_done = pyqtSignal(str, int)
def __init__(self, parent=None):
super().__init__(parent)
self.queue = []
self.lock = threading.Lock()
self.stop_flag = False
self.current_root = None
def enqueue(self, root, front=False):
with self.lock:
if root not in self.queue:
self.queue.insert(0, root) if front else self.queue.append(root)
def pending(self):
with self.lock:
return list(self.queue)
def run(self):
self.stop_flag = False
con = db_connect()
try:
while not self.stop_flag:
with self.lock:
root = self.queue.pop(0) if self.queue else None
if root is None:
break
self.current_root = root
self.scan_root(con, root)
if not self.stop_flag:
self.current_root = None
finally:
con.close()
def scan_root(self, con, root):
files = []
for dirpath, dirnames, filenames in os.walk(root):
if self.stop_flag:
return
dirnames[:] = [d for d in dirnames if not d.startswith(".") and d != "__MACOSX"]
for fn in filenames:
if fn.startswith("._") or os.path.splitext(fn)[1].lower() not in AUDIO_EXT:
continue
p = os.path.join(dirpath, fn)
try:
st = os.stat(p)
except OSError:
continue
files.append((p, st.st_size, st.st_mtime))
self.progress.emit(root, 0, -len(files))
known = {p: (sz, mt) for p, sz, mt in con.execute("SELECT path, size, mtime FROM samples WHERE root=?",
(root,))}
seen = {p for p, _, _ in files}
gone = [p for p in known if p not in seen]
if gone:
con.executemany("DELETE FROM samples WHERE path=?", [(p,) for p in gone])
con.commit()
self.removed.emit(gone)
todo = [f for f in files if known.get(f[0]) != (f[1], f[2])]
total, done, buf = len(todo), 0, []
self.progress.emit(root, 0, total)
def flush():
if not buf:
return
con.executemany("INSERT OR REPLACE INTO samples(%s) VALUES (%s)"
% (",".join(SAMPLE_COLS), ",".join("?" * len(SAMPLE_COLS))),
[tuple(r.get(c) for c in SAMPLE_COLS) for r in buf])
con.commit()
self.batch.emit(list(buf))
buf.clear()
with ThreadPoolExecutor(max_workers=min(8, os.cpu_count() or 4)) as ex:
futs = {ex.submit(analyze_safe, p): (p, sz, mt) for p, sz, mt in todo}
for fut in as_completed(futs):
if self.stop_flag:
ex.shutdown(cancel_futures=True)
break
p, sz, mt = futs[fut]
buf.append(dict(path=p, root=root, size=sz, mtime=mt, **fut.result()))
done += 1
if len(buf) >= 250:
flush()
self.progress.emit(root, done, total)
flush()
if not self.stop_flag:
con.execute("UPDATE roots SET scanned=? WHERE path=?", (time.time(), root))
con.commit()
self.root_done.emit(root, total)
# ---------------------------------------------------------------- widgets
# ---------------------------------------------------------------- look & feel
# Modelled on the hardware: matte black panel, grey silkscreen labels, red/pink secondary labels and FUNC key,
# OLED menus (selected row = inverted), trig keys with coloured LED numbers.
LED = {"red": "#ff4d4d", "yellow": "#f4d24e", "green": "#a6e15a", "white": "#f2f2f2", "pink": "#ff7d8c",
"dim": "#8d8d93"}
CATEGORY_LED = {
"kick": "red", "tom": "red", "bass": "red",
"snare": "yellow", "clap": "yellow", "rim": "yellow",
"hat_closed": "white", "hat_open": "white", "cymbal": "white", "shaker": "white",
"perc": "green", "foley": "green", "fill": "green", "drum_loop": "green",
"pad": "pink", "keys": "pink", "synth": "pink", "vocal": "pink",
"atmos": "dim", "crackle": "dim", "fx": "dim", "other": "dim",
}
THEMES = { # "white" = the current Syntakt OLED, "red" = the red display / amber FUNC look
"white": {"ink": "#f4f4f4", "oled": "#000000", "func": "#e3525b", "func_text": "#1c0b0c", "accent": "#ff4d4d"},
"red": {"ink": "#ff5a2e", "oled": "#0c0201", "func": "#e07a3a", "func_text": "#1c0e04", "accent": "#ff7a3d"},
}
THEME = "white"
def theme(key):
return THEMES[THEME][key]
def accent_color(alpha=255):
c = QColor(theme("accent"))
c.setAlpha(alpha)
return c
def led_color(cat):
return QColor(LED[CATEGORY_LED.get(cat, "dim")])
def caps(s):
"""Upper-case like the panel labels (Turkish-aware: i -> İ)."""
return (s.replace("i", "İ") if LANG == "tr" else s).upper()
_icons = {}
def led_icon(cat):
"""Small glowing LED dot in the category's colour."""
key = CATEGORY_LED.get(cat, "dim")
if key not in _icons:
pm = QPixmap(12, 12)
pm.fill(Qt.GlobalColor.transparent)
p = QPainter(pm)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
c = QColor(LED[key])
glow = QColor(c)
glow.setAlpha(60)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(glow)
p.drawEllipse(0, 0, 12, 12)
p.setBrush(c)
p.drawEllipse(3, 3, 6, 6)
p.end()
_icons[key] = QIcon(pm)
return _icons[key]
def build_stylesheet():
t = THEMES[THEME]
return f"""
QWidget {{ background: #141416; color: #e8e8ea; font-size: 12px; }}
QMainWindow, QStatusBar {{ background: #111113; }}
QStatusBar {{ color: #8e8e95; }}
QStatusBar QLabel {{ color: #66666e; background: transparent; }}
QLabel {{ background: transparent; }}
QLabel#wordmark {{ color: #fafafa; font-size: 19px; font-weight: 700; }}
QLabel#caption {{ color: {t['func']}; font-size: 9px; font-weight: 600; }}
QLabel#section {{ color: #8e8e95; font-size: 10px; font-weight: 700; padding-top: 6px; }}
QLabel#hint {{ color: #74747c; font-size: 11px; }}
QLabel#empty {{ color: #8e8e95; font-size: 15px; }}
QLabel#warn {{ color: {LED['yellow']}; font-size: 11px; }}
QLineEdit, QComboBox {{ background: #0c0c0e; border: 1px solid #2c2c31; border-radius: 4px; padding: 4px 8px;
selection-background-color: {t['ink']}; selection-color: {t['oled']}; }}
QLineEdit:focus, QComboBox:focus {{ border-color: #66666e; }}
QComboBox::drop-down {{ border: none; width: 18px; }}
QComboBox QAbstractItemView {{ background: #0c0c0e; border: 1px solid #2c2c31; outline: 0;
selection-background-color: {t['ink']}; selection-color: {t['oled']}; }}
QPushButton, QToolButton {{ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #323236, stop:1 #252528);
border: 1px solid #3c3c41; border-bottom-color: #19191c; border-radius: 5px; padding: 6px 10px;
color: #e8e8ea; font-size: 11px; font-weight: 700; }}
QPushButton:hover, QToolButton:hover {{ border-color: #5c5c64; }}
QPushButton:pressed, QToolButton:pressed {{ background: #1c1c1f; }}
QPushButton:disabled {{ color: #4f4f56; border-color: #2a2a2e; background: #1f1f22; }}
QPushButton:checked {{ color: {t['accent']}; border: 1px solid {t['accent']}; background: #1c1617; }}
QPushButton#func {{ background: {t['func']}; color: {t['func_text']}; border: 1px solid {t['func']}; }}
QPushButton#func:hover {{ border-color: #ffffff; }}
QPushButton#func:disabled {{ background: #2e2224; color: #5c4c4e; border-color: #2e2224; }}
QToolButton::menu-indicator {{ image: none; width: 0; }}
QCheckBox {{ spacing: 6px; color: #d4d4d8; background: transparent; }}
QCheckBox::indicator {{ width: 9px; height: 9px; border-radius: 2px; background: #2a2a2e; border: 1px solid #4a4a50; }}
QCheckBox::indicator:checked {{ background: {t['accent']}; border-color: {t['accent']}; }}
QTreeWidget, QListWidget, QTableView {{ background: #0e0e10; alternate-background-color: #131316;
border: 1px solid #25252a; border-radius: 6px; outline: 0; }}
QTreeWidget::item, QListWidget::item {{ padding: 3px 4px; border-radius: 2px; }}
QTreeWidget#oled::item:selected, QListWidget#oled::item:selected {{ background: {t['ink']}; color: {t['oled']}; }}
QListWidget#kit::item:selected, QTableView::item:selected {{ background: #34353b; color: #ffffff; }}
QTreeWidget::branch {{ background: transparent; }}
QHeaderView::section {{ background: #17171a; color: #8e8e95; border: none; border-bottom: 1px solid #25252a;
padding: 4px 6px; font-size: 10px; font-weight: 700; }}
QTableCornerButton::section {{ background: #17171a; border: none; }}
QScrollBar:vertical {{ background: transparent; width: 10px; margin: 2px; }}
QScrollBar:horizontal {{ background: transparent; height: 10px; margin: 2px; }}
QScrollBar::handle {{ background: #3a3a40; border-radius: 3px; min-height: 24px; min-width: 24px; }}
QScrollBar::handle:hover {{ background: #50505a; }}
QScrollBar::add-line, QScrollBar::sub-line {{ width: 0; height: 0; }}
QScrollBar::add-page, QScrollBar::sub-page {{ background: transparent; }}
QSplitter::handle {{ background: #141416; }}
QSlider {{ background: transparent; }}
QSlider::groove:horizontal {{ height: 4px; background: #2a2a2e; border-radius: 2px; }}
QSlider::sub-page:horizontal {{ background: #6d6d75; border-radius: 2px; }}
QSlider::handle:horizontal {{ width: 14px; height: 14px; margin: -6px 0; border-radius: 7px;
background: qradialgradient(cx:0.5, cy:0.35, radius:0.7, stop:0 #55555c, stop:1 #141416);
border: 1px solid #5a5a62; }}
QMenu {{ background: #0c0c0e; border: 1px solid #2c2c31; padding: 4px; }}
QMenu::item {{ padding: 5px 18px; border-radius: 3px; background: transparent; }}
QMenu::item:selected {{ background: {t['ink']}; color: {t['oled']}; }}
QMenu::item:disabled {{ color: #55555b; }}
QMenu::separator {{ height: 1px; background: #2c2c31; margin: 4px 6px; }}
QMenu::indicator {{ width: 9px; height: 9px; border-radius: 2px; background: #2a2a2e; border: 1px solid #4a4a50;
margin-left: 4px; }}
QMenu::indicator:checked {{ background: {t['accent']}; border-color: {t['accent']}; }}
QToolTip {{ background: #000000; color: {t['ink']}; border: 1px solid #3a3a40; padding: 4px; }}
QProgressBar {{ background: #0c0c0e; border: 1px solid #2c2c31; border-radius: 3px; max-height: 8px;
color: transparent; }}
QProgressBar::chunk {{ background: {t['accent']}; border-radius: 2px; }}
"""
def section_label(text):
lbl = QLabel(caps(text), objectName="section")
f = lbl.font()
f.setLetterSpacing(QFont.SpacingType.AbsoluteSpacing, 1.4)
lbl.setFont(f)