-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretentative.py
More file actions
1720 lines (1498 loc) · 62.3 KB
/
Copy pathretentative.py
File metadata and controls
1720 lines (1498 loc) · 62.3 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
"""Re:Tentative - Stable Diffusion Model Manager [Beta]
Classify, rename, skin, sort, and queue-download a local SD model library.
Never guesses a base model; unresolved files quarantine to _unresolved.txt.
Full usage: README.md in the repo, or the in-app ? button.
"""
import os
import sys
import re
import json
import time
import hashlib
import threading
import urllib.request
import urllib.error
import urllib.parse
## paths; working files ride with the script
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(SCRIPT_DIR, "sd_mm_config.json")
EXCLUSION_PATH = os.path.join(SCRIPT_DIR, "_exclusion_list.txt")
UNRESOLVED_PATH = os.path.join(SCRIPT_DIR, "_unresolved.txt")
SKIPCACHE_PATH = os.path.join(SCRIPT_DIR, "_skip_cache.json")
SAVED_QUEUE_PATH = os.path.join(SCRIPT_DIR, "_saved_queue.txt")
DOWNLOAD_DIR = os.path.join(SCRIPT_DIR, "Downloaded Content")
def set_console_title(title="Re:Tentative Worker"):
"""Name the console so nobody closes it as junk (that kills the app).
Windows-only no-op elsewhere. Rename to .pyw for no console, see README."""
try:
if os.name == "nt":
os.system(f"title {title}")
except Exception:
pass
## civitai endpoints
BY_HASH = "https://civitai.com/api/v1/model-versions/by-hash/{}"
MODEL_PAGE = "https://civitai.com/models/{}"
## CDN 400s re-sent Bearer; strip it off-site
class _CivitaiRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
new = super().redirect_request(req, fp, code, msg, headers, newurl)
if new is not None:
host = (urllib.parse.urlparse(newurl).hostname or "").lower()
if not host.endswith("civitai.com"):
new.remove_header("Authorization") ## CDN leg: signature only
return new
_OPENER = urllib.request.build_opener(_CivitaiRedirectHandler())
## base->tag formatting only; unknowns pass as [Whatever]
TAG_MAP = {
"illustrious": "[Illustrious]",
"pony": "[Pony]",
"anima": "[Anima]",
"sdxl 1.0": "[SDXL 1.0]",
"sdxl": "[SDXL 1.0]",
"stable diffusion xl": "[SDXL 1.0]",
"sd 1.5": "[SD 1.5]",
"stable diffusion 1.5": "[SD 1.5]",
"noobai": "[NoobAI]",
"flux.1 d": "[Flux]",
"flux.1 s": "[Flux]",
}
MODEL_EXTS = {".safetensors", ".ckpt", ".pt"}
## config
def default_config():
return {"api_key": "", "ckpt_dir": "", "lora_dir": "", "vae_dir": ""}
def load_config():
if os.path.isfile(CONFIG_PATH):
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
cfg = json.load(f)
base = default_config()
base.update(cfg)
return base
except Exception:
pass
return default_config()
def save_config(cfg):
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2)
def save_queue_to_disk(urls):
"""Persist the current queue so it survives closing the app (auto-reload)."""
try:
with open(SAVED_QUEUE_PATH, "w", encoding="utf-8") as f:
for u in urls:
f.write(u + "\n")
return True
except Exception:
return False
def load_saved_queue():
"""Read the auto-reload queue file, if present. Returns a list of URLs."""
if not os.path.isfile(SAVED_QUEUE_PATH):
return []
try:
with open(SAVED_QUEUE_PATH, "r", encoding="utf-8") as f:
return [ln.strip() for ln in f if ln.strip()]
except Exception:
return []
def paths_configured(cfg):
"""True only if all three model folders are set and exist."""
for key in ("ckpt_dir", "lora_dir", "vae_dir"):
p = cfg.get(key, "")
if not p or not os.path.isdir(p):
return False
return True
## first-run scaffolding
DEFAULT_EXCLUSIONS = [] ## release ships with an EMPTY exclusion list
def ensure_working_files():
"""Create missing working files; idempotent, never overwrites."""
if not os.path.isfile(EXCLUSION_PATH):
with open(EXCLUSION_PATH, "w", encoding="utf-8") as f:
f.write("# One filename stem per line. Lines starting with # are ignored.\n")
f.write("# Files matching these stems are skipped entirely by the tool:\n")
f.write("# no hashing, no renaming, no unresolved-log entries.\n")
f.write("# Add non-Civitai files (local merges, hand-trained, HuggingFace,\n")
f.write("# TensorHub) here so the auto-pass leaves them alone.\n")
f.write("# Example (delete or replace):\n")
f.write("# myLocalMerge_v1\n")
if not os.path.isfile(UNRESOLVED_PATH):
open(UNRESOLVED_PATH, "w", encoding="utf-8").close()
if not os.path.isfile(SKIPCACHE_PATH):
with open(SKIPCACHE_PATH, "w", encoding="utf-8") as f:
json.dump([], f)
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
## exclusion list
def load_exclusions():
"""Return a set of lowercased, normalized stems to skip."""
ensure_working_files()
stems = set()
with open(EXCLUSION_PATH, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#"):
stems.add(normalize_stem(line))
return stems
def add_to_exclusions(stem):
"""Append a stem to the exclusion list if not already present."""
ensure_working_files()
existing = set()
with open(EXCLUSION_PATH, "r", encoding="utf-8") as f:
for line in f:
s = line.strip()
if s and not s.startswith("#"):
existing.add(normalize_stem(s))
if normalize_stem(stem) in existing:
return False
with open(EXCLUSION_PATH, "a", encoding="utf-8") as f:
f.write(stem + "\n")
return True
def normalize_stem(name):
"""Drop extension, drop trailing kohya step suffix (-000014), lowercase."""
stem = os.path.splitext(name)[0]
stem = re.sub(r"-0*\d{4,6}$", "", stem)
return stem.strip().lower()
## http helpers; short timeouts, never hang batches
def http_get_json(url, api_key=None, timeout=8, retries=2):
req = urllib.request.Request(url, headers={"User-Agent": "retentative/1.0"})
if api_key:
req.add_header("Authorization", f"Bearer {api_key}")
last_err = None
for attempt in range(retries + 1):
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code == 429 and attempt < retries:
time.sleep(1.5 * (attempt + 1))
last_err = e
continue
raise
except Exception as e:
last_err = e
if attempt < retries:
time.sleep(0.5)
continue
raise
if last_err:
raise last_err
def http_download(url, dest_path, api_key=None, timeout=120, cancel_flag=None,
progress=None):
req = urllib.request.Request(url, headers={"User-Agent": "retentative/1.0"})
if api_key:
req.add_header("Authorization", f"Bearer {api_key}")
with _OPENER.open(req, timeout=timeout) as resp:
total, done = int(resp.headers.get("Content-Length", 0)), 0
tmp = dest_path + ".part"
with open(tmp, "wb") as out:
while True:
if cancel_flag is not None and cancel_flag.is_set():
out.close()
try:
os.remove(tmp)
except OSError:
pass
return False
chunk = resp.read(256 * 1024)
if not chunk:
break
out.write(chunk)
done += len(chunk)
if progress:
if total:
progress(done / total)
else:
## no Content-Length: -(done+1) bytes; callers clamp negatives
progress(-(done + 1))
os.replace(tmp, dest_path)
return True
def sha256_file(path, cancel_flag=None):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
if cancel_flag is not None and cancel_flag.is_set():
return None
h.update(chunk)
return h.hexdigest()
def decamel(stem):
s = stem.replace("_", " ").replace("-", " ")
s = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", s)
s = re.sub(r"(?<=[A-Za-z])(?=\d)", " ", s)
s = re.sub(r"\s+", " ", s).strip()
return s
def sanitize_filename(name):
return re.sub(r'[<>:"/\\|?*]', "", name).strip()
def tag_for_base_model(base_model):
if not base_model:
return None
key = base_model.strip().lower()
if key in TAG_MAP:
return TAG_MAP[key]
return "[" + base_model.strip() + "]"
def log_unresolved(path, tried, reason):
with open(UNRESOLVED_PATH, "a", encoding="utf-8") as f:
f.write(f"{path}\n tried: {tried}\n reason: {reason}\n\n")
def load_skip_cache():
if os.path.isfile(SKIPCACHE_PATH):
try:
with open(SKIPCACHE_PATH, "r", encoding="utf-8") as f:
return set(json.load(f))
except Exception:
pass
return set()
def save_skip_cache(stems):
try:
with open(SKIPCACHE_PATH, "w", encoding="utf-8") as f:
json.dump(sorted(stems), f, indent=2)
except Exception:
pass
## sidecar / classification
def read_sidecar(model_path):
sidecar = os.path.splitext(model_path)[0] + ".civitai.info"
if not os.path.isfile(sidecar):
return None, None, None
try:
with open(sidecar, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return None, None, None
base = data.get("baseModel")
name = (data.get("model") or {}).get("name")
images = data.get("images") or []
return base, name, images
def classify_by_hash(model_path, api_key, cancel_flag=None):
digest = sha256_file(model_path, cancel_flag=cancel_flag)
if digest is None:
return None
try:
data = http_get_json(BY_HASH.format(digest), api_key=api_key)
except urllib.error.HTTPError as e:
if e.code == 404:
return None
return None
except Exception:
return None
return {
"base_model": data.get("baseModel"),
"model_name": (data.get("model") or {}).get("name"),
"images": data.get("images") or [],
"model_id": data.get("modelId"),
}
def scrape_data_next_head(model_id, api_key=None):
if not model_id:
return None
try:
url = MODEL_PAGE.format(model_id)
req = urllib.request.Request(url, headers={"User-Agent": "retentative/1.0"})
with urllib.request.urlopen(req, timeout=8) as resp:
html = resp.read().decode("utf-8", errors="ignore")
except Exception:
return None
for pat in (r'"baseModel"\s*:\s*"([^"]+)"',
r'data-next-head[^>]*baseModel[^>]*?"([^"]+)"'):
m = re.search(pat, html)
if m:
return m.group(1)
return None
## previews: stills first, video posters last, validated
_VIDEO_EXTS = {".mp4", ".webm", ".mov", ".m4v", ".avi", ".mkv", ".gifv"}
_IMAGE_MAGIC = (
b"\x89PNG\r\n\x1a\n", ## png
b"\xff\xd8\xff", ## jpeg
b"GIF87a", b"GIF89a", ## gif
b"BM", ## bmp
)
def _looks_like_image(head):
"""True if the leading bytes are a known image signature (WEBP is RIFF....WEBP)."""
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return True
return any(head.startswith(sig) for sig in _IMAGE_MAGIC)
def _video_to_poster(url):
"""Swap video ext for .jpeg; the CDN often serves a poster frame."""
base, ext = os.path.splitext(url)
if ext.lower() in _VIDEO_EXTS:
return base + ".jpeg"
return None
def image_preview_candidates(images):
"""Ordered preview URLs: real images first, then video poster guesses."""
if not images:
return []
image_urls, video_urls = [], []
for img in images:
url = img.get("url")
if not url:
continue
itype = (img.get("type") or "").lower()
ext = os.path.splitext(urllib.parse.urlparse(url).path)[1].lower()
if itype == "video" or ext in _VIDEO_EXTS:
video_urls.append(url)
else:
image_urls.append(url)
candidates = list(image_urls)
for v in video_urls:
poster = _video_to_poster(v)
if poster:
candidates.append(poster)
return candidates
def pick_preview_url(images):
"""First usable image preview URL (video entries skipped), or None."""
cands = image_preview_candidates(images)
return cands[0] if cands else None
def resolve_model(model_path, api_key, cancel_flag=None):
tried = []
base, name, images = read_sidecar(model_path)
if base:
return {
"base_model": base,
"tag": tag_for_base_model(base),
"model_name": name,
"preview_url": pick_preview_url(images),
"images": images,
"source": "sidecar",
}
tried.append("sidecar(absent)")
if not api_key:
tried.append("hash(skipped: no API key)")
log_unresolved(model_path, tried,
"no sidecar and no API key -> cannot classify")
return None
hit = classify_by_hash(model_path, api_key, cancel_flag=cancel_flag)
if hit and hit.get("base_model"):
return {
"base_model": hit["base_model"],
"tag": tag_for_base_model(hit["base_model"]),
"model_name": hit.get("model_name"),
"preview_url": pick_preview_url(hit.get("images") or []),
"images": hit.get("images") or [],
"source": "hash",
}
if hit and hit.get("model_id"):
tried.append("hash(no baseModel)")
scraped = scrape_data_next_head(hit["model_id"], api_key=api_key)
if scraped:
return {
"base_model": scraped,
"tag": tag_for_base_model(scraped),
"model_name": hit.get("model_name"),
"preview_url": pick_preview_url(hit.get("images") or []),
"images": hit.get("images") or [],
"source": "scrape",
}
tried.append("scrape(failed)")
else:
tried.append("hash(404)")
hint = decamel(os.path.splitext(os.path.basename(model_path))[0])
log_unresolved(
model_path, tried,
f"not resolvable from any authoritative source; "
f"filename hint only (NOT applied): {hint!r}")
return None
## rename / preview
def build_new_stem(tag, model_name, original_stem):
friendly = model_name.strip() if model_name else decamel(original_stem)
friendly = sanitize_filename(friendly)
## strip leading [Tag]s, never emit "[Tag]-[Tag]"
prev = None
while prev != friendly: ## loop collapses multi-prefix pileups
prev = friendly
friendly = re.sub(r"^\[[^\[\]]*\]\s*-?\s*", "", friendly, count=1).strip()
MAX_FRIENDLY = 80 ## keep full path under Windows MAX_PATH (~260)
if len(friendly) > MAX_FRIENDLY:
friendly = friendly[:MAX_FRIENDLY].rstrip()
return f"{tag}-{friendly}"
def already_formatted(stem):
return bool(re.match(r"^\[[^\]]+\]-", stem))
def rename_with_siblings(model_path, new_stem):
folder = os.path.dirname(model_path)
old_stem = os.path.splitext(os.path.basename(model_path))[0]
results = []
for fname in os.listdir(folder):
if fname == old_stem or fname.startswith(old_stem + "."):
suffix = fname[len(old_stem):]
src = os.path.join(folder, fname)
dst = os.path.join(folder, new_stem + suffix)
if os.path.abspath(src) == os.path.abspath(dst):
continue
if os.path.exists(dst):
continue
try:
os.rename(src, dst)
results.append((fname, new_stem + suffix))
except OSError as e:
log_unresolved(
src, ["rename"],
f"os.rename failed ({e.__class__.__name__}: {e}); "
f"target was {new_stem + suffix!r}")
return results
def has_preview(model_path):
stem = os.path.splitext(model_path)[0]
for ext in (".preview.png", ".preview.jpg", ".preview.jpeg"):
if os.path.isfile(stem + ext):
return True
return False
def _download_validated_image(url, dest, api_key=None, cancel_flag=None):
"""Download, keep only if the bytes are truly an image."""
tmp = dest + ".dl"
try:
ok = http_download(url, tmp, api_key=api_key, cancel_flag=cancel_flag)
except Exception:
ok = False
if not ok:
try:
os.remove(tmp)
except OSError:
pass
return False
try:
with open(tmp, "rb") as f:
head = f.read(32)
except Exception:
head = b""
if not _looks_like_image(head):
try:
os.remove(tmp)
except OSError:
pass
return False
try:
os.replace(tmp, dest)
return True
except Exception:
try:
os.remove(tmp)
except OSError:
pass
return False
def grab_preview(model_path, images, api_key, cancel_flag=None):
"""Save <stem>.preview.png from the first candidate that validates."""
if has_preview(model_path):
return False
dest = os.path.splitext(model_path)[0] + ".preview.png"
for url in image_preview_candidates(images):
if cancel_flag is not None and cancel_flag.is_set():
return False
if _download_validated_image(url, dest, api_key=api_key,
cancel_flag=cancel_flag):
return True
return False
## label & skin, the library normalizer
def iter_model_files(folder):
if not folder or not os.path.isdir(folder):
return
for fname in os.listdir(folder):
ext = os.path.splitext(fname)[1].lower()
if ext in MODEL_EXTS:
yield os.path.join(folder, fname)
def label_and_skin(cfg, log=print, cancel_flag=None):
if not paths_configured(cfg):
log("Model folders are not configured. Open Configuration first.")
return None
api_key = cfg.get("api_key", "")
exclusions = load_exclusions()
skip_cache = load_skip_cache()
open(UNRESOLVED_PATH, "w", encoding="utf-8").close()
counts = {"renamed": 0, "previewed": 0, "skipped_excluded": 0,
"skipped_formatted": 0, "skipped_cached": 0,
"unresolved": 0, "errors": 0}
folders = ((cfg["ckpt_dir"], "checkpoint"), (cfg["lora_dir"], "lora"))
for folder, label in folders:
log(f"\n=== {label.upper()}S in {folder} ===")
for model_path in iter_model_files(folder):
if cancel_flag is not None and cancel_flag.is_set():
log("Cancelled.")
return counts
fname = os.path.basename(model_path)
stem = os.path.splitext(fname)[0]
nstem = normalize_stem(fname)
if nstem in exclusions:
counts["skipped_excluded"] += 1
log(f" skip (excluded): {fname}")
continue
if already_formatted(stem):
counts["skipped_formatted"] += 1
continue
if nstem in skip_cache and read_sidecar(model_path)[0] is None:
counts["skipped_cached"] += 1
log(f" skip (cached-miss): {fname}")
continue
try:
info = resolve_model(model_path, api_key, cancel_flag=cancel_flag)
except Exception as e:
counts["errors"] += 1
log(f" ERROR {fname}: {e}")
continue
if info is None:
counts["unresolved"] += 1
skip_cache.add(nstem)
log(f" UNRESOLVED (quarantined): {fname}")
continue
new_stem = build_new_stem(info["tag"], info["model_name"], stem)
if grab_preview(model_path, info["images"], api_key,
cancel_flag=cancel_flag):
counts["previewed"] += 1
log(f" preview grabbed: {fname}")
moved = rename_with_siblings(model_path, new_stem)
if moved:
counts["renamed"] += 1
log(f" {info['source']:>7} | {fname} -> {new_stem}")
save_skip_cache(skip_cache)
log("\n=== SUMMARY ===")
for k, v in counts.items():
log(f" {k:20s}: {v}")
log(f"\nUnresolved (if any): {UNRESOLVED_PATH}")
return counts
## sorter; VAE checked before checkpoint
KNOWN_VAE_NAMES = {"sdxl.vae", "qwen_image_vae", "vae-ft-mse-840000-ema-pruned"}
def is_vae(fname):
stem = os.path.splitext(fname)[0].lower()
if stem in KNOWN_VAE_NAMES:
return True
return "vae" in stem
def is_lora(model_path):
sidecar = os.path.splitext(model_path)[0] + ".civitai.info"
if os.path.isfile(sidecar):
try:
with open(sidecar, "r", encoding="utf-8") as f:
data = json.load(f)
t = (data.get("model") or {}).get("type", "")
if t.upper() == "LORA":
return True
if t.upper() == "CHECKPOINT":
return False
except Exception:
pass
try:
size_mb = os.path.getsize(model_path) / (1024 * 1024)
return size_mb < 500
except OSError:
return False
def destination_for(model_path, cfg):
fname = os.path.basename(model_path)
if is_vae(fname):
return cfg["vae_dir"]
if is_lora(model_path):
return cfg["lora_dir"]
return cfg["ckpt_dir"]
def sort_downloads(cfg, log=print, cancel_flag=None):
if not paths_configured(cfg):
log("Model folders are not configured. Open Configuration first.")
return 0
if not os.path.isdir(DOWNLOAD_DIR):
log(f"No download dir: {DOWNLOAD_DIR}")
return 0
moved = 0
for fname in list(os.listdir(DOWNLOAD_DIR)):
if cancel_flag is not None and cancel_flag.is_set():
log("Sort cancelled.")
break
ext = os.path.splitext(fname)[1].lower()
if ext not in MODEL_EXTS:
continue
src = os.path.join(DOWNLOAD_DIR, fname)
dest_dir = destination_for(src, cfg)
os.makedirs(dest_dir, exist_ok=True)
stem = os.path.splitext(fname)[0]
for sib in list(os.listdir(DOWNLOAD_DIR)):
sstem = os.path.splitext(sib)[0]
if sib == fname or sstem == stem or sib.startswith(stem + "."):
s = os.path.join(DOWNLOAD_DIR, sib)
d = os.path.join(dest_dir, sib)
if not os.path.exists(d):
os.rename(s, d)
moved += 1
log(f" sorted -> {os.path.basename(dest_dir)}: {fname}")
return moved
## civitai url / download
def civitai_version_id_from_url(url):
url = url.strip()
q = urllib.parse.urlparse(url)
params = urllib.parse.parse_qs(q.query)
if "modelVersionId" in params:
return ("version", params["modelVersionId"][0])
m = re.search(r"/api/download/models/(\d+)", url)
if m:
return ("version", m.group(1))
m = re.search(r"/models/(\d+)", url)
if m:
return ("model", m.group(1))
return (None, None)
def resolve_download_url(kind, cid, api_key):
if kind == "version":
data = http_get_json(
f"https://civitai.com/api/v1/model-versions/{cid}", api_key=api_key)
else:
data = http_get_json(
f"https://civitai.com/api/v1/models/{cid}", api_key=api_key)
versions = data.get("modelVersions") or []
if not versions:
return None, None
data = versions[0]
files = data.get("files") or []
primary = next((f for f in files if f.get("primary")),
files[0] if files else None)
if not primary:
return None, None
return primary.get("downloadUrl"), primary.get("name")
def fetch_metadata_by_url(url, api_key):
kind, cid = civitai_version_id_from_url(url)
if not cid:
return None
try:
if kind == "version":
data = http_get_json(
f"https://civitai.com/api/v1/model-versions/{cid}", api_key=api_key)
else:
mdata = http_get_json(
f"https://civitai.com/api/v1/models/{cid}", api_key=api_key)
versions = mdata.get("modelVersions") or []
if not versions:
return None
data = versions[0]
data.setdefault("model", {})["name"] = mdata.get("name")
except Exception:
return None
return {
"base_model": data.get("baseModel"),
"model_name": (data.get("model") or {}).get("name"),
"preview_url": pick_preview_url(data.get("images") or []),
"keywords": data.get("trainedWords") or [],
}
## manual asset helpers for Repair / Add
def scan_known_base_models(cfg):
"""Dropdown derives from the library plus defaults; never hardcoded."""
found = set()
for key in ("ckpt_dir", "lora_dir"):
folder = cfg.get(key, "")
if not folder or not os.path.isdir(folder):
continue
for fname in os.listdir(folder):
if not fname.endswith(".civitai.info"):
continue
try:
with open(os.path.join(folder, fname), "r", encoding="utf-8") as f:
data = json.load(f)
bm = data.get("baseModel")
if bm:
found.add(bm.strip())
except Exception:
continue
for pretty in ("Illustrious", "Pony", "Anima", "SDXL 1.0",
"SD 1.5", "NoobAI", "Flux"):
found.add(pretty)
return sorted(found, key=str.lower)
def find_model_file(stem_or_name, folder):
if not folder or not os.path.isdir(folder):
return None
for ext in MODEL_EXTS:
cand = os.path.join(folder, stem_or_name + ext)
if os.path.isfile(cand):
return cand
target = os.path.splitext(stem_or_name)[0]
for fname in os.listdir(folder):
ext = os.path.splitext(fname)[1].lower()
if ext in MODEL_EXTS and os.path.splitext(fname)[0] == target:
return os.path.join(folder, fname)
return None
def list_model_stems(folder):
out = []
if not folder or not os.path.isdir(folder):
return out
for fname in os.listdir(folder):
ext = os.path.splitext(fname)[1].lower()
if ext in MODEL_EXTS:
out.append(os.path.splitext(fname)[0])
return sorted(out, key=str.lower)
def asset_status(model_path):
base, name, images = read_sidecar(model_path)
sidecar = os.path.splitext(model_path)[0] + ".civitai.info"
keywords = []
if os.path.isfile(sidecar):
try:
with open(sidecar, "r", encoding="utf-8") as f:
data = json.load(f)
keywords = data.get("trainedWords") or []
except Exception:
pass
return {
"has_sidecar": os.path.isfile(sidecar),
"has_preview": has_preview(model_path),
"base_model": base,
"model_name": name,
"keywords": keywords,
}
def write_keywords_to_sidecar(model_path, keywords):
sidecar = os.path.splitext(model_path)[0] + ".civitai.info"
data = {}
if os.path.isfile(sidecar):
try:
with open(sidecar, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
data = {}
data["trainedWords"] = keywords
try:
with open(sidecar, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
return True
except Exception:
return False
def apply_manual_asset(model_path, tag, friendly, keywords, preview_source,
api_key=None, make_exclusion=False, log=print):
if not os.path.isfile(model_path):
return False, f"Model file not found: {model_path}"
if keywords:
write_keywords_to_sidecar(model_path, keywords)
if preview_source:
dest = os.path.splitext(model_path)[0] + ".preview.png"
src = preview_source.strip().strip('"')
try:
if src.lower().startswith(("http://", "https://")):
http_download(src, dest, api_key=api_key)
log(" preview downloaded from URL")
elif os.path.isfile(src):
import shutil
shutil.copyfile(src, dest)
log(" preview copied from local file")
else:
log(f" ! preview source not a URL or existing file: {src}")
except Exception as e:
log(f" ! preview failed: {e}")
new_stem = build_new_stem(tag, friendly,
os.path.splitext(os.path.basename(model_path))[0])
moved = rename_with_siblings(model_path, new_stem)
if make_exclusion and add_to_exclusions(new_stem):
log(f" added to exclusion list: {new_stem}")
if moved:
return True, f"Applied: {new_stem}"
return True, f"Metadata applied; filename unchanged: {new_stem}"
## gui
README_TEXT = """\
Re:Tentative - Stable Diffusion Model Manager [Beta]
WHAT IT DOES
Keeps a local Stable Diffusion model library tidy. It classifies your
checkpoints and LoRAs by base model, renames them to a consistent
[BaseModel]-Friendly Name format, downloads a preview image when one is
missing, sorts freshly-downloaded files into the correct folders, and
includes a small Civitai download queue.
FIRST-TIME SETUP
1. Click Configuration and point the tool at your three model folders:
Checkpoints, LoRA, and VAE.
2. Paste your Civitai API key and click Save Key. The key lets the tool
read model metadata and download previews without rate-limit stalls.
A "Downloaded Content" folder is created next to this program; new
downloads land there before being sorted.
THE BUTTONS
Add Batch Load a .txt file of Civitai URLs (one per line) into the queue.
+ / Ctrl+V Add a single Civitai URL from your clipboard to the queue.
Click the small + on the queue's top-right corner, or press
Ctrl+V with the queue focused.
Remove Remove the selected queue entry.
Clear Queue Empty the whole queue. Asks first only if a download is
running; otherwise clears immediately.
Begin Download Download everything in the queue into Downloaded Content,
then sort and label/skin the new files automatically. Each
file shows a live progress bar that collapses to one record
line when it finishes.
Cancel Stop after the current file finishes.
Label & Skin Walk your whole library: classify each model, rename it to
[BaseModel]-Friendly Name, and grab a preview if missing.
Safe to run repeatedly -- already-named files are skipped.
Sort Only Move loose files out of Downloaded Content into the right
model folder (VAEs, LoRAs, checkpoints).
Repair Asset Fix one asset by hand. Search your library, pick a file, and
correct its base model, name, keywords, or preview.
Add Asset Register a file that did NOT come from Civitai (HuggingFace,
TensorHub, a local merge). Pick it with Load From Local; it is
labeled and skinned, and added to the exclusion list so the
auto-pass leaves it alone.
Save Queue Save the current queue so it reloads automatically next launch.
Export Queue Save the queue to a .txt file you choose (shareable; loads
back in via Add Batch).
Configuration Set the three model folder paths.
Save Key Store your Civitai API key.
Exit Close the program.
HOW CLASSIFICATION WORKS
For each file the tool tries, in order:
1. Read the base model from the file's .civitai.info sidecar (LoRAs).
2. If there's no sidecar (checkpoints), hash the file and ask Civitai
what it is by hash.
3. If that returns no base model, scrape the model page as a last resort.
4. If nothing works, the file is QUARANTINED: left completely untouched
and logged to _unresolved.txt. The tool never guesses a base model
from a filename, so it will never write a wrong label silently.
PREVIEWS
When a model has no preview, one is fetched from its Civitai images. Many
Civitai previews are videos, so the tool prefers a real still: it skips
videos and falls through to the next image, and validates that what it saves
is actually an image. If no usable still exists, the model is left without a
preview rather than with a broken one.
FILES THE TOOL KEEPS (all next to this program)
_exclusion_list.txt Filename stems to skip entirely. Put non-Civitai files
here so they aren't re-checked every run.
_unresolved.txt A fresh report each run of files that couldn't be
resolved -- your punch list for manual Repair.
_skip_cache.json Remembers files that failed once, so big files aren't
re-hashed every run. Delete it to force a full retry.
_saved_queue.txt Your saved download queue. Written by Save Queue and
reloaded automatically on the next launch.
sd_mm_config.json Your API key and folder paths.
A NOTE ABOUT RENAMING
Renaming model files changes the strings your SD UI stored in older image
metadata and in any saved styles or workflows. This is expected. After a
run, click the refresh arrows on your UI's model lists so it re-reads the
new names.
"""
def open_config_dialog(parent, cfg, on_saved=None):
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
win = tk.Toplevel(parent)
win.title("Configuration")
win.geometry("640x220")
win.resizable(False, False)
win.transient(parent)
win.grab_set()
pad = {"padx": 8, "pady": 8}
rows = [("Checkpoints folder:", "ckpt_dir"),
("LoRA folder:", "lora_dir"),
("VAE folder:", "vae_dir")]
vars_ = {}
for i, (label, key) in enumerate(rows):
ttk.Label(win, text=label).grid(row=i, column=0, sticky="w", **pad)
v = tk.StringVar(value=cfg.get(key, ""))
vars_[key] = v
ttk.Entry(win, textvariable=v, width=52).grid(row=i, column=1, sticky="we", **pad)
def make_browse(var=v, lbl=label):
def browse():