Matthew Tucker commited on
Commit ·
1ff50f0
1
Parent(s): 243a13a
add Black and reformat
Browse files- cliptag/__init__.py +1 -1
- cliptag/cliptag.py +57 -26
- cliptag/loaders.py +30 -25
- genwords.py +7 -7
- gradio_app.py +19 -7
- requirements-dev.txt +3 -0
cliptag/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
from .cliptag import ImageKeywordGenerator, load_keywords_from_files
|
|
|
|
| 1 |
+
from .cliptag import ImageKeywordGenerator, load_keywords_from_files
|
cliptag/cliptag.py
CHANGED
|
@@ -3,16 +3,22 @@ from typing import List
|
|
| 3 |
import torch
|
| 4 |
import open_clip
|
| 5 |
import os
|
| 6 |
-
from clip_interrogator import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from tqdm import tqdm
|
| 8 |
|
|
|
|
| 9 |
def load_keywords_from_files(directory):
|
| 10 |
keyword_list = []
|
| 11 |
for filename in os.listdir(directory):
|
| 12 |
# Check if the file has a .txt extension
|
| 13 |
-
if filename.endswith(
|
| 14 |
file_path = os.path.join(directory, filename)
|
| 15 |
-
with open(file_path,
|
| 16 |
# Read lines and strip leading/trailing whitespace
|
| 17 |
keywords = [line.strip() for line in file]
|
| 18 |
# Add keywords to the master keyword_list
|
|
@@ -20,11 +26,12 @@ def load_keywords_from_files(directory):
|
|
| 20 |
print(f"Loaded {len(keyword_list)} keywords...")
|
| 21 |
return keyword_list
|
| 22 |
|
|
|
|
| 23 |
class Interrogator(CIInterrogator):
|
| 24 |
def __init__(self, config: Config):
|
| 25 |
self.config = config
|
| 26 |
self.device = config.device
|
| 27 |
-
self.dtype = torch.float16 if self.device ==
|
| 28 |
self.caption_offloaded = True
|
| 29 |
self.clip_offloaded = True
|
| 30 |
self.load_clip_model()
|
|
@@ -32,19 +39,25 @@ class Interrogator(CIInterrogator):
|
|
| 32 |
def load_clip_model(self):
|
| 33 |
config = self.config
|
| 34 |
|
| 35 |
-
clip_model_name, clip_model_pretrained_name = config.clip_model_name.split(
|
|
|
|
|
|
|
| 36 |
|
| 37 |
if config.clip_model is None:
|
| 38 |
if not config.quiet:
|
| 39 |
print(f"Loading CLIP model {config.clip_model_name}...")
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
device=config.device,
|
| 46 |
jit=False,
|
| 47 |
-
cache_dir=config.clip_model_path
|
| 48 |
)
|
| 49 |
self.clip_model.eval()
|
| 50 |
else:
|
|
@@ -52,23 +65,33 @@ class Interrogator(CIInterrogator):
|
|
| 52 |
self.clip_preprocess = config.clip_preprocess
|
| 53 |
self.tokenize = open_clip.get_tokenizer(clip_model_name)
|
| 54 |
|
| 55 |
-
class ImageKeywordGenerator:
|
| 56 |
|
|
|
|
| 57 |
def __init__(self, features_file_dir, config=None):
|
| 58 |
if not config:
|
| 59 |
config = Config(caption_model_name=None)
|
| 60 |
self.ci = Interrogator(config)
|
| 61 |
-
cache_desc = features_file_dir.replace(
|
| 62 |
-
self.table = LabelTable(
|
|
|
|
|
|
|
| 63 |
self.device = self.table.device
|
| 64 |
self.chunk_size = self.table.chunk_size
|
| 65 |
self.config = self.table.config
|
| 66 |
self.labels = self.table.labels
|
| 67 |
self.embeds = self.table.embeds
|
| 68 |
|
| 69 |
-
def _rank(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
top_count = min(top_count, len(text_embeds))
|
| 71 |
-
text_embeds = torch.stack([torch.from_numpy(t) for t in text_embeds]).to(
|
|
|
|
|
|
|
| 72 |
with torch.cuda.amp.autocast():
|
| 73 |
similarity = image_features @ text_embeds.T
|
| 74 |
if reverse:
|
|
@@ -78,28 +101,36 @@ class ImageKeywordGenerator:
|
|
| 78 |
|
| 79 |
values_list = values.squeeze(0).tolist()
|
| 80 |
indices_list = indices.squeeze(0).tolist()
|
| 81 |
-
|
| 82 |
return [(values_list[i], indices_list[i]) for i in range(top_count)]
|
| 83 |
|
| 84 |
-
def rank(
|
|
|
|
|
|
|
| 85 |
if len(self.labels) <= self.chunk_size:
|
| 86 |
-
tops = self._rank(
|
|
|
|
|
|
|
| 87 |
return {self.labels[i]: val for val, i in tops}
|
| 88 |
|
| 89 |
-
num_chunks = int(math.ceil(len(self.labels)/self.chunk_size))
|
| 90 |
keep_per_chunk = int(self.chunk_size / num_chunks)
|
| 91 |
|
| 92 |
top_labels, top_embeds = [], []
|
| 93 |
for chunk_idx in tqdm(range(num_chunks), disable=self.config.quiet):
|
| 94 |
-
start = chunk_idx*self.chunk_size
|
| 95 |
-
stop = min(start+self.chunk_size, len(self.embeds))
|
| 96 |
-
tops = self._rank(
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
tops = self._rank(image_features, top_embeds, top_count=top_count)
|
| 101 |
return {self.labels[i]: val for val, i in tops}
|
| 102 |
|
| 103 |
-
|
| 104 |
def generate_keywords_for_image(self, image, top_k=5):
|
| 105 |
-
return self.rank(self.ci.image_to_features(image), top_count=top_k)
|
|
|
|
| 3 |
import torch
|
| 4 |
import open_clip
|
| 5 |
import os
|
| 6 |
+
from clip_interrogator import (
|
| 7 |
+
Config,
|
| 8 |
+
Interrogator as CIInterrogator,
|
| 9 |
+
LabelTable,
|
| 10 |
+
load_list,
|
| 11 |
+
)
|
| 12 |
from tqdm import tqdm
|
| 13 |
|
| 14 |
+
|
| 15 |
def load_keywords_from_files(directory):
|
| 16 |
keyword_list = []
|
| 17 |
for filename in os.listdir(directory):
|
| 18 |
# Check if the file has a .txt extension
|
| 19 |
+
if filename.endswith(".txt"):
|
| 20 |
file_path = os.path.join(directory, filename)
|
| 21 |
+
with open(file_path, "r") as file:
|
| 22 |
# Read lines and strip leading/trailing whitespace
|
| 23 |
keywords = [line.strip() for line in file]
|
| 24 |
# Add keywords to the master keyword_list
|
|
|
|
| 26 |
print(f"Loaded {len(keyword_list)} keywords...")
|
| 27 |
return keyword_list
|
| 28 |
|
| 29 |
+
|
| 30 |
class Interrogator(CIInterrogator):
|
| 31 |
def __init__(self, config: Config):
|
| 32 |
self.config = config
|
| 33 |
self.device = config.device
|
| 34 |
+
self.dtype = torch.float16 if self.device == "cuda" else torch.float32
|
| 35 |
self.caption_offloaded = True
|
| 36 |
self.clip_offloaded = True
|
| 37 |
self.load_clip_model()
|
|
|
|
| 39 |
def load_clip_model(self):
|
| 40 |
config = self.config
|
| 41 |
|
| 42 |
+
clip_model_name, clip_model_pretrained_name = config.clip_model_name.split(
|
| 43 |
+
"/", 2
|
| 44 |
+
)
|
| 45 |
|
| 46 |
if config.clip_model is None:
|
| 47 |
if not config.quiet:
|
| 48 |
print(f"Loading CLIP model {config.clip_model_name}...")
|
| 49 |
|
| 50 |
+
(
|
| 51 |
+
self.clip_model,
|
| 52 |
+
_,
|
| 53 |
+
self.clip_preprocess,
|
| 54 |
+
) = open_clip.create_model_and_transforms(
|
| 55 |
+
clip_model_name,
|
| 56 |
+
pretrained=clip_model_pretrained_name,
|
| 57 |
+
precision="fp16" if config.device == "cuda" else "fp32",
|
| 58 |
device=config.device,
|
| 59 |
jit=False,
|
| 60 |
+
cache_dir=config.clip_model_path,
|
| 61 |
)
|
| 62 |
self.clip_model.eval()
|
| 63 |
else:
|
|
|
|
| 65 |
self.clip_preprocess = config.clip_preprocess
|
| 66 |
self.tokenize = open_clip.get_tokenizer(clip_model_name)
|
| 67 |
|
|
|
|
| 68 |
|
| 69 |
+
class ImageKeywordGenerator:
|
| 70 |
def __init__(self, features_file_dir, config=None):
|
| 71 |
if not config:
|
| 72 |
config = Config(caption_model_name=None)
|
| 73 |
self.ci = Interrogator(config)
|
| 74 |
+
cache_desc = features_file_dir.replace("/", "_")
|
| 75 |
+
self.table = LabelTable(
|
| 76 |
+
load_keywords_from_files(features_file_dir), cache_desc, self.ci
|
| 77 |
+
)
|
| 78 |
self.device = self.table.device
|
| 79 |
self.chunk_size = self.table.chunk_size
|
| 80 |
self.config = self.table.config
|
| 81 |
self.labels = self.table.labels
|
| 82 |
self.embeds = self.table.embeds
|
| 83 |
|
| 84 |
+
def _rank(
|
| 85 |
+
self,
|
| 86 |
+
image_features: torch.Tensor,
|
| 87 |
+
text_embeds: torch.Tensor,
|
| 88 |
+
top_count: int = 1,
|
| 89 |
+
reverse: bool = False,
|
| 90 |
+
) -> str:
|
| 91 |
top_count = min(top_count, len(text_embeds))
|
| 92 |
+
text_embeds = torch.stack([torch.from_numpy(t) for t in text_embeds]).to(
|
| 93 |
+
self.device
|
| 94 |
+
)
|
| 95 |
with torch.cuda.amp.autocast():
|
| 96 |
similarity = image_features @ text_embeds.T
|
| 97 |
if reverse:
|
|
|
|
| 101 |
|
| 102 |
values_list = values.squeeze(0).tolist()
|
| 103 |
indices_list = indices.squeeze(0).tolist()
|
| 104 |
+
|
| 105 |
return [(values_list[i], indices_list[i]) for i in range(top_count)]
|
| 106 |
|
| 107 |
+
def rank(
|
| 108 |
+
self, image_features: torch.Tensor, top_count: int = 1, reverse: bool = False
|
| 109 |
+
) -> List[str]:
|
| 110 |
if len(self.labels) <= self.chunk_size:
|
| 111 |
+
tops = self._rank(
|
| 112 |
+
image_features, self.embeds, top_count=top_count, reverse=reverse
|
| 113 |
+
)
|
| 114 |
return {self.labels[i]: val for val, i in tops}
|
| 115 |
|
| 116 |
+
num_chunks = int(math.ceil(len(self.labels) / self.chunk_size))
|
| 117 |
keep_per_chunk = int(self.chunk_size / num_chunks)
|
| 118 |
|
| 119 |
top_labels, top_embeds = [], []
|
| 120 |
for chunk_idx in tqdm(range(num_chunks), disable=self.config.quiet):
|
| 121 |
+
start = chunk_idx * self.chunk_size
|
| 122 |
+
stop = min(start + self.chunk_size, len(self.embeds))
|
| 123 |
+
tops = self._rank(
|
| 124 |
+
image_features,
|
| 125 |
+
self.embeds[start:stop],
|
| 126 |
+
top_count=keep_per_chunk,
|
| 127 |
+
reverse=reverse,
|
| 128 |
+
)
|
| 129 |
+
top_labels.extend([self.labels[start + i] for _, i in tops])
|
| 130 |
+
top_embeds.extend([self.embeds[start + i] for _, i in tops])
|
| 131 |
|
| 132 |
tops = self._rank(image_features, top_embeds, top_count=top_count)
|
| 133 |
return {self.labels[i]: val for val, i in tops}
|
| 134 |
|
|
|
|
| 135 |
def generate_keywords_for_image(self, image, top_k=5):
|
| 136 |
+
return self.rank(self.ci.image_to_features(image), top_count=top_k)
|
cliptag/loaders.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
import os
|
| 4 |
import pickle
|
| 5 |
|
|
@@ -7,6 +5,7 @@ import torch
|
|
| 7 |
from cliptag import ImageKeywordGenerator
|
| 8 |
from clip_interrogator import Config
|
| 9 |
|
|
|
|
| 10 |
def load_device():
|
| 11 |
device = None
|
| 12 |
|
|
@@ -21,27 +20,33 @@ def load_device():
|
|
| 21 |
|
| 22 |
return device
|
| 23 |
|
|
|
|
| 24 |
def load_clip_generators(clip_model_names, feature_files_dir, device, cache_dir):
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import pickle
|
| 3 |
|
|
|
|
| 5 |
from cliptag import ImageKeywordGenerator
|
| 6 |
from clip_interrogator import Config
|
| 7 |
|
| 8 |
+
|
| 9 |
def load_device():
|
| 10 |
device = None
|
| 11 |
|
|
|
|
| 20 |
|
| 21 |
return device
|
| 22 |
|
| 23 |
+
|
| 24 |
def load_clip_generators(clip_model_names, feature_files_dir, device, cache_dir):
|
| 25 |
+
"""
|
| 26 |
+
Load models from file or create new ones
|
| 27 |
+
:return: list of ImageKeywordGenerator objects
|
| 28 |
+
"""
|
| 29 |
+
generator_cache_dir = f"{cache_dir}/generators"
|
| 30 |
+
embeds_cache_dir = f"{cache_dir}/embeds"
|
| 31 |
+
pickled_generators = f"{generator_cache_dir}/keyword_generators.pkl"
|
| 32 |
+
|
| 33 |
+
if os.path.exists(pickled_generators):
|
| 34 |
+
print("Loading models from file")
|
| 35 |
+
with open(pickled_generators, "rb") as f:
|
| 36 |
+
keyword_generators = pickle.load(f)
|
| 37 |
+
else:
|
| 38 |
+
keyword_generators = []
|
| 39 |
+
|
| 40 |
+
for clip_model_name in clip_model_names:
|
| 41 |
+
config = Config(
|
| 42 |
+
clip_model_name=clip_model_name,
|
| 43 |
+
caption_model_name=None,
|
| 44 |
+
device=device,
|
| 45 |
+
cache_path=embeds_cache_dir,
|
| 46 |
+
)
|
| 47 |
+
keyword_generators.append(ImageKeywordGenerator(feature_files_dir, config))
|
| 48 |
+
|
| 49 |
+
with open(pickled_generators, "wb") as f:
|
| 50 |
+
pickle.dump(keyword_generators, f)
|
| 51 |
+
|
| 52 |
+
return keyword_generators
|
genwords.py
CHANGED
|
@@ -4,16 +4,16 @@ from nltk import pos_tag
|
|
| 4 |
from nltk.tag.mapping import map_tag
|
| 5 |
from nltk import download as nltk_download
|
| 6 |
|
| 7 |
-
nltk_download(
|
| 8 |
-
nltk_download(
|
| 9 |
-
nltk_download(
|
| 10 |
|
| 11 |
WORDS_FILE = "./features/words.txt"
|
| 12 |
-
UNSUPPORTED_POS_TAGS = [
|
| 13 |
TOP_K = 200000
|
| 14 |
|
| 15 |
print("Extracting words from the Brown corpus...")
|
| 16 |
-
words = brown.tagged_words(tagset=
|
| 17 |
|
| 18 |
# print("Part-of-speech tagging words...")
|
| 19 |
# tagged_words = pos_tag(words, tagset='universal')
|
|
@@ -34,5 +34,5 @@ common_words = [word for word, _ in word_freqdist.most_common(TOP_K)]
|
|
| 34 |
# print(f"{word}")
|
| 35 |
|
| 36 |
print("Writing common words to file...")
|
| 37 |
-
with open(WORDS_FILE,
|
| 38 |
-
f.write("\n".join(common_words))
|
|
|
|
| 4 |
from nltk.tag.mapping import map_tag
|
| 5 |
from nltk import download as nltk_download
|
| 6 |
|
| 7 |
+
nltk_download("brown")
|
| 8 |
+
nltk_download("averaged_perceptron_tagger")
|
| 9 |
+
nltk_download("universal_tagset")
|
| 10 |
|
| 11 |
WORDS_FILE = "./features/words.txt"
|
| 12 |
+
UNSUPPORTED_POS_TAGS = ["ADP", "CONJ", "DET", "NUM", "PRT", "PRON", ".", "X"]
|
| 13 |
TOP_K = 200000
|
| 14 |
|
| 15 |
print("Extracting words from the Brown corpus...")
|
| 16 |
+
words = brown.tagged_words(tagset="universal")
|
| 17 |
|
| 18 |
# print("Part-of-speech tagging words...")
|
| 19 |
# tagged_words = pos_tag(words, tagset='universal')
|
|
|
|
| 34 |
# print(f"{word}")
|
| 35 |
|
| 36 |
print("Writing common words to file...")
|
| 37 |
+
with open(WORDS_FILE, "w") as f:
|
| 38 |
+
f.write("\n".join(common_words))
|
gradio_app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import concurrent.futures
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
| 4 |
-
import torch
|
| 5 |
from cliptag.cliptag import ImageKeywordGenerator
|
| 6 |
from cliptag.loaders import load_clip_generators, load_device
|
| 7 |
from clip_interrogator import Config
|
|
@@ -13,22 +13,29 @@ TOP_K_LABELS = 100
|
|
| 13 |
CLIP_MODELS = [
|
| 14 |
"ViT-L-14/openai",
|
| 15 |
"ViT-L-14/laion2b_s32b_b82k",
|
| 16 |
-
"ViT-B-32/laion2b_s34b_b79k"
|
| 17 |
]
|
| 18 |
|
| 19 |
device = load_device()
|
| 20 |
-
keyword_generators = load_clip_generators(
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def generate_keywords(keyword_generator, input_image, top_k):
|
| 23 |
return keyword_generator.generate_keywords_for_image(input_image, top_k=top_k)
|
| 24 |
|
|
|
|
| 25 |
def keywords(input_image):
|
| 26 |
labels = []
|
| 27 |
|
| 28 |
# Use ThreadPoolExecutor to parallelize keyword generation
|
| 29 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 30 |
# Use a lambda to pass the required arguments to the generate_keywords function
|
| 31 |
-
tasks = [
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# Collect the results
|
| 34 |
for future in concurrent.futures.as_completed(tasks):
|
|
@@ -36,13 +43,16 @@ def keywords(input_image):
|
|
| 36 |
|
| 37 |
return labels
|
| 38 |
|
|
|
|
| 39 |
print("Loading interfacez...")
|
| 40 |
outputs = []
|
| 41 |
examples = [os.path.join("examples", example) for example in os.listdir("examples")]
|
| 42 |
|
| 43 |
with gr.Blocks() as demo:
|
| 44 |
-
gr.Markdown(
|
| 45 |
-
|
|
|
|
|
|
|
| 46 |
btn = gr.Button("Generate Keywords")
|
| 47 |
gr.Examples(
|
| 48 |
examples=examples,
|
|
@@ -50,7 +60,9 @@ with gr.Blocks() as demo:
|
|
| 50 |
)
|
| 51 |
with gr.Row():
|
| 52 |
for clip_model_name in CLIP_MODELS:
|
| 53 |
-
output = gr.Label(
|
|
|
|
|
|
|
| 54 |
outputs.append(output)
|
| 55 |
|
| 56 |
btn.click(fn=keywords, inputs=inp, outputs=outputs)
|
|
|
|
| 1 |
import concurrent.futures
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
| 4 |
+
import torch
|
| 5 |
from cliptag.cliptag import ImageKeywordGenerator
|
| 6 |
from cliptag.loaders import load_clip_generators, load_device
|
| 7 |
from clip_interrogator import Config
|
|
|
|
| 13 |
CLIP_MODELS = [
|
| 14 |
"ViT-L-14/openai",
|
| 15 |
"ViT-L-14/laion2b_s32b_b82k",
|
| 16 |
+
"ViT-B-32/laion2b_s34b_b79k",
|
| 17 |
]
|
| 18 |
|
| 19 |
device = load_device()
|
| 20 |
+
keyword_generators = load_clip_generators(
|
| 21 |
+
CLIP_MODELS, FEATURES_FILE_DIR, device, CACHE_DIR
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
|
| 25 |
def generate_keywords(keyword_generator, input_image, top_k):
|
| 26 |
return keyword_generator.generate_keywords_for_image(input_image, top_k=top_k)
|
| 27 |
|
| 28 |
+
|
| 29 |
def keywords(input_image):
|
| 30 |
labels = []
|
| 31 |
|
| 32 |
# Use ThreadPoolExecutor to parallelize keyword generation
|
| 33 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 34 |
# Use a lambda to pass the required arguments to the generate_keywords function
|
| 35 |
+
tasks = [
|
| 36 |
+
executor.submit(generate_keywords, kg, input_image, TOP_K_LABELS)
|
| 37 |
+
for kg in keyword_generators
|
| 38 |
+
]
|
| 39 |
|
| 40 |
# Collect the results
|
| 41 |
for future in concurrent.futures.as_completed(tasks):
|
|
|
|
| 43 |
|
| 44 |
return labels
|
| 45 |
|
| 46 |
+
|
| 47 |
print("Loading interfacez...")
|
| 48 |
outputs = []
|
| 49 |
examples = [os.path.join("examples", example) for example in os.listdir("examples")]
|
| 50 |
|
| 51 |
with gr.Blocks() as demo:
|
| 52 |
+
gr.Markdown(
|
| 53 |
+
"Upload an image below to generate keywords using different CLIP model versions."
|
| 54 |
+
)
|
| 55 |
+
inp = gr.Image(type="pil", label="Image")
|
| 56 |
btn = gr.Button("Generate Keywords")
|
| 57 |
gr.Examples(
|
| 58 |
examples=examples,
|
|
|
|
| 60 |
)
|
| 61 |
with gr.Row():
|
| 62 |
for clip_model_name in CLIP_MODELS:
|
| 63 |
+
output = gr.Label(
|
| 64 |
+
label=f"{clip_model_name} Image Keywords", num_top_classes=TOP_K_LABELS
|
| 65 |
+
)
|
| 66 |
outputs.append(output)
|
| 67 |
|
| 68 |
btn.click(fn=keywords, inputs=inp, outputs=outputs)
|
requirements-dev.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-r requirements.txt
|
| 2 |
+
|
| 3 |
+
black
|