-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkgrid.py
More file actions
2010 lines (1794 loc) · 70.2 KB
/
Copy pathworkgrid.py
File metadata and controls
2010 lines (1794 loc) · 70.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""workgrid — local browser-based media library viewer/organizer.
Server: multi-source scanner + config, HTTP (127.0.0.1 only) with Range
streaming, thumbnail pipeline, metadata, file ops. UI lives in static/.
Usage: python workgrid.py [folder ...] [--port N] [--no-browser]
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import webbrowser
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import unquote, urlparse, parse_qs
# ---- optional dependencies (degrade gracefully) ---------------------------
try:
from PIL import Image, ImageOps
from PIL.ExifTags import TAGS as EXIF_TAGS, GPSTAGS
# local trusted files; portfolio renders can exceed the default
# decompression-bomb threshold (~179 MP)
Image.MAX_IMAGE_PIXELS = None
HAVE_PIL = True
except ImportError:
HAVE_PIL = False
print("[workgrid] Pillow not installed — no image thumbnails/EXIF",
file=sys.stderr)
try:
import pillow_heif
pillow_heif.register_heif_opener()
HAVE_HEIF = True
except ImportError:
HAVE_HEIF = False
try:
import imageio_ffmpeg
FFMPEG = imageio_ffmpeg.get_ffmpeg_exe()
except ImportError:
FFMPEG = shutil.which("ffmpeg")
if not FFMPEG:
print("[workgrid] no ffmpeg — no video thumbnails/metadata",
file=sys.stderr)
try:
from send2trash import send2trash
HAVE_TRASH = True
except ImportError:
HAVE_TRASH = False
# ---------------------------------------------------------------- constants
IMAGE_EXTS = {"jpg", "jpeg", "png", "gif", "webp", "bmp", "tif", "tiff",
"svg", "avif", "heic", "heif", "jfif", "ico"}
VIDEO_EXTS = {"mp4", "webm", "mov", "m4v", "mkv", "avi", "ogv", "mpg",
"mpeg", "wmv", "3gp"}
SKIP_DIRS = {"$recycle.bin", "node_modules", "system volume information",
".workgrid-thumbs"}
MIME_TYPES = {
"jpg": "image/jpeg", "jpeg": "image/jpeg", "jfif": "image/jpeg",
"png": "image/png", "gif": "image/gif", "webp": "image/webp",
"bmp": "image/bmp", "tif": "image/tiff", "tiff": "image/tiff",
"svg": "image/svg+xml", "avif": "image/avif", "heic": "image/heic",
"heif": "image/heif", "ico": "image/x-icon",
"mp4": "video/mp4", "m4v": "video/mp4", "webm": "video/webm",
"mov": "video/quicktime", "mkv": "video/x-matroska",
"avi": "video/x-msvideo", "ogv": "video/ogg", "mpg": "video/mpeg",
"mpeg": "video/mpeg", "wmv": "video/x-ms-wmv", "3gp": "video/3gpp",
"html": "text/html; charset=utf-8", "css": "text/css; charset=utf-8",
"js": "text/javascript; charset=utf-8", "json": "application/json",
"woff2": "font/woff2",
}
CHUNK = 64 * 1024
THUMB_SIZE = 320
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"static")
def app_data_dir():
if sys.platform == "win32":
base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~"))
else:
base = os.environ.get("XDG_DATA_HOME",
os.path.expanduser("~/.local/share"))
d = os.path.join(base, "workgrid")
os.makedirs(d, exist_ok=True)
return d
APP_DATA = app_data_dir()
CONFIG_PATH = os.path.join(APP_DATA, "config.json")
THUMB_DIR = os.path.join(APP_DATA, "thumbs")
os.makedirs(THUMB_DIR, exist_ok=True)
# ------------------------------------------------------------------- config
_config_lock = threading.Lock()
def load_config():
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return {}
def save_config_patch(**patch):
with _config_lock:
cfg = load_config()
cfg.update(patch)
try:
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2)
except OSError as e:
print(f"[workgrid] could not save config: {e}", file=sys.stderr)
# ------------------------------------------------------------ json stores
class JsonStore:
"""Small thread-safe JSON file store (media meta, annotations, ...)."""
def __init__(self, filename):
self.path = os.path.join(APP_DATA, filename)
self.lock = threading.Lock()
try:
with open(self.path, "r", encoding="utf-8") as f:
self.data = json.load(f)
except (OSError, ValueError):
self.data = {}
self._dirty = False
def get(self, key, default=None):
with self.lock:
return self.data.get(key, default)
def set(self, key, value):
with self.lock:
self.data[key] = value
self._dirty = True
def update(self, key, patch):
with self.lock:
cur = self.data.get(key) or {}
cur.update(patch)
self.data[key] = cur
self._dirty = True
def delete(self, key):
with self.lock:
if key in self.data:
del self.data[key]
self._dirty = True
def rename_key(self, old, new):
with self.lock:
if old in self.data:
self.data[new] = self.data.pop(old)
self._dirty = True
def save(self, force=False):
with self.lock:
if not self._dirty and not force:
return
try:
tmp = self.path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(self.data, f)
os.replace(tmp, self.path)
self._dirty = False
except OSError as e:
print(f"[workgrid] save {self.path}: {e}", file=sys.stderr)
MEDIA_META = JsonStore("media-meta.json") # thumb key -> {duration,w,h,...}
ANNOTATIONS = JsonStore("annotations.json") # "sid/rel" -> {rating,label,tags}
# ------------------------------------------------------------------ library
class Library:
"""Registered sources + scanned items. Scans run per-source in threads."""
def __init__(self):
self.lock = threading.Lock()
self.sources = [] # [{id, path, name}]
self.items = {} # source id -> [item, ...]
self.scanning = {} # source id -> bool
self.version = 0 # bumped on any library change
@staticmethod
def source_id(path):
real = os.path.realpath(path)
return hashlib.md5(real.lower().encode("utf-8")).hexdigest()[:8]
def bump(self):
with self.lock:
self.version += 1
def add_source(self, path):
real = os.path.realpath(path)
if not os.path.isdir(real):
return None
sid = self.source_id(real)
with self.lock:
if any(s["id"] == sid for s in self.sources):
return sid
self.sources.append({"id": sid, "path": real,
"name": os.path.basename(real) or real})
self.version += 1
self.scan_async(sid)
return sid
def remove_source(self, sid):
with self.lock:
self.sources = [s for s in self.sources if s["id"] != sid]
self.items.pop(sid, None)
self.scanning.pop(sid, None)
self.version += 1
with _thumb_dir_lock:
_thumb_dir_cache.pop(sid, None)
def get_source(self, sid):
with self.lock:
for s in self.sources:
if s["id"] == sid:
return dict(s)
return None
def scan_async(self, sid=None):
with self.lock:
targets = [dict(s) for s in self.sources
if sid is None or s["id"] == sid]
for src in targets:
threading.Thread(target=self._scan_source, args=(src,),
daemon=True).start()
def _scan_source(self, src):
sid = src["id"]
with self.lock:
self.scanning[sid] = True
found = []
root = src["path"]
try:
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames
if not d.startswith(".")
and d.lower() not in SKIP_DIRS]
for fn in filenames:
if fn.startswith("."):
continue
ext = os.path.splitext(fn)[1].lstrip(".").lower()
if ext in IMAGE_EXTS:
kind = "image"
elif ext in VIDEO_EXTS:
kind = "video"
else:
continue
full = os.path.join(dirpath, fn)
try:
st = os.stat(full)
except OSError:
continue
rel = os.path.relpath(full, root).replace(os.sep, "/")
found.append({
"source": sid,
"name": fn,
"rel": rel,
"folder": os.path.dirname(rel),
"type": kind,
"format": ext,
"size": st.st_size,
"modified": int(st.st_mtime),
})
except OSError as e:
print(f"[workgrid] scan error for {root}: {e}", file=sys.stderr)
with self.lock:
if any(s["id"] == sid for s in self.sources):
self.items[sid] = found
self.scanning[sid] = False
self.version += 1
THUMBS.enqueue_items(found)
def all_items(self):
with self.lock:
return [it for sid in self.items for it in self.items[sid]]
def find_item(self, sid, rel):
with self.lock:
for it in self.items.get(sid, []):
if it["rel"] == rel:
return dict(it)
return None
def snapshot(self):
with self.lock:
items = [dict(it) for sid in self.items
for it in self.items[sid]]
sources = [dict(s) for s in self.sources]
scanning = any(self.scanning.values())
version = self.version
# enrich with cached thumb/meta info + sidecar annotations
for it in items:
key = thumb_key(it)
it["thumb"] = find_thumb(it, key) is not None
meta = MEDIA_META.get(key)
if meta:
for k in ("duration", "width", "height"):
if meta.get(k) is not None:
it[k] = meta[k]
ann = ANNOTATIONS.get(f'{it["source"]}/{it["rel"]}')
if ann:
if ann.get("rating"):
it["rating"] = ann["rating"]
if ann.get("label"):
it["label"] = ann["label"]
if ann.get("tags"):
it["tags"] = ann["tags"]
if ann.get("autotags"):
it["autotags"] = ann["autotags"]
return {
"sources": sources,
"items": items,
"scanning": scanning,
"version": version,
"thumbs": THUMBS.progress(),
"capabilities": {
"pil": HAVE_PIL, "heif": HAVE_HEIF,
"ffmpeg": bool(FFMPEG), "trash": HAVE_TRASH,
"autotag": AUTOTAG.available(),
},
}
def persist_sources():
save_config_patch(sources=[{"path": s["path"]} for s in LIB.sources])
# --------------------------------------------------------------- thumbnails
def thumb_key(item):
raw = f'{item["source"]}/{item["rel"]}|{item["modified"]}|{item["size"]}'
return hashlib.md5(raw.encode("utf-8")).hexdigest()
_thumb_dir_cache = {} # source id -> writable per-source dir, or None
_thumb_dir_lock = threading.Lock()
def source_thumb_dir(sid):
"""Per-source `.workgrid-thumbs` cache dir if the source is writable,
else None (thumbs then fall back to app-data). Cached per source."""
with _thumb_dir_lock:
if sid in _thumb_dir_cache:
return _thumb_dir_cache[sid]
src = LIB.get_source(sid)
if src is None:
return None # not cached: source may be registered later
d = os.path.join(src["path"], ".workgrid-thumbs")
result = None
try:
os.makedirs(d, exist_ok=True)
probe = os.path.join(d, ".write-probe")
with open(probe, "w"):
pass
os.remove(probe)
if sys.platform == "win32":
import ctypes
ctypes.windll.kernel32.SetFileAttributesW(d, 2) # +hidden
result = d
except OSError:
result = None # read-only source -> app-data fallback
with _thumb_dir_lock:
_thumb_dir_cache[sid] = result
return result
def thumb_write_path(item, key):
"""Where a new thumbnail should be written for this item."""
d = source_thumb_dir(item["source"]) or THUMB_DIR
return os.path.join(d, key + ".jpg")
def find_thumb(item, key=None):
"""Existing thumbnail path or None. Checks the per-source dir first,
then the app-data dir (fallback + pre-hybrid legacy cache)."""
if key is None:
key = thumb_key(item)
d = source_thumb_dir(item["source"])
if d:
p = os.path.join(d, key + ".jpg")
if os.path.exists(p):
return p
p = os.path.join(THUMB_DIR, key + ".jpg")
return p if os.path.exists(p) else None
def parse_ffmpeg_info(path):
"""Extract duration/resolution/codec/fps/bitrate by parsing
`ffmpeg -i` stderr (no bundled ffprobe)."""
if not FFMPEG:
return {}
try:
p = subprocess.run(
[FFMPEG, "-hide_banner", "-i", path],
capture_output=True, text=True, errors="replace", timeout=30,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
err = p.stderr
except (OSError, subprocess.TimeoutExpired):
return {}
info = {}
m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", err)
if m:
info["duration"] = round(int(m.group(1)) * 3600 +
int(m.group(2)) * 60 +
float(m.group(3)), 2)
m = re.search(r"Duration:.*?bitrate:\s*(\d+)\s*kb/s", err)
if m:
info["bitrate"] = int(m.group(1))
m = re.search(r"Stream.*?Video:\s*(\w+)[^\n]*?(\d{2,5})x(\d{2,5})", err)
if m:
info["codec"] = m.group(1)
info["width"] = int(m.group(2))
info["height"] = int(m.group(3))
m = re.search(r"(\d+(?:\.\d+)?)\s*fps", err)
if m:
info["fps"] = float(m.group(1))
return info
class ThumbManager:
"""Background thumbnail generation with progress reporting."""
WORKERS = 3
def __init__(self):
self.lock = threading.Lock()
self.queue = deque()
self.queued = set() # keys in queue or in flight
self.failed = set() # keys that failed (don't retry)
self.done_count = 0
self.total_count = 0
self._started = False
def _ensure_workers(self):
if self._started:
return
self._started = True
for _ in range(self.WORKERS):
threading.Thread(target=self._worker, daemon=True).start()
def enqueue_items(self, items, force=False):
added = 0
with self.lock:
for it in items:
key = thumb_key(it)
if key in self.queued:
continue
if not force and (key in self.failed
or find_thumb(it, key) is not None):
continue
if force:
self.failed.discard(key)
self.queue.append((key, dict(it)))
self.queued.add(key)
added += 1
self.total_count += added
if added:
self._ensure_workers()
return added
def progress(self):
with self.lock:
return {"done": self.done_count, "total": self.total_count,
"pending": len(self.queued)}
def _worker(self):
while True:
with self.lock:
job = self.queue.popleft() if self.queue else None
if job is None:
MEDIA_META.save()
time.sleep(0.4)
continue
key, item = job
try:
ok = self._generate(key, item)
if not ok:
with self.lock:
self.failed.add(key)
except Exception as e:
print(f'[workgrid] thumb failed {item["rel"]}: {e}',
file=sys.stderr)
with self.lock:
self.failed.add(key)
with self.lock:
self.queued.discard(key)
self.done_count += 1
LIB.bump()
def _generate(self, key, item):
src = LIB.get_source(item["source"])
if src is None:
return False
full = os.path.join(src["path"], item["rel"].replace("/", os.sep))
if not os.path.isfile(full):
return False
out = thumb_write_path(item, key)
if item["type"] == "image":
return self._image_thumb(full, out, key, item)
return self._video_thumb(full, out, key)
def _image_thumb(self, full, out, key, item):
if not HAVE_PIL or item["format"] == "svg":
return False # svg: browser renders the original
with Image.open(full) as im:
MEDIA_META.update(key, {"width": im.width, "height": im.height})
im = ImageOps.exif_transpose(im)
im.thumbnail((THUMB_SIZE, THUMB_SIZE), Image.LANCZOS)
if im.mode in ("RGBA", "LA", "P"):
im = im.convert("RGBA")
bg = Image.new("RGB", im.size, (26, 28, 31))
bg.paste(im, mask=im.split()[-1])
im = bg
elif im.mode != "RGB":
im = im.convert("RGB")
im.save(out, "JPEG", quality=80)
return True
def _video_thumb(self, full, out, key):
if not FFMPEG:
return False
info = parse_ffmpeg_info(full)
if info:
MEDIA_META.update(key, info)
seek = "1" if info.get("duration", 0) >= 1.5 else "0"
cmd = [FFMPEG, "-hide_banner", "-loglevel", "error",
"-ss", seek, "-i", full, "-frames:v", "1",
"-vf", f"scale={THUMB_SIZE}:-2", "-q:v", "4", "-y", out]
try:
p = subprocess.run(
cmd, capture_output=True, timeout=60,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
except (OSError, subprocess.TimeoutExpired):
return False
return p.returncode == 0 and os.path.exists(out) \
and os.path.getsize(out) > 0
def rebuild_all(self):
items = LIB.all_items()
with self.lock:
self.failed.clear()
for it in items:
p = find_thumb(it)
if p:
try:
os.remove(p)
except OSError:
pass
return self.enqueue_items(items, force=True)
# ------------------------------------------------------------ deep metadata
def _exif_str(v):
if isinstance(v, bytes):
return v.decode("utf-8", "replace").strip("\x00 ")
return str(v)
def image_metadata(full):
rows = {}
if not HAVE_PIL:
return rows
try:
with Image.open(full) as im:
rows["dimensions"] = f"{im.width} × {im.height}"
try:
exif = im.getexif()
except Exception:
return rows
if not exif:
return rows
named = {EXIF_TAGS.get(t, t): v for t, v in exif.items()}
# camera fields live in the Exif IFD
try:
ifd = exif.get_ifd(0x8769)
named.update({EXIF_TAGS.get(t, t): v for t, v in ifd.items()})
except Exception:
pass
make = _exif_str(named.get("Make", "")).strip()
model = _exif_str(named.get("Model", "")).strip()
if make or model:
cam = model if model.lower().startswith(make.lower()) \
else (make + " " + model).strip()
rows["camera"] = cam
if named.get("LensModel"):
rows["lens"] = _exif_str(named["LensModel"])
iso = named.get("ISOSpeedRatings") or \
named.get("PhotographicSensitivity")
if iso:
rows["iso"] = f"ISO {iso}"
if named.get("FNumber"):
try:
rows["aperture"] = f"f/{float(named['FNumber']):g}"
except (TypeError, ValueError):
pass
if named.get("ExposureTime"):
try:
t = float(named["ExposureTime"])
rows["shutter"] = f"1/{round(1 / t)} s" if 0 < t < 1 \
else f"{t:g} s"
except (TypeError, ValueError, ZeroDivisionError):
pass
if named.get("FocalLength"):
try:
rows["focal length"] = \
f"{float(named['FocalLength']):g} mm"
except (TypeError, ValueError):
pass
if named.get("DateTimeOriginal"):
rows["captured"] = _exif_str(named["DateTimeOriginal"])
try:
gps_ifd = exif.get_ifd(0x8825)
if gps_ifd:
gps = {GPSTAGS.get(t, t): v for t, v in gps_ifd.items()}
lat, lon = gps.get("GPSLatitude"), gps.get("GPSLongitude")
if lat and lon:
def dms(v, ref, neg):
d = float(v[0]) + float(v[1]) / 60 \
+ float(v[2]) / 3600
return -d if ref in neg else d
rows["gps"] = (
f'{dms(lat, gps.get("GPSLatitudeRef"), "S"):.5f}, '
f'{dms(lon, gps.get("GPSLongitudeRef"), "W"):.5f}')
except Exception:
pass
except Exception as e:
rows["note"] = f"could not read: {e}"
return rows
def video_metadata(full, key):
info = MEDIA_META.get(key) or parse_ffmpeg_info(full)
rows = {}
if info.get("duration") is not None:
d = info["duration"]
rows["duration"] = f"{int(d // 60)}:{d % 60:04.1f}"
if info.get("width"):
rows["resolution"] = f'{info["width"]} × {info["height"]}'
if info.get("codec"):
rows["codec"] = info["codec"]
if info.get("fps"):
rows["fps"] = f'{info["fps"]:g} fps'
if info.get("bitrate"):
rows["bitrate"] = f'{info["bitrate"]} kb/s'
return rows
# ------------------------------------------------------------------ file ops
ILLEGAL_NAME = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
def valid_name(name):
name = name.strip()
if not name or name in (".", "..") or ILLEGAL_NAME.search(name):
return None
if name.rstrip(". ") != name: # windows: no trailing dots/spaces
return None
return name
def auto_rename(dest_dir, name):
"""foo.jpg -> foo (2).jpg, foo (3).jpg, ... until free."""
stem, ext = os.path.splitext(name)
n = 2
while True:
cand = f"{stem} ({n}){ext}"
if not os.path.exists(os.path.join(dest_dir, cand)):
return cand
n += 1
def migrate_item_data(old_sid, old_rel, new_sid, new_rel, new_full):
"""Sidecar annotations + thumbnail cache follow a moved/renamed file."""
ANNOTATIONS.rename_key(f"{old_sid}/{old_rel}", f"{new_sid}/{new_rel}")
ANNOTATIONS.save()
try:
st = os.stat(new_full)
except OSError:
return
# old cache entries are keyed by the pre-move stat; mtime survives
# shutil.move, so rebuild both keys from the same mtime/size
fake_old = {"source": old_sid, "rel": old_rel,
"modified": int(st.st_mtime), "size": st.st_size}
fake_new = {"source": new_sid, "rel": new_rel,
"modified": int(st.st_mtime), "size": st.st_size}
old_key, new_key = thumb_key(fake_old), thumb_key(fake_new)
if old_key == new_key:
return
old_thumb = find_thumb(fake_old, old_key)
if old_thumb:
try:
# cross-source move may cross drives: shutil.move, not replace
shutil.move(old_thumb, thumb_write_path(fake_new, new_key))
except OSError:
pass
meta = MEDIA_META.get(old_key)
if meta is not None:
MEDIA_META.set(new_key, meta)
MEDIA_META.delete(old_key)
MEDIA_META.save()
def drive_supports_recycle(path):
"""Network drives have no Recycle Bin — SHFileOperation would delete
permanently. Those files go to an app-data trash folder instead."""
if sys.platform != "win32":
return True
import ctypes
drive = os.path.splitdrive(os.path.realpath(path))[0]
if not drive:
return False
DRIVE_REMOTE = 4
return ctypes.windll.kernel32.GetDriveTypeW(drive + "\\") != DRIVE_REMOTE
def app_trash(full):
"""Fallback trash: move into app-data/trash/<date>/, never overwrite."""
day_dir = os.path.join(APP_DATA, "trash", time.strftime("%Y-%m-%d"))
os.makedirs(day_dir, exist_ok=True)
name = os.path.basename(full)
if os.path.exists(os.path.join(day_dir, name)):
name = auto_rename(day_dir, name)
shutil.move(full, os.path.join(day_dir, name))
def drop_item_data(sid, rel, item=None):
ANNOTATIONS.delete(f"{sid}/{rel}")
ANNOTATIONS.save()
if item:
key = thumb_key(item)
p = find_thumb(item, key)
if p:
try:
os.remove(p)
except OSError:
pass
MEDIA_META.delete(key)
# ------------------------------------------------------- organization utils
LABELS = {"red", "yellow", "green", "blue", "purple"}
def find_duplicates():
"""Byte-identical files: size prefilter, then md5 hash."""
by_size = {}
for it in LIB.all_items():
by_size.setdefault(it["size"], []).append(it)
groups = []
for size, items in by_size.items():
if len(items) < 2 or size == 0:
continue
by_hash = {}
for it in items:
full = resolve_in_source(it["source"], it["rel"])
if full is None:
continue
h = hashlib.md5()
try:
with open(full, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
except OSError:
continue
by_hash.setdefault(h.hexdigest(), []).append(it)
for digest, dupes in by_hash.items():
if len(dupes) > 1:
groups.append({"hash": digest, "size": size,
"items": [{"source": d["source"],
"rel": d["rel"],
"name": d["name"]}
for d in dupes]})
groups.sort(key=lambda g: -g["size"])
return groups
def library_stats():
items = LIB.all_items()
by_format, by_month = {}, {}
total_size = 0
for it in items:
f = by_format.setdefault(it["format"],
{"count": 0, "size": 0, "type": it["type"]})
f["count"] += 1
f["size"] += it["size"]
total_size += it["size"]
month = time.strftime("%Y-%m", time.localtime(it["modified"]))
by_month[month] = by_month.get(month, 0) + 1
return {
"total": len(items),
"totalSize": total_size,
"images": sum(1 for it in items if it["type"] == "image"),
"videos": sum(1 for it in items if it["type"] == "video"),
"byFormat": by_format,
"byMonth": dict(sorted(by_month.items())),
}
# ------------------------------------------------------------- auto-tagging
DEFAULT_VOCAB = [
"portrait", "landscape", "studio shot", "product shot", "automotive",
"car", "architecture", "interior", "food", "drink", "bottle", "people",
"animal", "nature", "forest", "beach", "mountains", "city", "night",
"aerial view", "close-up", "macro", "black and white", "colorful",
"minimal", "3d render", "cgi", "illustration", "text or logo",
"advertising", "packaging", "helicopter", "airplane", "water", "snow",
"sunset", "abstract",
]
class AutoTagger:
"""Optional local CLIP zero-shot tagging. Pluggable backend:
open_clip (torch CPU) if installed, else hidden. Results cached by
file-hash + vocabulary version; runs as a pausable background job."""
def __init__(self):
self.lock = threading.Lock()
self.cache = JsonStore("autotag-cache.json")
cfg = load_config()
self.vocab = cfg.get("autotagVocab") or list(DEFAULT_VOCAB)
self.vocab_version = cfg.get("autotagVocabVersion", 1)
self.running = False
self.pause_flag = False
self.done = 0
self.total = 0
self.error = None
self._model = None # (model, preprocess, text_features)
self._backend = None
def available(self):
if self._backend is not None:
return True
try:
import open_clip # noqa: F401
import torch # noqa: F401
self._backend = "open_clip"
return True
except ImportError:
return False
def status(self):
with self.lock:
return {
"available": self.available(),
"backend": self._backend,
"running": self.running,
"done": self.done,
"total": self.total,
"error": self.error,
"vocab": self.vocab,
}
def set_vocab(self, terms):
with self.lock:
if terms == self.vocab:
return
self.vocab = terms
self.vocab_version += 1
self._model = None # re-embed text next run
save_config_patch(autotagVocab=terms,
autotagVocabVersion=self.vocab_version)
def pause(self):
self.pause_flag = True
def start(self):
if not self.available():
return {"error": "no local model backend installed"}
with self.lock:
if self.running:
return {"ok": True, "already": True}
self.running = True
self.pause_flag = False
self.error = None
threading.Thread(target=self._run, daemon=True).start()
return {"ok": True}
# -- backend helpers
def _load_model(self):
if self._model is not None:
return self._model
# symlinked HF cache breaks under Store-Python AppData virtualization
os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")
import torch
import open_clip
model, _, preprocess = open_clip.create_model_and_transforms(
"ViT-B-32-quickgelu", pretrained="openai",
cache_dir=os.path.join(APP_DATA, "models"))
model.eval()
tokenizer = open_clip.get_tokenizer("ViT-B-32-quickgelu")
prompts = [f"a photo of {t}" for t in self.vocab]
with torch.no_grad():
text = tokenizer(prompts)
tf = model.encode_text(text)
tf = tf / tf.norm(dim=-1, keepdim=True)
self._model = (model, preprocess, tf)
return self._model
def _tag_image(self, pil_image):
import torch
model, preprocess, tf = self._load_model()
with torch.no_grad():
img = preprocess(pil_image).unsqueeze(0)
feat = model.encode_image(img)
feat = feat / feat.norm(dim=-1, keepdim=True)
sims = (100.0 * feat @ tf.T).softmax(dim=-1)[0]
scored = sorted(zip(self.vocab, sims.tolist()),
key=lambda p: -p[1])
return [[t, round(s, 3)] for t, s in scored[:5] if s >= 0.08]
@staticmethod
def _file_hash(full):
h = hashlib.md5()
try:
with open(full, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
except OSError:
return None
return h.hexdigest()
def _run(self):
items = [it for it in LIB.all_items()]
with self.lock:
self.total = len(items)
self.done = 0
try:
self._load_model()
except Exception as e:
with self.lock:
self.running = False
self.error = f"model load failed: {e}"
print(f"[workgrid] autotag: {self.error}", file=sys.stderr)
return
for it in items:
if self.pause_flag:
break
try:
self._tag_item(it)
except Exception as e:
print(f'[workgrid] autotag {it["rel"]}: {e}',
file=sys.stderr)
with self.lock:
self.done += 1
LIB.bump()
self.cache.save()
ANNOTATIONS.save()
with self.lock:
self.running = False
def _tag_item(self, it):
ann_key = f'{it["source"]}/{it["rel"]}'
full = resolve_in_source(it["source"], it["rel"])
if full is None:
return
fhash = self._file_hash(full)
if fhash is None:
return
cache_key = f"{fhash}:{self.vocab_version}"
tags = self.cache.get(cache_key)
if tags is None:
if it["type"] == "video":
# tag the poster frame (thumbnail)
tpath = find_thumb(it)
if tpath is None:
return
src_path = tpath
else:
if it["format"] == "svg" or not HAVE_PIL:
return