Skip to content

Commit 2741435

Browse files
author
Roel Kluin
committed
this seems to work again, requires json edits for custom models, though
1 parent 8bbad93 commit 2741435

2 files changed

Lines changed: 37 additions & 88 deletions

File tree

json_schema/interrogators_v1_schema.json

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
{
2+
"$schema": "http://json-schema.org/draft-07/schema#",
3+
"title": "Interrogator Configurations",
24
"type": "object",
35
"properties": {
46
"MLDanbooruInterrogator": {
@@ -38,6 +40,8 @@
3840
"type": "object",
3941
"properties": {
4042
"name": { "type": "string" },
43+
"local_model": { "type": "string" },
44+
"local_tags": { "type": "string" },
4145
"model_path": { "type": "string" },
4246
"repo_id": { "type": "string" },
4347
"filename": { "type": "string" },
@@ -60,9 +64,21 @@
6064
"local_files_only": { "type": "boolean" },
6165
"legacy_cache_layout": { "type": "boolean" }
6266
},
63-
"required": [
64-
"name",
65-
"repo_id"
67+
"$comment": "repo_id is required if you want to actually download the model",
68+
"oneOf": [
69+
{
70+
"required": [
71+
"name",
72+
"repo_id"
73+
]
74+
},
75+
{
76+
"required": [
77+
"name",
78+
"local_model",
79+
"local_tags"
80+
]
81+
}
6682
],
6783
"additionalProperties": false
6884
}

tagger/interrogator.py

Lines changed: 18 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
onnx_path = Path(shared.models_path, 'TaggerOnnx')
5959
os.makedirs(onnx_path, exist_ok=True)
6060

61+
6162
class Interrogator:
6263
""" Interrogator class for tagger """
6364
# the raw input and output.
@@ -126,52 +127,11 @@ def refresh(cls) -> List[str]:
126127
if class_name[-12:] == "Interrogator":
127128
It_type = getattr(sys.modules[__name__], class_name)
128129
for name, obj in it.items():
130+
print(f"Loading {name} as {class_name}")
129131
if "name" not in obj:
130132
obj["name"] = name
131133
cls.entries[name] = It_type(**obj)
132134

133-
# load deepdanbooru project
134-
for path in os.scandir(ddp_path):
135-
if not path.is_dir():
136-
continue
137-
print(f"Scanning {path} as deepdanbooru project")
138-
139-
if not Path(path, 'project.json').is_file():
140-
print(f"Warning: {path} has no project.json, skipped")
141-
continue
142-
143-
cls.entries[path.name] = DeepDanbooruInterrogator(path.name, path)
144-
# scan for onnx models as well
145-
for path in os.scandir(onnx_path):
146-
if not path.is_dir():
147-
continue
148-
print(f"Scanning {path} as onnx model")
149-
150-
onnx_files = []
151-
for file_name in os.scandir(path):
152-
if file_name.name.endswith('.onnx'):
153-
onnx_files.append(file_name)
154-
155-
if len(onnx_files) != 1:
156-
print(f"Warning: {path}: multiple .onnx models => skipped")
157-
continue
158-
159-
for csv in os.scandir(path):
160-
if csv.name.endswith('.csv') and "tag" in csv.name.lower() \
161-
or "select" in csv.name.lower():
162-
tags_path = Path(path, csv.name)
163-
break
164-
else:
165-
print(f"Warning: {path}: no selected tags .csv file, skipped")
166-
continue
167-
168-
if path.name not in cls.entries:
169-
print(f"Warning: {path} not configured in interrogators.json")
170-
continue
171-
local_path = Path(path, onnx_files[0].name)
172-
cls.entries[path.name].local_model = str(local_path)
173-
cls.entries[path.name].local_tags = str(tags_path)
174-
175135
return sorted(i.name for i in cls.entries.values())
176136

177137
@staticmethod
@@ -194,8 +154,8 @@ def __init__(self, name: str) -> None:
194154
# run_mode 0 is dry run, 1 means run (alternating), 2 means disabled
195155
self.run_mode = 0 if hasattr(self, "large_batch_interrogate") else 2
196156
# default path if not overridden by download
197-
self.local_model = None
198-
self.local_tags = None
157+
self.local_model = ''
158+
self.local_tags = ''
199159
# XXX don't Interrogator.refresh()-ception here
200160

201161
def load(self) -> bool:
@@ -453,8 +413,6 @@ def __init__(
453413
self.model_path = model_path
454414
self.tags_path = tags_path
455415
self.model = None
456-
self.local_model = ''
457-
self.local_tags = ''
458416
# tagger_hf_hub_down_opts contains args to hf_hub_download(). Parse
459417
# and pass only the supported args.
460418

@@ -471,10 +429,6 @@ def __init__(
471429
print(f"Warning: interrogators.json: model {self.name}: "
472430
f"parameter {k} unsupported or or wrong type.")
473431

474-
if 'repo_id' not in self.hf_params:
475-
print(f"Warning: interrogators.json: HuggingFace model {self.name}"
476-
" lacks a repo_id. If not already local, download may fail.")
477-
478432
attrs = getattr(shared.opts, 'tagger_hf_hub_down_opts',
479433
f'cache_dir="{Its.hf_cache}"')
480434
attrs = [attr.split('=') for attr in map(str.strip, attrs.split(','))]
@@ -506,43 +460,22 @@ def __init__(
506460
"Invalid for hf_hub_download() => ignored.")
507461

508462
def download(self) -> Tuple[str, str]:
509-
repo_id = self.hf_params.get('repo_id', '(?)')
510-
print(f"Loading {self.name} model file from {repo_id}")
511-
if self.local_model == '':
512-
Interrogator.refresh()
513463
paths = [self.local_model, self.local_tags]
464+
try:
465+
# To prevent download don't set repo_id, export HF_HUB_OFFLINE=1
466+
repo_id = self.hf_params['repo_id']
467+
468+
print(f"(Down)Loading {self.name} model file from {repo_id}")
469+
for i, filename in enumerate([self.model_path, self.tags_path]):
470+
self.hf_params['filename'] = filename
471+
paths[i] = hf_hub_download(**self.hf_params)
472+
except Exception as err:
473+
print(f"Warning: {self.name}: {err} (might be as expected)")
474+
for i in range(2):
475+
if not os.path.isabs(paths[i]):
476+
paths[i] = os.path.join(shared.models_path, paths[i])
477+
pass
514478

515-
data = {}
516-
for k in self.repo_specs:
517-
if k in self.hf_params:
518-
data[k] = self.hf_params[k]
519-
520-
# check if the model is up to date
521-
info_path = Path(self.local_model).with_suffix('.info')
522-
if info_path.exists():
523-
524-
if all(os.path.exists(p) for p in paths):
525-
with open(info_path, 'r') as filen:
526-
try:
527-
old_data = json.load(filen)
528-
if old_data == data:
529-
print(f"Model {self.name} is up to date.")
530-
return paths
531-
except json.decoder.JSONDecodeError:
532-
pass
533-
534-
try:
535-
for i, filen in enumerate([self.model_path, self.tags_path]):
536-
self.hf_params['filename'] = filen
537-
paths[i] = hf_hub_download(**self.hf_params)
538-
except Exception as err:
539-
print(f"hf_hub_download({self.hf_params}: {err}")
540-
return paths
541-
542-
# write the repo_specs to a json alongside the model so we can
543-
# check if the model is up to date
544-
with open(info_path, 'w') as filen:
545-
json.dump(data, filen)
546479
return paths
547480

548481
def load_model(self, model_path) -> None:

0 commit comments

Comments
 (0)