Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/modules/hashes.py
3055 views
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
try:
25
ondisk_mtime = os.path.getmtime(filename)
26
except FileNotFoundError:
27
return None
28
29
if title not in hashes:
30
return None
31
32
cached_sha256 = hashes[title].get("sha256", None)
33
cached_mtime = hashes[title].get("mtime", 0)
34
35
if ondisk_mtime > cached_mtime or cached_sha256 is None:
36
return None
37
38
return cached_sha256
39
40
41
def sha256(filename, title, use_addnet_hash=False):
42
hashes = cache("hashes-addnet") if use_addnet_hash else cache("hashes")
43
44
sha256_value = sha256_from_cache(filename, title, use_addnet_hash)
45
if sha256_value is not None:
46
return sha256_value
47
48
if shared.cmd_opts.no_hashing:
49
return None
50
51
print(f"Calculating sha256 for {filename}: ", end='')
52
if use_addnet_hash:
53
with open(filename, "rb") as file:
54
sha256_value = addnet_hash_safetensors(file)
55
else:
56
sha256_value = calculate_sha256(filename)
57
print(f"{sha256_value}")
58
59
hashes[title] = {
60
"mtime": os.path.getmtime(filename),
61
"sha256": sha256_value,
62
}
63
64
dump_cache()
65
66
return sha256_value
67
68
69
def addnet_hash_safetensors(b):
70
"""kohya-ss hash for safetensors from https://github.com/kohya-ss/sd-scripts/blob/main/library/train_util.py"""
71
hash_sha256 = hashlib.sha256()
72
blksize = 1024 * 1024
73
74
b.seek(0)
75
header = b.read(8)
76
n = int.from_bytes(header, "little")
77
78
offset = n + 8
79
b.seek(offset)
80
for chunk in iter(lambda: b.read(blksize), b""):
81
hash_sha256.update(chunk)
82
83
return hash_sha256.hexdigest()
84
85
86