InvokeAI 2.2.4.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- backend/__init__.py +0 -0
- backend/invoke_ai_web_server.py +1724 -0
- backend/modules/__init__.py +0 -0
- backend/modules/create_cmd_parser.py +55 -0
- backend/modules/get_canvas_generation_mode.py +117 -0
- backend/modules/parameters.py +71 -0
- backend/modules/parse_seed_weights.py +47 -0
- configs/INITIAL_MODELS.yaml +80 -0
- configs/models.yaml.example +29 -0
- configs/sd-concepts.txt +803 -0
- configs/stable-diffusion/v1-finetune.yaml +110 -0
- configs/stable-diffusion/v1-finetune_style.yaml +103 -0
- configs/stable-diffusion/v1-inference.yaml +79 -0
- configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
- configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
- docs/assets/invoke-web-server-1.png +0 -0
- docs/assets/invoke_ai_banner.png +0 -0
- invokeai-2.2.4.5.data/data/assets/caution.png +0 -0
- invokeai-2.2.4.5.data/data/configs/INITIAL_MODELS.yaml +80 -0
- invokeai-2.2.4.5.data/data/configs/models.yaml.example +29 -0
- invokeai-2.2.4.5.data/data/configs/sd-concepts.txt +803 -0
- invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune.yaml +110 -0
- invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune_style.yaml +103 -0
- invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inference.yaml +79 -0
- invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
- invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter-Bold.790c108b.ttf +0 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter.b9a8e5e2.ttf +0 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/favicon.0d253ced.ico +0 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/index-legacy-b741077f.js +48 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/index.0dadf5d0.css +1 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/index.21ff81eb.js +625 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/logo.13003d72.png +0 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills-legacy-dde3a68a.js +4 -0
- invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills.1ff60148.js +1 -0
- invokeai-2.2.4.5.data/data/frontend/dist/index.html +23 -0
- invokeai-2.2.4.5.data/data/scripts/configure_invokeai.py +797 -0
- invokeai-2.2.4.5.data/data/scripts/create_root.py +43 -0
- invokeai-2.2.4.5.data/data/scripts/dream.py +10 -0
- invokeai-2.2.4.5.data/data/scripts/images2prompt.py +30 -0
- invokeai-2.2.4.5.data/data/scripts/invoke.py +5 -0
- invokeai-2.2.4.5.data/data/scripts/legacy_api.py +681 -0
- invokeai-2.2.4.5.data/data/scripts/load_models.py +12 -0
- invokeai-2.2.4.5.data/data/scripts/merge_embeddings.py +124 -0
- invokeai-2.2.4.5.data/data/scripts/preload_models.py +12 -0
- invokeai-2.2.4.5.data/data/scripts/sd-metadata.py +22 -0
- invokeai-2.2.4.5.dist-info/LICENSE +21 -0
- invokeai-2.2.4.5.dist-info/LICENSE-ModelWeights.txt +294 -0
- invokeai-2.2.4.5.dist-info/METADATA +288 -0
- invokeai-2.2.4.5.dist-info/RECORD +169 -0
- invokeai-2.2.4.5.dist-info/WHEEL +5 -0
- invokeai-2.2.4.5.dist-info/entry_points.txt +4 -0
- invokeai-2.2.4.5.dist-info/top_level.txt +6 -0
- invokeai-2.2.4.5.dist-info/zip-safe +1 -0
- ldm/__init__.py +0 -0
- ldm/data/__init__.py +0 -0
- ldm/data/base.py +31 -0
- ldm/data/imagenet.py +466 -0
- ldm/data/lsun.py +126 -0
- ldm/data/personalized.py +202 -0
- ldm/data/personalized_style.py +169 -0
- ldm/generate.py +1159 -0
- ldm/invoke/CLI.py +960 -0
- ldm/invoke/__init__.py +3 -0
- ldm/invoke/args.py +1257 -0
- ldm/invoke/concepts_lib.py +169 -0
- ldm/invoke/conditioning.py +289 -0
- ldm/invoke/devices.py +27 -0
- ldm/invoke/generator/__init__.py +4 -0
- ldm/invoke/generator/base.py +335 -0
- ldm/invoke/generator/embiggen.py +501 -0
- ldm/invoke/generator/img2img.py +97 -0
- ldm/invoke/generator/inpaint.py +358 -0
- ldm/invoke/generator/omnibus.py +175 -0
- ldm/invoke/generator/txt2img.py +88 -0
- ldm/invoke/generator/txt2img2img.py +182 -0
- ldm/invoke/globals.py +31 -0
- ldm/invoke/image_util.py +70 -0
- ldm/invoke/log.py +66 -0
- ldm/invoke/model_cache.py +449 -0
- ldm/invoke/patchmatch.py +44 -0
- ldm/invoke/pngwriter.py +113 -0
- ldm/invoke/prompt_parser.py +655 -0
- ldm/invoke/readline.py +442 -0
- ldm/invoke/restoration/__init__.py +4 -0
- ldm/invoke/restoration/base.py +38 -0
- ldm/invoke/restoration/codeformer.py +103 -0
- ldm/invoke/restoration/codeformer_arch.py +276 -0
- ldm/invoke/restoration/gfpgan.py +84 -0
- ldm/invoke/restoration/outcrop.py +108 -0
- ldm/invoke/restoration/outpaint.py +92 -0
- ldm/invoke/restoration/realesrgan.py +90 -0
- ldm/invoke/restoration/vqgan_arch.py +435 -0
- ldm/invoke/seamless.py +30 -0
- ldm/invoke/server.py +282 -0
- ldm/invoke/server_legacy.py +246 -0
- ldm/invoke/txt2mask.py +136 -0
- ldm/lr_scheduler.py +143 -0
- ldm/models/__init__.py +0 -0
- ldm/models/autoencoder.py +596 -0
- ldm/models/diffusion/__init__.py +0 -0
- ldm/models/diffusion/classifier.py +355 -0
- ldm/models/diffusion/cross_attention_control.py +443 -0
- ldm/models/diffusion/cross_attention_map_saving.py +95 -0
- ldm/models/diffusion/ddim.py +111 -0
- ldm/models/diffusion/ddpm.py +2263 -0
- ldm/models/diffusion/ksampler.py +312 -0
- ldm/models/diffusion/plms.py +146 -0
- ldm/models/diffusion/sampler.py +450 -0
- ldm/models/diffusion/shared_invokeai_diffusion.py +244 -0
- ldm/modules/__init__.py +0 -0
- ldm/modules/attention.py +274 -0
- ldm/modules/diffusionmodules/__init__.py +0 -0
- ldm/modules/diffusionmodules/model.py +894 -0
- ldm/modules/diffusionmodules/openaimodel.py +1036 -0
- ldm/modules/diffusionmodules/util.py +314 -0
- ldm/modules/distributions/__init__.py +0 -0
- ldm/modules/distributions/distributions.py +104 -0
- ldm/modules/ema.py +88 -0
- ldm/modules/embedding_manager.py +413 -0
- ldm/modules/encoders/__init__.py +0 -0
- ldm/modules/encoders/modules.py +772 -0
- ldm/modules/image_degradation/__init__.py +6 -0
- ldm/modules/image_degradation/bsrgan.py +846 -0
- ldm/modules/image_degradation/bsrgan_light.py +751 -0
- ldm/modules/image_degradation/utils_image.py +1024 -0
- ldm/modules/losses/__init__.py +1 -0
- ldm/modules/losses/contperceptual.py +175 -0
- ldm/modules/losses/vqperceptual.py +240 -0
- ldm/modules/x_transformer.py +752 -0
- ldm/simplet2i.py +13 -0
- ldm/util.py +264 -0
- scripts/configure_invokeai.py +797 -0
- scripts/create_root.py +43 -0
- scripts/dream.py +10 -0
- scripts/images2prompt.py +30 -0
- scripts/invoke.py +5 -0
- scripts/legacy_api.py +681 -0
- scripts/load_models.py +12 -0
- scripts/merge_embeddings.py +124 -0
- scripts/orig_scripts/img2img.py +296 -0
- scripts/orig_scripts/inpaint.py +98 -0
- scripts/orig_scripts/knn2img.py +397 -0
- scripts/orig_scripts/sample_diffusion.py +313 -0
- scripts/orig_scripts/train_searcher.py +147 -0
- scripts/orig_scripts/txt2img.py +324 -0
- scripts/preload_models.py +12 -0
- scripts/sd-metadata.py +22 -0
- vendored/clip/clip/__init__.py +1 -0
- vendored/clip/clip/bpe_simple_vocab_16e6.txt.gz +0 -0
- vendored/clip/clip/clip.py +237 -0
- vendored/clip/clip/model.py +436 -0
- vendored/clip/clip/simple_tokenizer.py +132 -0
- vendored/clip/hubconf.py +42 -0
- vendored/clip/setup.py +21 -0
- vendored/clip/tests/test_consistency.py +25 -0
- vendored/clipseg/datasets/coco_wrapper.py +99 -0
- vendored/clipseg/datasets/pascal_zeroshot.py +60 -0
- vendored/clipseg/datasets/pfe_dataset.py +129 -0
- vendored/clipseg/datasets/phrasecut.py +380 -0
- vendored/clipseg/datasets/utils.py +68 -0
- vendored/clipseg/evaluation_utils.py +292 -0
- vendored/clipseg/general_utils.py +272 -0
- vendored/clipseg/metrics.py +271 -0
- vendored/clipseg/models/clipseg.py +538 -0
- vendored/clipseg/models/vitseg.py +286 -0
- vendored/clipseg/score.py +453 -0
- vendored/clipseg/setup.py +30 -0
- vendored/clipseg/training.py +266 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import gzip
|
|
2
|
+
import html
|
|
3
|
+
import os
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
|
|
6
|
+
import ftfy
|
|
7
|
+
import regex as re
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@lru_cache()
|
|
11
|
+
def default_bpe():
|
|
12
|
+
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@lru_cache()
|
|
16
|
+
def bytes_to_unicode():
|
|
17
|
+
"""
|
|
18
|
+
Returns list of utf-8 byte and a corresponding list of unicode strings.
|
|
19
|
+
The reversible bpe codes work on unicode strings.
|
|
20
|
+
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
|
|
21
|
+
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
|
|
22
|
+
This is a signficant percentage of your normal, say, 32K bpe vocab.
|
|
23
|
+
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
|
24
|
+
And avoids mapping to whitespace/control characters the bpe code barfs on.
|
|
25
|
+
"""
|
|
26
|
+
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
|
|
27
|
+
cs = bs[:]
|
|
28
|
+
n = 0
|
|
29
|
+
for b in range(2**8):
|
|
30
|
+
if b not in bs:
|
|
31
|
+
bs.append(b)
|
|
32
|
+
cs.append(2**8+n)
|
|
33
|
+
n += 1
|
|
34
|
+
cs = [chr(n) for n in cs]
|
|
35
|
+
return dict(zip(bs, cs))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def get_pairs(word):
|
|
39
|
+
"""Return set of symbol pairs in a word.
|
|
40
|
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
|
41
|
+
"""
|
|
42
|
+
pairs = set()
|
|
43
|
+
prev_char = word[0]
|
|
44
|
+
for char in word[1:]:
|
|
45
|
+
pairs.add((prev_char, char))
|
|
46
|
+
prev_char = char
|
|
47
|
+
return pairs
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def basic_clean(text):
|
|
51
|
+
text = ftfy.fix_text(text)
|
|
52
|
+
text = html.unescape(html.unescape(text))
|
|
53
|
+
return text.strip()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def whitespace_clean(text):
|
|
57
|
+
text = re.sub(r'\s+', ' ', text)
|
|
58
|
+
text = text.strip()
|
|
59
|
+
return text
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SimpleTokenizer(object):
|
|
63
|
+
def __init__(self, bpe_path: str = default_bpe()):
|
|
64
|
+
self.byte_encoder = bytes_to_unicode()
|
|
65
|
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
|
66
|
+
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
|
|
67
|
+
merges = merges[1:49152-256-2+1]
|
|
68
|
+
merges = [tuple(merge.split()) for merge in merges]
|
|
69
|
+
vocab = list(bytes_to_unicode().values())
|
|
70
|
+
vocab = vocab + [v+'</w>' for v in vocab]
|
|
71
|
+
for merge in merges:
|
|
72
|
+
vocab.append(''.join(merge))
|
|
73
|
+
vocab.extend(['<|startoftext|>', '<|endoftext|>'])
|
|
74
|
+
self.encoder = dict(zip(vocab, range(len(vocab))))
|
|
75
|
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
|
76
|
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
|
77
|
+
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
|
|
78
|
+
self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
|
|
79
|
+
|
|
80
|
+
def bpe(self, token):
|
|
81
|
+
if token in self.cache:
|
|
82
|
+
return self.cache[token]
|
|
83
|
+
word = tuple(token[:-1]) + ( token[-1] + '</w>',)
|
|
84
|
+
pairs = get_pairs(word)
|
|
85
|
+
|
|
86
|
+
if not pairs:
|
|
87
|
+
return token+'</w>'
|
|
88
|
+
|
|
89
|
+
while True:
|
|
90
|
+
bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
|
|
91
|
+
if bigram not in self.bpe_ranks:
|
|
92
|
+
break
|
|
93
|
+
first, second = bigram
|
|
94
|
+
new_word = []
|
|
95
|
+
i = 0
|
|
96
|
+
while i < len(word):
|
|
97
|
+
try:
|
|
98
|
+
j = word.index(first, i)
|
|
99
|
+
new_word.extend(word[i:j])
|
|
100
|
+
i = j
|
|
101
|
+
except:
|
|
102
|
+
new_word.extend(word[i:])
|
|
103
|
+
break
|
|
104
|
+
|
|
105
|
+
if word[i] == first and i < len(word)-1 and word[i+1] == second:
|
|
106
|
+
new_word.append(first+second)
|
|
107
|
+
i += 2
|
|
108
|
+
else:
|
|
109
|
+
new_word.append(word[i])
|
|
110
|
+
i += 1
|
|
111
|
+
new_word = tuple(new_word)
|
|
112
|
+
word = new_word
|
|
113
|
+
if len(word) == 1:
|
|
114
|
+
break
|
|
115
|
+
else:
|
|
116
|
+
pairs = get_pairs(word)
|
|
117
|
+
word = ' '.join(word)
|
|
118
|
+
self.cache[token] = word
|
|
119
|
+
return word
|
|
120
|
+
|
|
121
|
+
def encode(self, text):
|
|
122
|
+
bpe_tokens = []
|
|
123
|
+
text = whitespace_clean(basic_clean(text)).lower()
|
|
124
|
+
for token in re.findall(self.pat, text):
|
|
125
|
+
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
|
|
126
|
+
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
|
|
127
|
+
return bpe_tokens
|
|
128
|
+
|
|
129
|
+
def decode(self, tokens):
|
|
130
|
+
text = ''.join([self.decoder[token] for token in tokens])
|
|
131
|
+
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
|
|
132
|
+
return text
|
vendored/clip/hubconf.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from clip.clip import tokenize as _tokenize, load as _load, available_models as _available_models
|
|
2
|
+
import re
|
|
3
|
+
import string
|
|
4
|
+
|
|
5
|
+
dependencies = ["torch", "torchvision", "ftfy", "regex", "tqdm"]
|
|
6
|
+
|
|
7
|
+
# For compatibility (cannot include special characters in function name)
|
|
8
|
+
model_functions = { model: re.sub(f'[{string.punctuation}]', '_', model) for model in _available_models()}
|
|
9
|
+
|
|
10
|
+
def _create_hub_entrypoint(model):
|
|
11
|
+
def entrypoint(**kwargs):
|
|
12
|
+
return _load(model, **kwargs)
|
|
13
|
+
|
|
14
|
+
entrypoint.__doc__ = f"""Loads the {model} CLIP model
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
device : Union[str, torch.device]
|
|
19
|
+
The device to put the loaded model
|
|
20
|
+
|
|
21
|
+
jit : bool
|
|
22
|
+
Whether to load the optimized JIT model or more hackable non-JIT model (default).
|
|
23
|
+
|
|
24
|
+
download_root: str
|
|
25
|
+
path to download the model files; by default, it uses "~/.cache/clip"
|
|
26
|
+
|
|
27
|
+
Returns
|
|
28
|
+
-------
|
|
29
|
+
model : torch.nn.Module
|
|
30
|
+
The {model} CLIP model
|
|
31
|
+
|
|
32
|
+
preprocess : Callable[[PIL.Image], torch.Tensor]
|
|
33
|
+
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
|
|
34
|
+
"""
|
|
35
|
+
return entrypoint
|
|
36
|
+
|
|
37
|
+
def tokenize():
|
|
38
|
+
return _tokenize
|
|
39
|
+
|
|
40
|
+
_entrypoints = {model_functions[model]: _create_hub_entrypoint(model) for model in _available_models()}
|
|
41
|
+
|
|
42
|
+
globals().update(_entrypoints)
|
vendored/clip/setup.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import pkg_resources
|
|
4
|
+
from setuptools import setup, find_packages
|
|
5
|
+
|
|
6
|
+
setup(
|
|
7
|
+
name="clip",
|
|
8
|
+
py_modules=["clip"],
|
|
9
|
+
version="1.0",
|
|
10
|
+
description="",
|
|
11
|
+
author="OpenAI",
|
|
12
|
+
packages=find_packages(exclude=["tests*"]),
|
|
13
|
+
install_requires=[
|
|
14
|
+
str(r)
|
|
15
|
+
for r in pkg_resources.parse_requirements(
|
|
16
|
+
open(os.path.join(os.path.dirname(__file__), "requirements.txt"))
|
|
17
|
+
)
|
|
18
|
+
],
|
|
19
|
+
include_package_data=True,
|
|
20
|
+
extras_require={'dev': ['pytest']},
|
|
21
|
+
)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pytest
|
|
3
|
+
import torch
|
|
4
|
+
from PIL import Image
|
|
5
|
+
|
|
6
|
+
import clip
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@pytest.mark.parametrize('model_name', clip.available_models())
|
|
10
|
+
def test_consistency(model_name):
|
|
11
|
+
device = "cpu"
|
|
12
|
+
jit_model, transform = clip.load(model_name, device=device, jit=True)
|
|
13
|
+
py_model, _ = clip.load(model_name, device=device, jit=False)
|
|
14
|
+
|
|
15
|
+
image = transform(Image.open("CLIP.png")).unsqueeze(0).to(device)
|
|
16
|
+
text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)
|
|
17
|
+
|
|
18
|
+
with torch.no_grad():
|
|
19
|
+
logits_per_image, _ = jit_model(image, text)
|
|
20
|
+
jit_probs = logits_per_image.softmax(dim=-1).cpu().numpy()
|
|
21
|
+
|
|
22
|
+
logits_per_image, _ = py_model(image, text)
|
|
23
|
+
py_probs = logits_per_image.softmax(dim=-1).cpu().numpy()
|
|
24
|
+
|
|
25
|
+
assert np.allclose(jit_probs, py_probs, atol=0.01, rtol=0.1)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import pickle
|
|
2
|
+
from types import new_class
|
|
3
|
+
import torch
|
|
4
|
+
import numpy as np
|
|
5
|
+
import os
|
|
6
|
+
import json
|
|
7
|
+
|
|
8
|
+
from os.path import join, dirname, isdir, isfile, expanduser, realpath, basename
|
|
9
|
+
from random import shuffle, seed as set_seed
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from itertools import combinations
|
|
13
|
+
from torchvision import transforms
|
|
14
|
+
from torchvision.transforms.transforms import Resize
|
|
15
|
+
|
|
16
|
+
from datasets.utils import blend_image_segmentation
|
|
17
|
+
from general_utils import get_from_repository
|
|
18
|
+
|
|
19
|
+
COCO_CLASSES = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'}
|
|
20
|
+
|
|
21
|
+
class COCOWrapper(object):
|
|
22
|
+
|
|
23
|
+
def __init__(self, split, fold=0, image_size=400, aug=None, mask='separate', negative_prob=0,
|
|
24
|
+
with_class_label=False):
|
|
25
|
+
super().__init__()
|
|
26
|
+
|
|
27
|
+
self.mask = mask
|
|
28
|
+
self.with_class_label = with_class_label
|
|
29
|
+
self.negative_prob = negative_prob
|
|
30
|
+
|
|
31
|
+
from third_party.hsnet.data.coco import DatasetCOCO
|
|
32
|
+
|
|
33
|
+
get_from_repository('COCO-20i', ['COCO-20i.tar'])
|
|
34
|
+
|
|
35
|
+
foldpath = join(dirname(__file__), '../third_party/hsnet/data/splits/coco/%s/fold%d.pkl')
|
|
36
|
+
|
|
37
|
+
def build_img_metadata_classwise(self):
|
|
38
|
+
with open(foldpath % (self.split, self.fold), 'rb') as f:
|
|
39
|
+
img_metadata_classwise = pickle.load(f)
|
|
40
|
+
return img_metadata_classwise
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
DatasetCOCO.build_img_metadata_classwise = build_img_metadata_classwise
|
|
44
|
+
# DatasetCOCO.read_mask = read_mask
|
|
45
|
+
|
|
46
|
+
mean = [0.485, 0.456, 0.406]
|
|
47
|
+
std = [0.229, 0.224, 0.225]
|
|
48
|
+
transform = transforms.Compose([
|
|
49
|
+
transforms.Resize((image_size, image_size)),
|
|
50
|
+
transforms.ToTensor(),
|
|
51
|
+
transforms.Normalize(mean, std)
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
self.coco = DatasetCOCO(expanduser('~/datasets/COCO-20i/'), fold, transform, split, 1, False)
|
|
55
|
+
|
|
56
|
+
self.all_classes = [self.coco.class_ids]
|
|
57
|
+
self.coco.base_path = join(expanduser('~/datasets/COCO-20i'))
|
|
58
|
+
|
|
59
|
+
def __len__(self):
|
|
60
|
+
return len(self.coco)
|
|
61
|
+
|
|
62
|
+
def __getitem__(self, i):
|
|
63
|
+
sample = self.coco[i]
|
|
64
|
+
|
|
65
|
+
label_name = COCO_CLASSES[int(sample['class_id'])]
|
|
66
|
+
|
|
67
|
+
img_s, seg_s = sample['support_imgs'][0], sample['support_masks'][0]
|
|
68
|
+
|
|
69
|
+
if self.negative_prob > 0 and torch.rand(1).item() < self.negative_prob:
|
|
70
|
+
new_class_id = sample['class_id']
|
|
71
|
+
while new_class_id == sample['class_id']:
|
|
72
|
+
sample2 = self.coco[torch.randint(0, len(self), (1,)).item()]
|
|
73
|
+
new_class_id = sample2['class_id']
|
|
74
|
+
img_s = sample2['support_imgs'][0]
|
|
75
|
+
seg_s = torch.zeros_like(seg_s)
|
|
76
|
+
|
|
77
|
+
mask = self.mask
|
|
78
|
+
if mask == 'separate':
|
|
79
|
+
supp = (img_s, seg_s)
|
|
80
|
+
elif mask == 'text_label':
|
|
81
|
+
# DEPRECATED
|
|
82
|
+
supp = [int(sample['class_id'])]
|
|
83
|
+
elif mask == 'text':
|
|
84
|
+
supp = [label_name]
|
|
85
|
+
else:
|
|
86
|
+
if mask.startswith('text_and_'):
|
|
87
|
+
mask = mask[9:]
|
|
88
|
+
label_add = [label_name]
|
|
89
|
+
else:
|
|
90
|
+
label_add = []
|
|
91
|
+
|
|
92
|
+
supp = label_add + blend_image_segmentation(img_s, seg_s, mode=mask)
|
|
93
|
+
|
|
94
|
+
if self.with_class_label:
|
|
95
|
+
label = (torch.zeros(0), sample['class_id'],)
|
|
96
|
+
else:
|
|
97
|
+
label = (torch.zeros(0), )
|
|
98
|
+
|
|
99
|
+
return (sample['query_img'],) + tuple(supp), (sample['query_mask'].unsqueeze(0),) + label
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from os.path import expanduser
|
|
2
|
+
import torch
|
|
3
|
+
import json
|
|
4
|
+
import torchvision
|
|
5
|
+
from general_utils import get_from_repository
|
|
6
|
+
from general_utils import log
|
|
7
|
+
from torchvision import transforms
|
|
8
|
+
|
|
9
|
+
PASCAL_VOC_CLASSES_ZS = [['cattle.n.01', 'motorcycle.n.01'], ['aeroplane.n.01', 'sofa.n.01'],
|
|
10
|
+
['cat.n.01', 'television.n.03'], ['train.n.01', 'bottle.n.01'],
|
|
11
|
+
['chair.n.01', 'pot_plant.n.01']]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PascalZeroShot(object):
|
|
15
|
+
|
|
16
|
+
def __init__(self, split, n_unseen, image_size=224) -> None:
|
|
17
|
+
super().__init__()
|
|
18
|
+
|
|
19
|
+
import sys
|
|
20
|
+
sys.path.append('third_party/JoEm')
|
|
21
|
+
from third_party.JoEm.data_loader.dataset import VOCSegmentation
|
|
22
|
+
from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC
|
|
23
|
+
|
|
24
|
+
self.pascal_classes = VOC
|
|
25
|
+
self.image_size = image_size
|
|
26
|
+
|
|
27
|
+
self.transform = transforms.Compose([
|
|
28
|
+
transforms.Resize((image_size, image_size)),
|
|
29
|
+
])
|
|
30
|
+
|
|
31
|
+
if split == 'train':
|
|
32
|
+
self.voc = VOCSegmentation(get_unseen_idx(n_unseen), get_seen_idx(n_unseen),
|
|
33
|
+
split=split, transform=True, transform_args=dict(base_size=312, crop_size=312),
|
|
34
|
+
ignore_bg=False, ignore_unseen=False, remv_unseen_img=True)
|
|
35
|
+
elif split == 'val':
|
|
36
|
+
self.voc = VOCSegmentation(get_unseen_idx(n_unseen), get_seen_idx(n_unseen),
|
|
37
|
+
split=split, transform=False,
|
|
38
|
+
ignore_bg=False, ignore_unseen=False)
|
|
39
|
+
|
|
40
|
+
self.unseen_idx = get_unseen_idx(n_unseen)
|
|
41
|
+
|
|
42
|
+
def __len__(self):
|
|
43
|
+
return len(self.voc)
|
|
44
|
+
|
|
45
|
+
def __getitem__(self, i):
|
|
46
|
+
|
|
47
|
+
sample = self.voc[i]
|
|
48
|
+
label = sample['label'].long()
|
|
49
|
+
all_labels = [l for l in torch.where(torch.bincount(label.flatten())>0)[0].numpy().tolist() if l != 255]
|
|
50
|
+
class_indices = [l for l in all_labels]
|
|
51
|
+
class_names = [self.pascal_classes[l] for l in all_labels]
|
|
52
|
+
|
|
53
|
+
image = self.transform(sample['image'])
|
|
54
|
+
|
|
55
|
+
label = transforms.Resize((self.image_size, self.image_size),
|
|
56
|
+
interpolation=torchvision.transforms.InterpolationMode.NEAREST)(label.unsqueeze(0))[0]
|
|
57
|
+
|
|
58
|
+
return (image,), (label, )
|
|
59
|
+
|
|
60
|
+
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from os.path import expanduser
|
|
2
|
+
import torch
|
|
3
|
+
import json
|
|
4
|
+
from general_utils import get_from_repository
|
|
5
|
+
from datasets.utils import blend_image_segmentation
|
|
6
|
+
from general_utils import log
|
|
7
|
+
|
|
8
|
+
PASCAL_CLASSES = {a['id']: a['synonyms'] for a in json.load(open('datasets/pascal_classes.json'))}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PFEPascalWrapper(object):
|
|
12
|
+
|
|
13
|
+
def __init__(self, mode, split, mask='separate', image_size=473, label_support=None, size=None, p_negative=0, aug=None):
|
|
14
|
+
import sys
|
|
15
|
+
# sys.path.append(expanduser('~/projects/new_one_shot'))
|
|
16
|
+
from third_party.PFENet.util.dataset import SemData
|
|
17
|
+
|
|
18
|
+
get_from_repository('PascalVOC2012', ['Pascal5i.tar'])
|
|
19
|
+
|
|
20
|
+
self.p_negative = p_negative
|
|
21
|
+
self.size = size
|
|
22
|
+
self.mode = mode
|
|
23
|
+
self.image_size = image_size
|
|
24
|
+
|
|
25
|
+
if label_support in {True, False}:
|
|
26
|
+
log.warning('label_support argument is deprecated. Use mask instead.')
|
|
27
|
+
#raise ValueError()
|
|
28
|
+
|
|
29
|
+
self.mask = mask
|
|
30
|
+
|
|
31
|
+
value_scale = 255
|
|
32
|
+
mean = [0.485, 0.456, 0.406]
|
|
33
|
+
mean = [item * value_scale for item in mean]
|
|
34
|
+
std = [0.229, 0.224, 0.225]
|
|
35
|
+
std = [item * value_scale for item in std]
|
|
36
|
+
|
|
37
|
+
import third_party.PFENet.util.transform as transform
|
|
38
|
+
|
|
39
|
+
if mode == 'val':
|
|
40
|
+
data_list = expanduser('~/projects/old_one_shot/PFENet/lists/pascal/val.txt')
|
|
41
|
+
|
|
42
|
+
data_transform = [transform.test_Resize(size=image_size)] if image_size != 'original' else []
|
|
43
|
+
data_transform += [
|
|
44
|
+
transform.ToTensor(),
|
|
45
|
+
transform.Normalize(mean=mean, std=std)
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
elif mode == 'train':
|
|
50
|
+
data_list = expanduser('~/projects/old_one_shot/PFENet/lists/pascal/voc_sbd_merge_noduplicate.txt')
|
|
51
|
+
|
|
52
|
+
assert image_size != 'original'
|
|
53
|
+
|
|
54
|
+
data_transform = [
|
|
55
|
+
transform.RandScale([0.9, 1.1]),
|
|
56
|
+
transform.RandRotate([-10, 10], padding=mean, ignore_label=255),
|
|
57
|
+
transform.RandomGaussianBlur(),
|
|
58
|
+
transform.RandomHorizontalFlip(),
|
|
59
|
+
transform.Crop((image_size, image_size), crop_type='rand', padding=mean, ignore_label=255),
|
|
60
|
+
transform.ToTensor(),
|
|
61
|
+
transform.Normalize(mean=mean, std=std)
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
data_transform = transform.Compose(data_transform)
|
|
65
|
+
|
|
66
|
+
self.dataset = SemData(split=split, mode=mode, data_root=expanduser('~/datasets/PascalVOC2012/VOC2012'),
|
|
67
|
+
data_list=data_list, shot=1, transform=data_transform, use_coco=False, use_split_coco=False)
|
|
68
|
+
|
|
69
|
+
self.class_list = self.dataset.sub_val_list if mode == 'val' else self.dataset.sub_list
|
|
70
|
+
|
|
71
|
+
# verify that subcls_list always has length 1
|
|
72
|
+
# assert len(set([len(d[4]) for d in self.dataset])) == 1
|
|
73
|
+
|
|
74
|
+
print('actual length', len(self.dataset.data_list))
|
|
75
|
+
|
|
76
|
+
def __len__(self):
|
|
77
|
+
if self.mode == 'val':
|
|
78
|
+
return len(self.dataset.data_list)
|
|
79
|
+
else:
|
|
80
|
+
return len(self.dataset.data_list)
|
|
81
|
+
|
|
82
|
+
def __getitem__(self, index):
|
|
83
|
+
if self.dataset.mode == 'train':
|
|
84
|
+
image, label, s_x, s_y, subcls_list = self.dataset[index % len(self.dataset.data_list)]
|
|
85
|
+
elif self.dataset.mode == 'val':
|
|
86
|
+
image, label, s_x, s_y, subcls_list, ori_label = self.dataset[index % len(self.dataset.data_list)]
|
|
87
|
+
ori_label = torch.from_numpy(ori_label).unsqueeze(0)
|
|
88
|
+
|
|
89
|
+
if self.image_size != 'original':
|
|
90
|
+
longerside = max(ori_label.size(1), ori_label.size(2))
|
|
91
|
+
backmask = torch.ones(ori_label.size(0), longerside, longerside).cuda()*255
|
|
92
|
+
backmask[0, :ori_label.size(1), :ori_label.size(2)] = ori_label
|
|
93
|
+
label = backmask.clone().long()
|
|
94
|
+
else:
|
|
95
|
+
label = label.unsqueeze(0)
|
|
96
|
+
|
|
97
|
+
# assert label.shape == (473, 473)
|
|
98
|
+
|
|
99
|
+
if self.p_negative > 0:
|
|
100
|
+
if torch.rand(1).item() < self.p_negative:
|
|
101
|
+
while True:
|
|
102
|
+
idx = torch.randint(0, len(self.dataset.data_list), (1,)).item()
|
|
103
|
+
_, _, s_x, s_y, subcls_list_tmp, _ = self.dataset[idx]
|
|
104
|
+
if subcls_list[0] != subcls_list_tmp[0]:
|
|
105
|
+
break
|
|
106
|
+
|
|
107
|
+
s_x = s_x[0]
|
|
108
|
+
s_y = (s_y == 1)[0]
|
|
109
|
+
label_fg = (label == 1).float()
|
|
110
|
+
val_mask = (label != 255).float()
|
|
111
|
+
|
|
112
|
+
class_id = self.class_list[subcls_list[0]]
|
|
113
|
+
|
|
114
|
+
label_name = PASCAL_CLASSES[class_id][0]
|
|
115
|
+
label_add = ()
|
|
116
|
+
mask = self.mask
|
|
117
|
+
|
|
118
|
+
if mask == 'text':
|
|
119
|
+
support = ('a photo of a ' + label_name + '.',)
|
|
120
|
+
elif mask == 'separate':
|
|
121
|
+
support = (s_x, s_y)
|
|
122
|
+
else:
|
|
123
|
+
if mask.startswith('text_and_'):
|
|
124
|
+
label_add = (label_name,)
|
|
125
|
+
mask = mask[9:]
|
|
126
|
+
|
|
127
|
+
support = (blend_image_segmentation(s_x, s_y.float(), mask)[0],)
|
|
128
|
+
|
|
129
|
+
return (image,) + label_add + support, (label_fg.unsqueeze(0), val_mask.unsqueeze(0), subcls_list[0])
|