Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/modules/extensions.py
3055 views
1
from __future__ import annotations
2
3
import configparser
4
import dataclasses
5
import os
6
import threading
7
import re
8
9
from modules import shared, errors, cache, scripts
10
from modules.gitpython_hack import Repo
11
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
12
13
extensions: list[Extension] = []
14
extension_paths: dict[str, Extension] = {}
15
loaded_extensions: dict[str, Exception] = {}
16
17
18
os.makedirs(extensions_dir, exist_ok=True)
19
20
21
def active():
22
if shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
23
return []
24
elif shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions == "extra":
25
return [x for x in extensions if x.enabled and x.is_builtin]
26
else:
27
return [x for x in extensions if x.enabled]
28
29
30
@dataclasses.dataclass
31
class CallbackOrderInfo:
32
name: str
33
before: list
34
after: list
35
36
37
class ExtensionMetadata:
38
filename = "metadata.ini"
39
config: configparser.ConfigParser
40
canonical_name: str
41
requires: list
42
43
def __init__(self, path, canonical_name):
44
self.config = configparser.ConfigParser()
45
46
filepath = os.path.join(path, self.filename)
47
# `self.config.read()` will quietly swallow OSErrors (which FileNotFoundError is),
48
# so no need to check whether the file exists beforehand.
49
try:
50
self.config.read(filepath)
51
except Exception:
52
errors.report(f"Error reading {self.filename} for extension {canonical_name}.", exc_info=True)
53
54
self.canonical_name = self.config.get("Extension", "Name", fallback=canonical_name)
55
self.canonical_name = canonical_name.lower().strip()
56
57
self.requires = None
58
59
def get_script_requirements(self, field, section, extra_section=None):
60
"""reads a list of requirements from the config; field is the name of the field in the ini file,
61
like Requires or Before, and section is the name of the [section] in the ini file; additionally,
62
reads more requirements from [extra_section] if specified."""
63
64
x = self.config.get(section, field, fallback='')
65
66
if extra_section:
67
x = x + ', ' + self.config.get(extra_section, field, fallback='')
68
69
listed_requirements = self.parse_list(x.lower())
70
res = []
71
72
for requirement in listed_requirements:
73
loaded_requirements = (x for x in requirement.split("|") if x in loaded_extensions)
74
relevant_requirement = next(loaded_requirements, requirement)
75
res.append(relevant_requirement)
76
77
return res
78
79
def parse_list(self, text):
80
"""converts a line from config ("ext1 ext2, ext3 ") into a python list (["ext1", "ext2", "ext3"])"""
81
82
if not text:
83
return []
84
85
# both "," and " " are accepted as separator
86
return [x for x in re.split(r"[,\s]+", text.strip()) if x]
87
88
def list_callback_order_instructions(self):
89
for section in self.config.sections():
90
if not section.startswith("callbacks/"):
91
continue
92
93
callback_name = section[10:]
94
95
if not callback_name.startswith(self.canonical_name):
96
errors.report(f"Callback order section for extension {self.canonical_name} is referencing the wrong extension: {section}")
97
continue
98
99
before = self.parse_list(self.config.get(section, 'Before', fallback=''))
100
after = self.parse_list(self.config.get(section, 'After', fallback=''))
101
102
yield CallbackOrderInfo(callback_name, before, after)
103
104
105
class Extension:
106
lock = threading.Lock()
107
cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
108
metadata: ExtensionMetadata
109
110
def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
111
self.name = name
112
self.path = path
113
self.enabled = enabled
114
self.status = ''
115
self.can_update = False
116
self.is_builtin = is_builtin
117
self.commit_hash = ''
118
self.commit_date = None
119
self.version = ''
120
self.branch = None
121
self.remote = None
122
self.have_info_from_repo = False
123
self.metadata = metadata if metadata else ExtensionMetadata(self.path, name.lower())
124
self.canonical_name = metadata.canonical_name
125
126
def to_dict(self):
127
return {x: getattr(self, x) for x in self.cached_fields}
128
129
def from_dict(self, d):
130
for field in self.cached_fields:
131
setattr(self, field, d[field])
132
133
def read_info_from_repo(self):
134
if self.is_builtin or self.have_info_from_repo:
135
return
136
137
def read_from_repo():
138
with self.lock:
139
if self.have_info_from_repo:
140
return
141
142
self.do_read_info_from_repo()
143
144
return self.to_dict()
145
146
try:
147
d = cache.cached_data_for_file('extensions-git', self.name, os.path.join(self.path, ".git"), read_from_repo)
148
self.from_dict(d)
149
except FileNotFoundError:
150
pass
151
self.status = 'unknown' if self.status == '' else self.status
152
153
def do_read_info_from_repo(self):
154
repo = None
155
try:
156
if os.path.exists(os.path.join(self.path, ".git")):
157
repo = Repo(self.path)
158
except Exception:
159
errors.report(f"Error reading github repository info from {self.path}", exc_info=True)
160
161
if repo is None or repo.bare:
162
self.remote = None
163
else:
164
try:
165
self.remote = next(repo.remote().urls, None)
166
commit = repo.head.commit
167
self.commit_date = commit.committed_date
168
if repo.active_branch:
169
self.branch = repo.active_branch.name
170
self.commit_hash = commit.hexsha
171
self.version = self.commit_hash[:8]
172
173
except Exception:
174
errors.report(f"Failed reading extension data from Git repository ({self.name})", exc_info=True)
175
self.remote = None
176
177
self.have_info_from_repo = True
178
179
def list_files(self, subdir, extension):
180
dirpath = os.path.join(self.path, subdir)
181
if not os.path.isdir(dirpath):
182
return []
183
184
res = []
185
for filename in sorted(os.listdir(dirpath)):
186
res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
187
188
res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]
189
190
return res
191
192
def check_updates(self):
193
repo = Repo(self.path)
194
branch_name = f'{repo.remote().name}/{self.branch}'
195
for fetch in repo.remote().fetch(dry_run=True):
196
if self.branch and fetch.name != branch_name:
197
continue
198
if fetch.flags != fetch.HEAD_UPTODATE:
199
self.can_update = True
200
self.status = "new commits"
201
return
202
203
try:
204
origin = repo.rev_parse(branch_name)
205
if repo.head.commit != origin:
206
self.can_update = True
207
self.status = "behind HEAD"
208
return
209
except Exception:
210
self.can_update = False
211
self.status = "unknown (remote error)"
212
return
213
214
self.can_update = False
215
self.status = "latest"
216
217
def fetch_and_reset_hard(self, commit=None):
218
repo = Repo(self.path)
219
if commit is None:
220
commit = f'{repo.remote().name}/{self.branch}'
221
# Fix: `error: Your local changes to the following files would be overwritten by merge`,
222
# because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
223
repo.git.fetch(all=True)
224
repo.git.reset(commit, hard=True)
225
self.have_info_from_repo = False
226
227
228
def list_extensions():
229
extensions.clear()
230
extension_paths.clear()
231
loaded_extensions.clear()
232
233
if shared.cmd_opts.disable_all_extensions:
234
print("*** \"--disable-all-extensions\" arg was used, will not load any extensions ***")
235
elif shared.opts.disable_all_extensions == "all":
236
print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
237
elif shared.cmd_opts.disable_extra_extensions:
238
print("*** \"--disable-extra-extensions\" arg was used, will only load built-in extensions ***")
239
elif shared.opts.disable_all_extensions == "extra":
240
print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
241
242
243
# scan through extensions directory and load metadata
244
for dirname in [extensions_builtin_dir, extensions_dir]:
245
if not os.path.isdir(dirname):
246
continue
247
248
for extension_dirname in sorted(os.listdir(dirname)):
249
path = os.path.join(dirname, extension_dirname)
250
if not os.path.isdir(path):
251
continue
252
253
canonical_name = extension_dirname
254
metadata = ExtensionMetadata(path, canonical_name)
255
256
# check for duplicated canonical names
257
already_loaded_extension = loaded_extensions.get(metadata.canonical_name)
258
if already_loaded_extension is not None:
259
errors.report(f'Duplicate canonical name "{canonical_name}" found in extensions "{extension_dirname}" and "{already_loaded_extension.name}". Former will be discarded.', exc_info=False)
260
continue
261
262
is_builtin = dirname == extensions_builtin_dir
263
extension = Extension(name=extension_dirname, path=path, enabled=extension_dirname not in shared.opts.disabled_extensions, is_builtin=is_builtin, metadata=metadata)
264
extensions.append(extension)
265
extension_paths[extension.path] = extension
266
loaded_extensions[canonical_name] = extension
267
268
for extension in extensions:
269
extension.metadata.requires = extension.metadata.get_script_requirements("Requires", "Extension")
270
271
# check for requirements
272
for extension in extensions:
273
if not extension.enabled:
274
continue
275
276
for req in extension.metadata.requires:
277
required_extension = loaded_extensions.get(req)
278
if required_extension is None:
279
errors.report(f'Extension "{extension.name}" requires "{req}" which is not installed.', exc_info=False)
280
continue
281
282
if not required_extension.enabled:
283
errors.report(f'Extension "{extension.name}" requires "{required_extension.name}" which is disabled.', exc_info=False)
284
continue
285
286
287
def find_extension(filename):
288
parentdir = os.path.dirname(os.path.realpath(filename))
289
290
while parentdir != filename:
291
extension = extension_paths.get(parentdir)
292
if extension is not None:
293
return extension
294
295
filename = parentdir
296
parentdir = os.path.dirname(filename)
297
298
return None
299
300
301