-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeclutter-app.py
More file actions
3481 lines (3224 loc) · 164 KB
/
Copy pathdeclutter-app.py
File metadata and controls
3481 lines (3224 loc) · 164 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
import os
import sys
import shutil
import random
import json
from pathlib import Path
from datetime import datetime, timedelta
# ── Defaults (overridable via .env) ───────────────────────────────────────────
BASE_DIR = Path("./test-nas")
ARCHIVE_DIR = "verwerkt"
INBOX_DIR = "in_behandeling"
RAW_DIR = "ruwe_data"
TRASH_DIR = "prullenbak"
DATELESS_DIR = "datumloos"
PORT = 8765
IMMICH_URL = "http://localhost:2283"
IMMICH_API_KEY = ""
DEBUG = False
PRESORT_DEBUG = False
DATA_DIR = Path(__file__).parent
TRANSLATIONS_DIR = Path(__file__).parent / "translations"
RECENTS_FILE = DATA_DIR / "recents.json"
THUMBCACHE_DIR = DATA_DIR / ".thumbcache"
DATUMCACHE_FILE = DATA_DIR / ".datumcache.json"
LOG_FILE = DATA_DIR / "declutter.log"
# ── Logging ───────────────────────────────────────────────────────────────────
def _log(msg: str):
"""Schrijft naar stdout én logbestand met tijdstempel."""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"{ts} {msg}"
print(line)
try:
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception:
pass
# ── .env loader ───────────────────────────────────────────────────────────────
def _laad_env_bestand(pad: Path) -> dict:
"""Leest een .env bestand, geeft {key: value}. Negeert # en lege regels."""
result = {}
try:
for regel in pad.read_text(encoding="utf-8").splitlines():
regel = regel.strip()
if not regel or regel.startswith("#"):
continue
if "=" in regel:
key, _, val = regel.partition("=")
key, val = key.strip(), val.strip()
if key and val:
result[key] = val
except FileNotFoundError:
pass
return result
def _toepas_env(cfg: dict):
global BASE_DIR, ARCHIVE_DIR, INBOX_DIR, RAW_DIR, TRASH_DIR, DATELESS_DIR, PORT
global IMMICH_URL, IMMICH_API_KEY, DEBUG, PRESORT_DEBUG, DATA_DIR
global RECENTS_FILE, THUMBCACHE_DIR, DATUMCACHE_FILE, LOG_FILE
# Deprecated Dutch variable names → English replacements.
# These will be removed in a future version.
_deprecated = {
"ARCHIEF_DIR": "ARCHIVE_DIR",
"UITZOEKEN_DIR": "INBOX_DIR",
"DUMP_DIR": "RAW_DIR",
"PRULLENBAK_DIR": "TRASH_DIR",
"DATUMLOOS_DIR": "DATELESS_DIR",
}
for old, new in _deprecated.items():
if old in cfg and new not in cfg:
print(f"[DEPRECATION] '{old}' is deprecated — please rename it to '{new}' in your .env file.")
cfg[new] = cfg[old]
if "DATA_DIR" in cfg:
DATA_DIR = Path(cfg["DATA_DIR"])
RECENTS_FILE = DATA_DIR / "recents.json"
THUMBCACHE_DIR = DATA_DIR / ".thumbcache"
DATUMCACHE_FILE = DATA_DIR / ".datumcache.json"
LOG_FILE = DATA_DIR / "declutter.log"
if "BASE_DIR" in cfg: BASE_DIR = Path(cfg["BASE_DIR"])
if "ARCHIVE_DIR" in cfg: ARCHIVE_DIR = cfg["ARCHIVE_DIR"]
if "INBOX_DIR" in cfg: INBOX_DIR = cfg["INBOX_DIR"]
if "RAW_DIR" in cfg: RAW_DIR = cfg["RAW_DIR"]
if "TRASH_DIR" in cfg: TRASH_DIR = cfg["TRASH_DIR"]
if "DATELESS_DIR" in cfg: DATELESS_DIR = cfg["DATELESS_DIR"]
if "PORT" in cfg:
try: PORT = int(cfg["PORT"])
except ValueError: pass
if "IMMICH_URL" in cfg: IMMICH_URL = cfg["IMMICH_URL"]
if "IMMICH_API_KEY" in cfg: IMMICH_API_KEY = cfg["IMMICH_API_KEY"]
if "DEBUG" in cfg: DEBUG = cfg["DEBUG"].lower() in ("1", "true", "yes")
if "PRESORT_DEBUG" in cfg: PRESORT_DEBUG = cfg["PRESORT_DEBUG"].lower() in ("1", "true", "yes")
# Laad .env bij import (voor normale modus)
_toepas_env(_laad_env_bestand(Path(__file__).parent / ".env"))
# ── Dependency check ──────────────────────────────────────────────────────────
def check_dependencies():
ok = True
if sys.version_info < (3, 8):
print(f"[FOUT] Python 3.8+ vereist (gevonden: {sys.version})")
ok = False
try:
import PIL # noqa: F401
except ImportError:
print("[FOUT] Pillow niet gevonden. Installeer via: pip install Pillow")
ok = False
try:
import pillow_heif # noqa: F401
except ImportError:
print("[WAARSCHUWING] pillow-heif niet gevonden. HEIC-bestanden worden niet ondersteund. Installeer via: pip install pillow-heif")
try:
import rawpy # noqa: F401
except ImportError:
print("[WAARSCHUWING] rawpy niet gevonden. ARW/RAW-thumbnails niet beschikbaar. Installeer via: pip install rawpy")
if not ok:
sys.exit(1)
# ── Stap 1: Testdata ──────────────────────────────────────────────────────────
def maak_testdata(aantal=40, progress_cb=None):
import urllib.request
if BASE_DIR.exists():
shutil.rmtree(BASE_DIR)
for m in [BASE_DIR / RAW_DIR, BASE_DIR / INBOX_DIR, BASE_DIR / ARCHIVE_DIR, BASE_DIR / DATELESS_DIR]:
m.mkdir(parents=True, exist_ok=True)
dump = BASE_DIR / RAW_DIR
foto_paden = []
for n in range(1, aantal + 1):
pad = dump / f"foto_{n:03d}.jpg"
url = f"https://picsum.photos/800/600?random={n}"
_log(f" Download {n}/{aantal}: {url}")
if progress_cb:
progress_cb(n, aantal, f"Foto {n} van {aantal} downloaden…")
urllib.request.urlretrieve(url, str(pad))
foto_paden.append(pad)
ts_start = datetime(2019, 1, 1).timestamp()
ts_eind = datetime(2025, 12, 31).timestamp()
t = random.uniform(ts_start, ts_eind)
os.utime(pad, (t, t))
# Duplicaten (±10% van aantal, minimaal 2)
n_dup = max(2, aantal // 10)
for i in range(min(n_dup, len(foto_paden))):
shutil.copy2(foto_paden[i], dump / f"dup_{i+1:03d}.jpg")
# 3 naamconflicten (als er genoeg fotos zijn)
if len(foto_paden) > 12:
for j in range(3):
shutil.copy2(foto_paden[10], dump / f"IMG_000{j+1}.jpg")
_log(f"Testdata aangemaakt: {aantal} foto's in {BASE_DIR}/")
# ── Stap 2: Pre-sorteren ──────────────────────────────────────────────────────
def presort(debug=False, progress_cb=None):
import time
bronmappen = [BASE_DIR / RAW_DIR]
uitzoeken = BASE_DIR / INBOX_DIR
alle_fotos = []
for bron in bronmappen:
if bron.exists():
alle_fotos.extend(zoek_fotos_recursief(bron))
totaal = len(alle_fotos)
if totaal == 0:
_log("Presort: geen foto's gevonden.")
if progress_cb:
progress_cb(0, 0, "Geen foto's gevonden.")
return
balk_breedte = 20
verplaatst = 0
overgeslagen = 0
start = time.time()
for i, foto in enumerate(alle_fotos, 1):
datum = lees_datum(foto, debug=debug)
doel_map = uitzoeken / datum.strftime("%Y-%m")
doel_map.mkdir(parents=True, exist_ok=True)
doel = doel_map / foto.name
was_conflict = doel.exists()
teller = 2
while doel.exists():
doel = doel_map / f"{foto.stem}_{teller}{foto.suffix}"
teller += 1
if was_conflict:
overgeslagen += 1
shutil.move(str(foto), doel)
verplaatst += 1
label = f"{doel.parent.name}/{doel.name}"
if progress_cb:
progress_cb(i, totaal, label)
else:
pct = i / totaal
gevuld = int(pct * balk_breedte)
balk = "█" * gevuld + "░" * (balk_breedte - gevuld)
print(f"\r[{balk}] {i}/{totaal} ({pct:.0%}) — {label:<40}", end="", flush=True)
duur = time.time() - start
if not progress_cb:
print(f"\n\n✓ {verplaatst} foto('s) verplaatst naar {uitzoeken}/")
print(f" Naamconflicten hernoemd : {overgeslagen}")
print(f" Tijd : {duur:.1f}s")
_log(f"[Presort] {verplaatst} verplaatst, {overgeslagen} hernoemd ({duur:.1f}s)")
# ── Systeemchecks ─────────────────────────────────────────────────────────────
def run_health_checks():
"""Voert systeemchecks uit. Geeft lijst van dicts terug met label_key, detail_key, status, value."""
import urllib.request as _ur
checks = []
def _dir_check(id_, label_key, path, need_write=False, optional=False):
p = Path(path) if not isinstance(path, Path) else path
if not p.exists():
return {"id": id_, "label_key": label_key, "value": str(p),
"status": "warn" if optional else "error",
"detail_key": "health_det_not_found"}
if not os.access(p, os.R_OK):
return {"id": id_, "label_key": label_key, "value": str(p),
"status": "warn" if optional else "error",
"detail_key": "health_det_no_read"}
if need_write and not os.access(p, os.W_OK):
return {"id": id_, "label_key": label_key, "value": str(p),
"status": "warn" if optional else "error",
"detail_key": "health_det_no_write"}
return {"id": id_, "label_key": label_key, "value": str(p),
"status": "ok", "detail_key": "health_det_ok"}
checks.append(_dir_check("base_dir", "health_check_base_dir", BASE_DIR))
checks.append(_dir_check("dump", "health_check_dump", BASE_DIR / RAW_DIR, optional=True))
checks.append(_dir_check("uitzoeken", "health_check_uitzoeken", BASE_DIR / INBOX_DIR, need_write=True))
checks.append(_dir_check("archief", "health_check_archief", BASE_DIR / ARCHIVE_DIR, need_write=True))
checks.append(_dir_check("datumloos", "health_check_datumloos", BASE_DIR / DATELESS_DIR, need_write=True))
checks.append(_dir_check("prullenbak", "health_check_prullenbak",BASE_DIR / TRASH_DIR,need_write=True))
checks.append(_dir_check("data_dir", "health_check_data_dir", DATA_DIR, need_write=True))
try:
import PIL
checks.append({"id": "pillow", "label_key": "health_check_pillow",
"value": f"v{PIL.__version__}", "status": "ok", "detail_key": "health_det_ok"})
except ImportError:
checks.append({"id": "pillow", "label_key": "health_check_pillow",
"value": "", "status": "error", "detail_key": "health_det_not_installed"})
try:
import pillow_heif # noqa: F401
checks.append({"id": "heic", "label_key": "health_check_heic",
"value": "", "status": "ok", "detail_key": "health_det_ok"})
except ImportError:
checks.append({"id": "heic", "label_key": "health_check_heic",
"value": "", "status": "warn", "detail_key": "health_det_optional"})
try:
import rawpy # noqa: F401
checks.append({"id": "raw", "label_key": "health_check_raw",
"value": "", "status": "ok", "detail_key": "health_det_ok"})
except ImportError:
checks.append({"id": "raw", "label_key": "health_check_raw",
"value": "", "status": "warn", "detail_key": "health_det_optional"})
if IMMICH_URL:
try:
headers = {}
if IMMICH_API_KEY:
headers["x-api-key"] = IMMICH_API_KEY
req = _ur.Request(f"{IMMICH_URL}/api/server-info", headers=headers)
_ur.urlopen(req, timeout=3)
checks.append({"id": "immich", "label_key": "health_check_immich",
"value": IMMICH_URL, "status": "ok", "detail_key": "health_det_reachable"})
except Exception:
checks.append({"id": "immich", "label_key": "health_check_immich",
"value": IMMICH_URL, "status": "warn", "detail_key": "health_det_unreachable"})
else:
checks.append({"id": "immich", "label_key": "health_check_immich",
"value": "", "status": "info", "detail_key": "health_det_not_configured"})
return checks
# ── Bestandstypen ─────────────────────────────────────────────────────────────
FOTO_EXTS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.heic', '.heif', '.arw'}
def zoek_fotos(map_pad: Path):
"""Alle ondersteunde fotobestanden in map_pad (case-insensitive), gesorteerd op mtime."""
bestanden = [
f for f in map_pad.iterdir()
if f.is_file() and f.suffix.lower() in FOTO_EXTS
]
return sorted(bestanden, key=lambda f: f.stat().st_mtime)
def zoek_fotos_recursief(map_pad: Path):
"""Alle ondersteunde fotobestanden recursief onder map_pad."""
return [
f for f in map_pad.rglob("*")
if f.is_file() and f.suffix.lower() in FOTO_EXTS
]
# ── Datum lezen + cache ────────────────────────────────────────────────────────
_datumcache: dict = {}
def _laad_datumcache():
global _datumcache
try:
_datumcache = json.loads(DATUMCACHE_FILE.read_text())
except Exception:
_datumcache = {}
def _sla_datumcache_op():
try:
DATUMCACHE_FILE.write_text(json.dumps(_datumcache))
except Exception:
pass
_laad_datumcache()
def lees_datum(pad: Path, debug=False) -> datetime:
"""Leest datum uit cache, dan EXIF, dan bestandsnaam, dan mtime."""
stat = pad.stat()
cache_key = f"{pad}|{int(stat.st_mtime)}|{stat.st_size}"
if cache_key in _datumcache:
try:
datum = datetime.strptime(_datumcache[cache_key][0], "%Y-%m-%d %H:%M:%S")
if debug:
print(f" [cache] {pad.name} → {datum:%Y-%m-%d} ({_datumcache[cache_key][1]})")
return datum
except Exception:
pass
datum, bron = _lees_datum_intern(pad)
_datumcache[cache_key] = [datum.strftime("%Y-%m-%d %H:%M:%S"), bron]
_sla_datumcache_op()
if debug:
print(f" [{bron:<12}] {pad.name} → {datum:%Y-%m-%d}")
return datum
def _lees_datum_intern(pad: Path):
"""Geeft (datetime, bron_label). Volgorde: EXIF → bestandsnaam → mtime."""
import re
# 1-3: EXIF
try:
from PIL import Image
img = Image.open(pad)
exif = img.getexif()
labels = {36867: "EXIF-origineel", 36868: "EXIF-digitized", 306: "EXIF-datetime"}
for tag, label in labels.items():
raw = exif.get(tag)
if raw:
try:
return datetime.strptime(raw.strip(), "%Y:%m:%d %H:%M:%S"), label
except ValueError:
continue
except Exception:
pass
# 4: Datum uit bestandsnaam
naam = pad.stem
patronen = [
(r"IMG_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})", "naam-android"),
(r"IMG-(\d{4})(\d{2})(\d{2})-WA", "naam-whatsapp"),
(r"(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})", "naam-datetime"),
(r"(\d{4})-(\d{2})-(\d{2}) (\d{2})\.(\d{2})\.(\d{2})","naam-dots"),
(r"(\d{4})-(\d{2})-(\d{2})", "naam-datum"),
(r"(\d{4})_(\d{2})_(\d{2})", "naam-underscore"),
]
for patroon, label in patronen:
m = re.search(patroon, naam)
if m:
g = m.groups()
try:
if len(g) >= 6:
return datetime(int(g[0]), int(g[1]), int(g[2]),
int(g[3]), int(g[4]), int(g[5])), label
else:
return datetime(int(g[0]), int(g[1]), int(g[2])), label
except ValueError:
continue
# 5: mtime
return datetime.fromtimestamp(pad.stat().st_mtime), "mtime"
# ── Recents ───────────────────────────────────────────────────────────────────
def laad_recents():
try:
return json.loads(RECENTS_FILE.read_text())
except Exception:
return []
def sla_recent_op(album):
recents = laad_recents()
if album in recents:
recents.remove(album)
recents.insert(0, album)
recents = recents[:10]
RECENTS_FILE.write_text(json.dumps(recents))
return recents
# ── Stap 3–5: Webapp ──────────────────────────────────────────────────────────
def start_server():
import base64
import json as _json
import socket
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
uitzoeken = BASE_DIR / INBOX_DIR
archief = BASE_DIR / ARCHIVE_DIR
try:
from PIL import Image
import io as _io
HAS_PILLOW = True
except ImportError:
HAS_PILLOW = False
import warnings as _warnings
try:
with _warnings.catch_warnings():
_warnings.simplefilter("ignore")
import rawpy as _rawpy
HAS_RAWPY = True
except ImportError:
HAS_RAWPY = False
thumbcache = THUMBCACHE_DIR
thumbcache.mkdir(parents=True, exist_ok=True)
_geo_cache: dict = {}
def _lees_gps(pad: Path):
if not HAS_PILLOW:
return None
try:
from PIL.ExifTags import TAGS, GPSTAGS
img = Image.open(pad)
try:
exif_raw = img._getexif() or {}
except Exception:
exif_raw = {}
gps_raw = None
for tag_id, val in exif_raw.items():
if TAGS.get(tag_id) == 'GPSInfo':
gps_raw = val
break
if not gps_raw:
return None
gps = {GPSTAGS.get(k, k): v for k, v in gps_raw.items()}
def _to_dec(coords, ref):
d, m, s = [float(x) for x in coords]
dd = d + m / 60 + s / 3600
if ref in ('S', 'W'):
dd = -dd
return round(dd, 6)
lat = _to_dec(gps['GPSLatitude'], gps.get('GPSLatitudeRef', 'N'))
lng = _to_dec(gps['GPSLongitude'], gps.get('GPSLongitudeRef', 'E'))
return {'lat': lat, 'lng': lng}
except Exception:
return None
def _reverse_geocode(lat: float, lng: float):
key = f"{lat:.3f},{lng:.3f}"
if key in _geo_cache:
return _geo_cache[key]
try:
import urllib.request as _ur, json as _j
url = f"https://nominatim.openstreetmap.org/reverse?lat={lat}&lon={lng}&format=json&accept-language=nl"
req = _ur.Request(url, headers={'User-Agent': 'Declutter/1.0'})
data = _j.loads(_ur.urlopen(req, timeout=4).read())
addr = data.get('address', {})
city = (addr.get('city') or addr.get('town') or
addr.get('village') or addr.get('municipality') or '')
country = addr.get('country', '')
result = ', '.join(x for x in [city, country] if x) or None
_geo_cache[key] = result
return result
except Exception:
return None
import queue as _queue
_sse_queues = []
_sse_lock = threading.Lock()
def _push_sse(msg):
with _sse_lock:
dood = []
for q in _sse_queues:
try: q.put_nowait(msg)
except Exception: dood.append(q)
for q in dood:
try: _sse_queues.remove(q)
except ValueError: pass
def _auto_presort(pad):
datum = lees_datum(pad)
doel_map = (BASE_DIR / INBOX_DIR) / datum.strftime("%Y-%m")
doel_map.mkdir(parents=True, exist_ok=True)
doel = doel_map / pad.name
teller = 2
while doel.exists():
doel = doel_map / f"{pad.stem}_{teller}{pad.suffix}"
teller += 1
shutil.move(str(pad), doel)
_log(f"[Watcher] {pad.name} \u2192 {doel.parent.name}/")
return doel
_watcher_pauze = [False] # mutable flag: True = watcher slaat scan over
def _watcher():
import time, re as _re
bronmappen = [BASE_DIR / RAW_DIR]
uits = BASE_DIR / INBOX_DIR
datumloos_pad = BASE_DIR / DATELESS_DIR
def scan():
gevonden = set()
for bron in bronmappen:
if bron.exists():
for f in bron.rglob("*"):
if f.is_file() and f.suffix.lower() in FOTO_EXTS:
gevonden.add(str(f))
if uits.exists():
for sub in uits.iterdir():
if not sub.is_dir(): continue
if _re.match(r'^\d{4}-\d{2}$', sub.name):
for f in sub.iterdir():
if f.is_file() and f.suffix.lower() in FOTO_EXTS:
gevonden.add(str(f))
else:
for f in sub.rglob("*"):
if f.is_file() and f.suffix.lower() in FOTO_EXTS:
gevonden.add(str(f))
return gevonden
bekende = scan()
while True:
time.sleep(5)
if _watcher_pauze[0]:
bekende = set() # reset bekende zodat na pauze alles als nieuw geldt
continue
try:
huidige = scan()
nieuw = huidige - bekende
if nieuw:
verplaatste = []
for pad_str in sorted(nieuw):
pad = Path(pad_str)
# Datumloos-map nooit pre-sorten
in_datumloos = datumloos_pad.exists() and pad.is_relative_to(datumloos_pad)
moet_presorten = not in_datumloos and any(
pad.is_relative_to(b) for b in bronmappen if b.exists()
)
if not moet_presorten and not in_datumloos and uits.exists():
try:
if pad.is_relative_to(uits):
rel = pad.relative_to(uits)
top = rel.parts[0] if rel.parts else ''
if not _re.match(r'^\d{4}-\d{2}$', top):
moet_presorten = True
except Exception:
pass
if moet_presorten:
try:
doel = _auto_presort(pad)
try:
verplaatste.append({
"naam": pad.name,
"van": str(pad.relative_to(BASE_DIR)),
"naar": str(doel.relative_to(BASE_DIR)),
})
except Exception:
pass
except Exception as e:
_log(f"[Watcher] Presort fout {pad.name}: {e}")
else:
try:
verplaatste.append({
"naam": pad.name,
"van": None,
"naar": str(pad.relative_to(BASE_DIR)),
})
except Exception:
pass
bekende = scan()
_push_sse(_json.dumps({"type": "update", "bestanden": verplaatste, "jm": jaren_maanden()}))
else:
bekende = huidige
except Exception as e:
_log(f"[Watcher] Scanfout: {e}")
threading.Thread(target=_watcher, daemon=True).start()
def get_thumbnail(pad: Path) -> bytes:
stat = pad.stat()
cache_key = f"{pad.name}_{int(stat.st_mtime)}_{stat.st_size}.jpg"
cache_pad = thumbcache / cache_key
if cache_pad.exists():
return cache_pad.read_bytes()
ext = pad.suffix.lower()
# ARW (Sony RAW): probeer ingebedde JPEG-preview te extraheren
if ext == '.arw':
img = None
if HAS_RAWPY:
try:
import io as _io
with _rawpy.imread(str(pad)) as raw:
thumb = raw.extract_thumb()
if thumb.format.name == 'JPEG':
img = Image.open(_io.BytesIO(thumb.data))
elif thumb.format.name == 'BITMAP':
img = Image.fromarray(thumb.data)
except Exception:
pass
if img is None:
data = _maak_placeholder(pad.name)
cache_pad.write_bytes(data)
return data
# Gevallen door naar Pillow resize hieronder
# HEIC/HEIF: probeer via pillow-heif of pyheif
elif ext in ('.heic', '.heif'):
img = None
try:
import pillow_heif
pillow_heif.register_heif_opener()
img = Image.open(pad)
except ImportError:
pass
if img is None:
try:
import pyheif
import io as _io
heif = pyheif.read(pad)
img = Image.frombytes(heif.mode, heif.size, heif.data)
except ImportError:
pass
if img is None:
data = _maak_placeholder(pad.name)
cache_pad.write_bytes(data)
return data
# Gevallen door naar Pillow resize hieronder
else:
img = None # gewone formaten: Pillow opent ze zelf hieronder
if HAS_PILLOW:
try:
import io as _io
if img is None:
img = Image.open(pad)
from PIL import ImageOps
img = ImageOps.exif_transpose(img)
img = img.convert("RGB")
img.thumbnail((400, 400))
buf = _io.BytesIO()
img.save(buf, format="JPEG", quality=70)
data = buf.getvalue()
cache_pad.write_bytes(data)
return data
except Exception:
pass
# Fallback: ruwe bytes (alleen zinvol voor echte JPEG)
data = pad.read_bytes()
cache_pad.write_bytes(data)
return data
def _maak_placeholder(naam: str) -> bytes:
"""Grijs placeholder JPEG met bestandsextensie als label."""
import io as _io
ext = Path(naam).suffix.upper().lstrip('.')
if HAS_PILLOW:
try:
from PIL import ImageDraw, ImageFont
img = Image.new("RGB", (200, 200), color=(60, 60, 60))
draw = ImageDraw.Draw(img)
draw.text((100, 90), ext, fill=(180, 180, 180), anchor="mm")
draw.text((100, 115), naam[:20], fill=(120, 120, 120), anchor="mm")
buf = _io.BytesIO()
img.save(buf, format="JPEG", quality=70)
return buf.getvalue()
except Exception:
pass
# Ultra-minimaal grijs JPEG (1x1 pixel, grijs)
return bytes([
0xFF,0xD8,0xFF,0xE0,0x00,0x10,0x4A,0x46,0x49,0x46,0x00,0x01,
0x01,0x00,0x00,0x01,0x00,0x01,0x00,0x00,0xFF,0xDB,0x00,0x43,
0x00,0x08,0x06,0x06,0x07,0x06,0x05,0x08,0x07,0x07,0x07,0x09,
0x09,0x08,0x0A,0x0C,0x14,0x0D,0x0C,0x0B,0x0B,0x0C,0x19,0x12,
0x13,0x0F,0x14,0x1D,0x1A,0x1F,0x1E,0x1D,0x1A,0x1C,0x1C,0x20,
0x24,0x2E,0x27,0x20,0x22,0x2C,0x23,0x1C,0x1C,0x28,0x37,0x29,
0x2C,0x30,0x31,0x34,0x34,0x34,0x1F,0x27,0x39,0x3D,0x38,0x32,
0x3C,0x2E,0x33,0x34,0x32,0xFF,0xC0,0x00,0x0B,0x08,0x00,0x01,
0x00,0x01,0x01,0x01,0x11,0x00,0xFF,0xC4,0x00,0x1F,0x00,0x00,
0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x09,0x0A,0x0B,0xFF,0xC4,0x00,0xB5,0x10,0x00,0x02,0x01,0x03,
0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,0x00,0x01,0x7D,
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,
0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,
0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24,0x33,0x62,0x72,
0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,
0x29,0x2A,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,
0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,
0x76,0x77,0x78,0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,
0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,
0xB7,0xB8,0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,
0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xE1,0xE2,
0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,
0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFF,0xDA,0x00,0x08,0x01,0x01,
0x00,0x00,0x3F,0x00,0xFB,0xD3,0xFF,0xD9
])
def jaren_maanden():
"""Geeft dict {jaar: [{naam, aantal}, ...]} van aanwezige submappen."""
result = {}
if not uitzoeken.exists():
return result
for submap in sorted(uitzoeken.iterdir()):
if not submap.is_dir():
continue
try:
jaar, _ = submap.name.split("-")
n = sum(1 for f in submap.iterdir()
if f.is_file() and f.suffix.lower() in FOTO_EXTS)
result.setdefault(jaar, []).append({"naam": submap.name, "aantal": n})
except ValueError:
pass
return result
# Systeem-/NAS-bestanden die een "lege" map toch niet-leeg maken
_SYS_NAMEN = {'desktop.ini', 'thumbs.db', '.ds_store', '@eadir', '#recycle'}
def _heeft_echte_inhoud(pad):
"""True als pad echte bestanden/mappen bevat (geen NAS/OS-systeembestanden)."""
for f in pad.iterdir():
if f.name.startswith('.') or f.name.startswith('@'):
continue
if f.name.lower() in _SYS_NAMEN:
continue
return True
return False
def verwijder_lege_mappen():
"""Verwijdert lege YYYY-MM submappen uit in_behandeling."""
import re
if uitzoeken.exists():
for sub in list(uitzoeken.iterdir()):
if sub.is_dir() and re.match(r'^\d{4}-\d{2}$', sub.name):
if not _heeft_echte_inhoud(sub):
try:
shutil.rmtree(sub)
_log(f"[Opruimen] Lege map verwijderd: {sub.name}")
except OSError:
pass
def fotos_in_map(maand_key):
"""Geeft lijst van foto-paden gesorteerd op mtime."""
pad = uitzoeken / maand_key
if not pad.exists():
return []
return zoek_fotos(pad)
def burst_groepen(fotos):
"""Groepeert foto's. Geeft lijst van dicts met 'fotos' en 'type'.
type: 'tight' (≤30s), 'moment' (31-300s), 'los' (>300s of enkelvoudig)."""
if not fotos:
return []
# Groepeer op 300s venster
ruw = []
huidige = [fotos[0]]
for foto in fotos[1:]:
dt = abs(foto.stat().st_mtime - huidige[-1].stat().st_mtime)
if dt <= 300:
huidige.append(foto)
else:
ruw.append(huidige)
huidige = [foto]
ruw.append(huidige)
# Bepaal type per groep
result = []
for groep in ruw:
if len(groep) < 2:
type_ = "los"
span_sec = 0
else:
mtimes = [f.stat().st_mtime for f in groep]
max_gap = max(abs(mtimes[i+1] - mtimes[i]) for i in range(len(mtimes)-1))
type_ = "tight" if max_gap <= 30 else "moment"
span_sec = int(max(mtimes) - min(mtimes))
result.append({"fotos": groep, "type": type_, "span_sec": span_sec})
return result
def uniek_doel(doel_map: Path, naam: str) -> Path:
doel = doel_map / naam
teller = 2
stem = Path(naam).stem
suffix = Path(naam).suffix
while doel.exists():
doel = doel_map / f"{stem}_{teller}{suffix}"
teller += 1
return doel
_immich_timer = None
_immich_lib_id = None # gecached library ID
def _immich_haal_lib_id():
"""Haalt het eerste library ID op via GET /api/libraries. Cachet in geheugen."""
nonlocal _immich_lib_id
if _immich_lib_id:
return _immich_lib_id
try:
import urllib.request, json as _j
req = urllib.request.Request(
f"{IMMICH_URL.rstrip('/')}/api/libraries",
headers={"x-api-key": IMMICH_API_KEY} if IMMICH_API_KEY else {},
)
with urllib.request.urlopen(req, timeout=5) as resp:
libs = _j.loads(resp.read())
if libs:
_immich_lib_id = libs[0]["id"]
return _immich_lib_id
except Exception as e:
_log(f"[Immich] Library ID ophalen mislukt: {e}")
return None
def _doe_rescan():
lib_id = _immich_haal_lib_id()
if not lib_id:
_log("[Immich] Geen library ID — rescan overgeslagen.")
return
try:
import urllib.request
req = urllib.request.Request(
f"{IMMICH_URL.rstrip('/')}/api/libraries/{lib_id}/scan",
data=b"{}",
method="POST",
headers={
"Content-Type": "application/json",
**({"x-api-key": IMMICH_API_KEY} if IMMICH_API_KEY else {}),
},
)
urllib.request.urlopen(req, timeout=10)
_log("[Immich] Rescan getriggerd.")
except Exception as e:
_log(f"[Immich] Rescan mislukt: {e}")
def immich_rescan():
nonlocal _immich_timer
if not IMMICH_URL:
return
if _immich_timer is not None:
_immich_timer.cancel()
_log("[Immich] Rescan gepland over 3600s...")
_immich_timer = threading.Timer(3600, _doe_rescan)
_immich_timer.daemon = True
_immich_timer.start()
def render_hoofdpagina():
return f"""<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Declutter</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='6' fill='%231a1a1a'/%3E%3Crect x='3' y='10' width='26' height='17' rx='3' fill='%232a6a9a'/%3E%3Cpath d='M11 10 L13 6 H19 L21 10Z' fill='%232a6a9a'/%3E%3Ccircle cx='16' cy='18.5' r='5' fill='%230d0d0d'/%3E%3Ccircle cx='16' cy='18.5' r='3.5' fill='%234a9abf'/%3E%3Ccircle cx='16' cy='18.5' r='1.5' fill='%23c8eef8'/%3E%3Ccircle cx='24.5' cy='13.5' r='1.5' fill='%23ffc107'/%3E%3C/svg%3E">
<style>
:root{{--foto-breedte:220px;--left-w:240px;--right-w:210px}}
*{{box-sizing:border-box}}
body{{font-family:sans-serif,'Apple Color Emoji','Segoe UI Emoji','Noto Color Emoji';margin:0;background:#1a1a1a;color:#eee;overflow-x:hidden}}
/* ── Toolbar ── */
.toolbar{{position:sticky;top:0;background:#111;padding:.5rem .8rem;display:flex;align-items:center;z-index:20;border-bottom:1px solid #333}}
.toolbar h1{{margin:0;font-size:1rem;white-space:nowrap;color:#f90;letter-spacing:.04em}}
input[type=text]{{width:100%;padding:.35rem .6rem;background:#222;border:1px solid #444;color:#eee;border-radius:4px;font-size:.85rem}}
.album-staat{{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:8px;height:8px;border-radius:50%;display:none}}
.album-staat.groen{{background:#4c4;display:block}}
.album-staat.oranje{{background:#f80;display:block}}
.album-staat.rood{{background:#c44;display:block}}
button{{padding:.35rem .7rem;border:none;border-radius:4px;cursor:pointer;font-size:.82rem}}
.btn-reset{{background:#c33;color:#fff}}
.btn-alles{{background:#383838;color:#ccc}}
.btn-presort{{background:#1e4a1e;color:#8f8;border:1px solid #2d6a2d}}
.btn-opruim{{background:#1a2a3a;color:#7af;border:1px solid #2a4a6a}}
.btn-cache{{background:#3a2a00;color:#f80;border:1px solid #5a4000}}
.btn-later{{background:#1e1e3a;color:#aaf;border:1px solid #336}}
.btn-verwijder{{background:#5a1010;color:#faa;border:1px solid #8a2020}}
.btn-verwijder:disabled{{background:#2a1a1a;color:#664;border-color:#3a1a1a;cursor:default}}
/* Prullenbak: geen acties beschikbaar */
.prullenbak-modus .foto-del{{display:none!important}}
.prullenbak-modus .foto-zoom{{display:none!important}}
.prullenbak-modus .foto{{cursor:default}}
/* Prullenbak tree: geen hover-acties */
.boom-rij.pb-readonly{{cursor:default}}
.boom-rij.pb-readonly .boom-rij-acties{{display:none!important}}
#status{{font-size:.72rem;color:#8f8;padding:.25rem .7rem;background:#111;border-top:1px solid #1e1e1e;flex-shrink:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}
/* ── 3-koloms layout ── */
html,body{{height:100%;overflow:hidden}}
body{{display:flex;flex-direction:column}}
#progress-wrap{{height:4px;flex-shrink:0;overflow:hidden}}
#progress{{height:4px;background:#4a8abf;transition:width .1s;width:0%}}
@keyframes laden-sweep{{0%{{transform:translateX(-100%)}}100%{{transform:translateX(400%)}}}}
#progress-wrap.laden #progress{{width:25%;animation:laden-sweep 1.1s ease-in-out infinite;transition:none}}
.fotos-laden{{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:3rem 1rem;gap:.8rem;color:#555}}
.fotos-laden-spinner{{width:28px;height:28px;border:3px solid #333;border-top-color:#4a8abf;border-radius:50%;animation:laden-sweep-spin .8s linear infinite}}
@keyframes laden-sweep-spin{{to{{transform:rotate(360deg)}}}}
#main-wrap{{flex:1;display:flex;min-height:0;overflow:hidden;flex-direction:column}}
#cols-wrap{{flex:1;display:flex;min-height:0;overflow:hidden}}
/* ── Linkerpaneel (treeview) ── */
#left-panel{{width:var(--left-w);flex-shrink:0;background:#141414;overflow-y:auto;display:flex;flex-direction:column}}
#left-resizer{{width:5px;flex-shrink:0;cursor:col-resize;background:#2a2a2a;transition:background .1s;z-index:10}}
#left-resizer:hover,#left-resizer.dragging{{background:#4a8abf}}
.ts-hdr{{display:flex;align-items:center;gap:.3rem;padding:.35rem .6rem;font-size:.75rem;font-weight:bold;color:#888;cursor:pointer;user-select:none;border-bottom:1px solid #222;background:#111}}
.ts-hdr:hover{{color:#bbb}}
.ts-pijl{{font-size:.55rem;transition:transform .15s;display:inline-block;width:10px;text-align:center}}
.ts-hdr.open .ts-pijl{{transform:rotate(90deg)}}
.ts-body{{display:none;padding:.2rem 0}}
.ts-body.open{{display:block}}
/* Tree nodes */
.boom-rij{{display:flex;align-items:center;gap:.25rem;padding:2px 0 2px 8px;cursor:pointer;border-radius:3px;margin:0 3px}}
.boom-rij:hover{{background:#1e1e1e}}
.boom-pijl{{width:12px;font-size:.5rem;color:#555;flex-shrink:0;text-align:center;user-select:none}}
.boom-naam{{font-size:.75rem;color:#9bc;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}}
.boom-count{{color:#555;font-size:.68rem;font-weight:normal}}
.boom-naam:hover{{color:#ddf}}
.boom-naam.actief{{color:#f90;font-weight:bold}}
.boom-sub{{display:none}}
.maand-rij{{display:flex;align-items:center;gap:.25rem;padding:2px 0 2px 20px;cursor:pointer;border-radius:3px;margin:0 3px}}
.maand-rij:hover{{background:#1e1e1e}}
.maand-rij span{{font-size:.73rem;color:#9bc}}
.maand-rij.actief span{{color:#f90;font-weight:bold}}
.jaar-rij{{display:flex;align-items:center;gap:.25rem;padding:.25rem .6rem;cursor:pointer;user-select:none}}
.jaar-rij:hover .jaar-label{{color:#eee}}
.jaar-label{{font-size:.72rem;font-weight:bold;color:#666}}
.jaar-pijl{{font-size:.5rem;color:#444;width:10px;text-align:center}}
.jaar-sub{{display:none;padding:.1rem 0}}
/* Activiteitlog in linkerpaneel */
#ts-activiteit .act-rij{{font-size:.68rem;padding:.2rem .6rem;border-bottom:1px solid #1e1e1e;line-height:1.4}}
#ts-activiteit .act-rij .act-ts{{color:#444}}
#ts-activiteit .act-rij .act-naam{{color:#ccc;font-weight:bold}}
#ts-activiteit .act-rij .act-naar{{color:#4a8a4a}}
/* ── Middenpaneel (foto's) ── */
#fotos-wrap{{flex:1;min-width:0;overflow:hidden;display:flex;flex-direction:column}}
#thumb-toolbar{{display:flex;align-items:center;gap:.5rem;padding:.35rem .7rem;background:#111;border-bottom:1px solid #222;font-size:.72rem;color:#666;flex-shrink:0;position:sticky;top:0;z-index:5}}
#thumb-toolbar input[type=range]{{width:90px;accent-color:#4a8abf;cursor:pointer}}
#fotos{{flex:1;padding:.75rem;min-width:0;overflow-y:auto}}
/* ── Rechterpaneel (selectie) ── */
#sidebar{{width:var(--right-w);flex-shrink:0;background:#111;border-left:1px solid #2a2a2a;overflow-y:auto;padding:.6rem}}
#sidebar h3{{margin:0 0 .4rem;font-size:.78rem;color:#888;text-transform:uppercase;letter-spacing:.05em}}
.sb-item{{display:flex;align-items:center;gap:.35rem;margin-bottom:.35rem;background:#1a1a1a;border-radius:4px;padding:3px 4px}}
.sb-thumb{{width:34px;height:34px;object-fit:cover;border-radius:3px;flex-shrink:0}}
.sb-naam{{font-size:.62rem;color:#bbb;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
.sb-x{{background:none;border:none;color:#c66;cursor:pointer;font-size:.85rem;padding:0 2px;flex-shrink:0}}
.sb-leeg{{font-size:.72rem;color:#444}}
/* ── Foto-grid ── */
.grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(var(--foto-breedte),1fr));gap:8px}}
.dag-header{{font-size:.88rem;font-weight:bold;color:#bbb;padding:.5rem 0 .25rem;border-bottom:1px solid #2a2a2a;margin-bottom:.1rem;grid-column:1/-1}}
.bladwijzer{{display:flex;align-items:center;gap:.5rem;margin:.5rem 0;color:#c44;font-size:.72rem;font-style:italic}}
.bladwijzer::before{{content:'';flex:0 0 10px;height:10px;background:#c44;border-radius:50%}}
.bladwijzer::after{{content:'';flex:1;height:1px;background:#c44}}
.burst{{border-radius:6px;padding:5px;margin-bottom:6px}}
.burst.tight{{background:#2d2010}}
.burst.moment{{background:#1a1a2d}}
.burst-label{{font-size:.67rem;margin-bottom:3px;cursor:pointer;display:inline-block;padding:2px 5px;border-radius:4px}}
.burst-label:hover{{opacity:.8}}
.burst.tight .burst-label{{color:#c8860a}}
.burst.moment .burst-label{{color:#7788cc}}
/* ── Lightbox ── */
#lb{{display:none;position:fixed;inset:0;background:rgba(0,0,0,.93);z-index:100;flex-direction:column;align-items:center;justify-content:center}}
#lb-inner{{display:flex;flex-direction:column;width:100%;max-width:1200px;height:100vh;padding:1rem;gap:.75rem;box-sizing:border-box}}
#lb-header{{display:flex;justify-content:space-between;align-items:center;color:#aaa;font-size:.82rem}}
#lb-teller{{color:#eee;font-weight:bold}}
#lb-fotos{{display:flex;gap:1rem;flex:1;min-height:0}}
.lb-foto-wrap{{flex:1;display:flex;flex-direction:column;gap:.4rem;min-width:0}}
.lb-foto-wrap img{{width:100%;height:calc(100% - 56px);object-fit:contain;border-radius:6px;border:3px solid transparent;cursor:pointer}}
.lb-foto-wrap img.met-hart{{border-color:#e33}}
.lb-foto-info{{font-size:.7rem;color:#aaa;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.3rem}}
.lb-hart{{background:none;border:2px solid #555;border-radius:50%;width:34px;height:34px;font-size:1rem;cursor:pointer;color:#aaa;flex-shrink:0;display:flex;align-items:center;justify-content:center;line-height:1}}
.lb-hart.actief{{border-color:#e33;color:#e33}}
#lb-nav{{display:flex;align-items:center;justify-content:center;gap:1rem}}