pantat88 commited on
Commit
755b6d7
1 Parent(s): 27f7449

Upload hashes.py

Browse files
Files changed (1) hide show
  1. hashes.py +79 -0
hashes.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os.path
3
+
4
+ from modules import shared
5
+ import modules.cache
6
+
7
+ dump_cache = modules.cache.dump_cache
8
+ cache = modules.cache.cache
9
+
10
+
11
+ def calculate_sha256(filename):
12
+ hash_sha256 = hashlib.sha256()
13
+ blksize = 1024 * 1024
14
+
15
+ with open(filename, "rb") as f:
16
+ for chunk in iter(lambda: f.read(blksize), b""):
17
+ hash_sha256.update(chunk)
18
+
19
+ return hash_sha256.hexdigest()
20
+
21
+
22
+ def sha256_from_cache(filename, title, use_addnet_hash=False):
23
+ hashes = cache("hashes-addnet") if use_addnet_hash else cache("hashes")
24
+ ondisk_mtime = os.path.getmtime(filename)
25
+
26
+ if title not in hashes:
27
+ return None
28
+
29
+ cached_sha256 = hashes[title].get("sha256", None)
30
+ cached_mtime = hashes[title].get("mtime", 0)
31
+
32
+ if ondisk_mtime > cached_mtime or cached_sha256 is None:
33
+ return None
34
+
35
+ return cached_sha256
36
+
37
+
38
+ def sha256(filename, title, use_addnet_hash=False):
39
+ hashes = cache("hashes-addnet") if use_addnet_hash else cache("hashes")
40
+
41
+ sha256_value = sha256_from_cache(filename, title, use_addnet_hash)
42
+ if sha256_value is not None:
43
+ return sha256_value
44
+
45
+ if shared.cmd_opts.no_hashing:
46
+ return None
47
+
48
+ if use_addnet_hash:
49
+ with open(filename, "rb") as file:
50
+ sha256_value = addnet_hash_safetensors(file)
51
+ else:
52
+ sha256_value = calculate_sha256(filename)
53
+
54
+ hashes[title] = {
55
+ "mtime": os.path.getmtime(filename),
56
+ "sha256": sha256_value,
57
+ }
58
+
59
+ dump_cache()
60
+
61
+ return sha256_value
62
+
63
+
64
+ def addnet_hash_safetensors(b):
65
+ """kohya-ss hash for safetensors from https://github.com/kohya-ss/sd-scripts/blob/main/library/train_util.py"""
66
+ hash_sha256 = hashlib.sha256()
67
+ blksize = 1024 * 1024
68
+
69
+ b.seek(0)
70
+ header = b.read(8)
71
+ n = int.from_bytes(header, "little")
72
+
73
+ offset = n + 8
74
+ b.seek(offset)
75
+ for chunk in iter(lambda: b.read(blksize), b""):
76
+ hash_sha256.update(chunk)
77
+
78
+ return hash_sha256.hexdigest()
79
+