File size: 16,036 Bytes
a509ff9
 
90290aa
a509ff9
 
 
a33aa9b
0e02b5f
 
 
 
 
a077145
 
90290aa
 
a077145
a33aa9b
a509ff9
d96b2be
611defa
d96b2be
611defa
 
 
 
 
 
d96b2be
 
 
 
 
611defa
 
 
d96b2be
611defa
 
 
 
 
d96b2be
 
 
 
 
 
 
 
 
 
611defa
d96b2be
 
 
 
 
611defa
 
 
 
d96b2be
611defa
d96b2be
 
 
 
 
 
 
611defa
 
 
90290aa
611defa
 
 
 
90290aa
d96b2be
 
 
a077145
 
 
 
 
 
 
 
 
 
 
 
 
 
90290aa
 
 
a077145
 
 
 
 
 
 
 
 
 
 
 
 
 
a509ff9
1e4bd6c
 
a509ff9
90290aa
a509ff9
 
 
1e4bd6c
 
 
a509ff9
90290aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e02b5f
 
 
 
90290aa
0e02b5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90290aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e02b5f
 
 
 
 
 
 
 
 
 
90290aa
 
0e02b5f
 
 
90290aa
 
 
a077145
90290aa
0e02b5f
a077145
 
 
 
 
 
 
0e02b5f
 
 
 
 
 
 
 
 
 
 
 
075d09e
90290aa
 
 
 
 
 
 
0e02b5f
90290aa
075d09e
0e02b5f
075d09e
 
 
 
 
 
 
a077145
 
0e02b5f
 
a509ff9
90290aa
611defa
 
 
 
 
 
 
 
 
90290aa
 
1e4bd6c
 
0e02b5f
611defa
 
90290aa
611defa
 
90290aa
611defa
 
 
0e02b5f
a509ff9
 
 
5792300
456433b
90290aa
 
5792300
456433b
6ec6a41
456433b
 
 
5792300
d96b2be
 
a509ff9
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import gradio as gr
from sklearn.metrics.pairwise import cosine_similarity
from scipy.sparse import csr_matrix
import numpy as np
from joblib import load
import h5py
from io import BytesIO
import csv
import re
import random
import compress_fasttext
from collections import OrderedDict
from lark import Lark
from lark import Token
from lark.exceptions import ParseError




faq_content="""
# Questions:

## What is the purpose of this tool?

When you enter a txt2img prompt prompt and press the "submit" button, the Tagset Completer parses your prompt and checks that all your tags are valid e621 tags.  
If it finds any that are not, it recommends some valid e621 tags you can use to replace them in the "Unseen Tags" table.  
Additionally, in the "Top Artists" text box, it lists the artists who would most likely draw an image having the set of tags you provided, 
in case you want to look them up to get more ideas.

## Does input order matter?

No

## Should I use underscores or spaces in the input tags?

Spaces are preferred, but it will still work if you use underscores.  The Unseen Tags table will just complain at you.

## Can I use parentheses or weights as in the Stable Diffusion Automatic1111 WebUI?

Yes, but only '(' and ')' and numerical weights, and all of these things are ignored in all calculations.  The main benefit of this is that you can copy/paste prompts from one program to another with minimal editing.  
An example that illustrates acceptable parentheses and weight formatting is:
((sunset over the mountains)), (clear sky:1.5), ((eagle flying high:2.0)), river, (fish swimming in the river:1.2), (campfire, (marshmallows:2.1):1.3), stars in the sky, ((full moon:1.8)), (wolf howling:1.7)

## Why are some valid tags marked as "unseen", and why don't some artists ever get returned?

Some data is excluded from consideration if it did not occur frequently enough in the sample from which the application makes its calculations.
If an artist or tag is too infrequent, we might not think we have enough data to make predictions about it.

## Are there any special tags?

Yes.  We normalized the favorite counts of each image to a range of 0-9, with 0 being the lowest favcount, and 9 being the highest.
You can include any of these special tags: "score:0", "score:1", "score:2", "score:3", "score:4", "score:5", "score:6", "score:7", "score:8", "score:9"
in your list to bias the output toward artists with higher or lower scoring images.  Since they are not real tags, the Unseen Tags section will complain, but you can ignore that.

## Are there any other special tricks?

Yes.  If you want to more strongly bias the artist output toward a specific tag, you can just list it multiple times.  
So for example, the query "red fox, red fox, red fox, score:7" will yield a list of artists who are more strongly associated with the tag "red fox"
than the query "red fox, score:7".  

## Why is this space tagged "not-for-all-audience"
The "not-for-all-audience" tag informs users that this tool's text output is derived from e621.net data for tag prediction and completion.  This measure underscores a commitment to responsible content sharing.

## How is the artist list calculated?

Each artist is represented by a "pseudo-document" composed of all the tags from their uploaded images, treating these tags similarly to words in a text document. 
Similarly, when you input a set of tags, the system creates a pseudo-document for your query out of all the tags. 
It then uses a technique called cosine similarity to compare your tags against each artist's collection, essentially finding which artist's tags are most "similar" to yours.
This method helps identify artists whose work is closely aligned with the themes or elements you're interested in.
For those curious about the underlying mechanics of comparing text-like data, we employ the TF-IDF (Term Frequency-Inverse Document Frequency) method, a standard approach in information retrieval. 
You can read more about TF-IDF on its [Wikipedia page](https://en.wikipedia.org/wiki/Tf%E2%80%93idf).

## How does the tag corrector work?

We collect the tag sets from over 4 million e621 posts, treating the tag set from each image as an individual document.  
We then randomly replace about 10% of the tags in each document with a randomly selected alias from e621's list of aliases for the tag 
(e.g. "canine" gets replaced with one of {k9,canines,mongrel,cannine,cnaine,feral_canine,anthro_canine}).
We then train a FastText (https://fasttext.cc/) model on the documents.  The result of this training is a function that maps arbitrary words to vectors such that
the vector for a tag and the vectors for its aliases are all close together (because the model has seen them in similar contexts).  
Since the lists of aliases contain misspellings and rephrasings of tags, the model should be robust to these kinds of problems as long as they are not too dissimilar from the alias lists.
"""


grammar=r"""
!start: (prompt | /[][():]/+)*
prompt: (emphasized | plain | comma | WHITESPACE)*
!emphasized: "(" prompt ")"
        | "(" prompt ":" [WHITESPACE] NUMBER [WHITESPACE] ")"
comma: ","
WHITESPACE: /\s+/
plain: /([^,\\\[\]():|]|\\.)+/
%import common.SIGNED_NUMBER -> NUMBER
"""
# Initialize the parser
parser = Lark(grammar, start='start')


special_tags = ["score:0", "score:1", "score:2", "score:3", "score:4", "score:5", "score:6", "score:7", "score:8", "score:9"]


# Function to extract tags
def extract_tags(tree):
    tags = []
    def _traverse(node):
        if isinstance(node, Token) and node.type == '__ANON_1':
            tags.append(node.value.strip())
        elif not isinstance(node, Token):
            for child in node.children:
                _traverse(child)

    _traverse(tree)
    return tags

    
# Load the model and data once at startup
with h5py.File('complete_artist_data.hdf5', 'r') as f:
    # Deserialize the vectorizer
    vectorizer_bytes = f['vectorizer'][()].tobytes()
    # Use io.BytesIO to convert bytes back to a file-like object for joblib to load
    vectorizer_buffer = BytesIO(vectorizer_bytes)
    vectorizer = load(vectorizer_buffer)
    
    # Load X_artist
    X_artist = f['X_artist'][:]
    # Load artist names and decode to strings
    artist_names = [name.decode() for name in f['artist_names'][:]]


with h5py.File('conditional_tag_probabilities_matrix.h5', 'r') as f:
    # Reconstruct the sparse co-occurrence matrix
    conditional_co_occurrence_matrix = csr_matrix(
        (f['co_occurrence_data'][:], f['co_occurrence_indices'][:], f['co_occurrence_indptr'][:]),
        shape=f['co_occurrence_shape'][:]
    )

    # Reconstruct the vocabulary
    conditional_words = f['vocabulary_words'][:]
    conditional_indices = f['vocabulary_indices'][:]
    conditional_vocabulary = {key.decode('utf-8'): value for key, value in zip(conditional_words, conditional_indices)}

    # Load the document count
    conditional_doc_count = f['doc_count'][()]
    conditional_smoothing = 100. / conditional_doc_count
    
    
def clean_tag(tag):
    return ''.join(char for char in tag if ord(char) < 128)
    
    
#Normally returns tag to aliases, but when reverse=True, returns alias to tags
def build_aliases_dict(filename, reverse=False):   
    aliases_dict = {}
    with open(filename, 'r', newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            tag = clean_tag(row[0])
            alias_list = [] if row[3] == "null" else [clean_tag(alias) for alias in row[3].split(',')]
            if reverse:
                for alias in alias_list:
                    aliases_dict.setdefault(alias, []).append(tag)
            else:
                aliases_dict[tag] = alias_list
    return aliases_dict


#Imagine we are adding smoothing_value to the number of times word_j occurs in each document for smoothing.
#Note the intention is that sum_i(P(word_i|word_j)) =(approx) # of words in a document rather than 1.
def conditional_probability(word_i, word_j, co_occurrence_matrix, vocabulary, doc_count, smoothing_value=0.01):
    word_i_index = vocabulary.get(word_i)
    word_j_index = vocabulary.get(word_j)
    
    if word_i_index is not None and word_j_index is not None:
        # Directly access the sparse matrix elements
        word_j_count = co_occurrence_matrix[word_j_index, word_j_index]
        smoothed_word_j_count =  word_j_count + (smoothing_value * doc_count)
        
        word_i_count = co_occurrence_matrix[word_i_index, word_i_index]
        
        co_occurrence_count = co_occurrence_matrix[word_i_index, word_j_index]
        smoothed_co_occurrence_count = co_occurrence_count + (smoothing_value * word_i_count) 
        
        # Calculate the conditional probability with smoothing
        conditional_prob = smoothed_co_occurrence_count / smoothed_word_j_count
        
        return conditional_prob
    elif word_i_index is None:
        return 0
    else:
        return None


#geometric_mean_given_words(target_word, context_words, conditional_co_occurrence_matrix, conditioanl_vocabulary, conditional_doc_count, smoothing_value=conditional_smoothing):
def geometric_mean_given_words(target_word, context_words, co_occurrence_matrix, vocabulary, doc_count, smoothing_value=0.01):
    probabilities = []
    
    # Collect the conditional probabilities of the target word given each context word, ignoring None values
    for context_word in context_words:
        prob = conditional_probability(target_word, context_word, co_occurrence_matrix, vocabulary, doc_count, smoothing_value)
        if prob is not None:
            probabilities.append(prob)
    
    # Compute the geometric mean of the probabilities, avoiding division by zero
    if probabilities:  # Check if the list is not empty
        geometric_mean = np.prod(probabilities) ** (1.0 / len(probabilities))
    else:
        geometric_mean = 0.5  # Or assign some default value if all probabilities are None
    
    return geometric_mean


def find_similar_tags(test_tags, similarity_weight):

    #Initialize stuff
    if not hasattr(find_similar_tags, "fasttext_small_model"):
        find_similar_tags.fasttext_small_model = compress_fasttext.models.CompressedFastTextKeyedVectors.load('e621FastTextModel010Replacement_small.bin')
    tag_aliases_file = 'fluffyrock_3m.csv'
    if not hasattr(find_similar_tags, "tag2aliases"):
        find_similar_tags.tag2aliases = build_aliases_dict(tag_aliases_file)
    if not hasattr(find_similar_tags, "alias2tags"):
        find_similar_tags.alias2tags = build_aliases_dict(tag_aliases_file, reverse=True)
    
    transformed_tags = [tag.replace(' ', '_') for tag in test_tags]

    # Find similar tags and prepare data for dataframe.
    results_data = []
    for tag in test_tags:
        if tag in special_tags:
            continue
            
        modified_tag_for_search = tag.replace(' ','_')
        similar_words = find_similar_tags.fasttext_small_model.most_similar(modified_tag_for_search, topn = 100)
        result, seen = [], set()
        
        if modified_tag_for_search in find_similar_tags.tag2aliases:
            if tag in find_similar_tags.tag2aliases and "_" in tag:   #Implicitly tell the user that they should get rid of the underscore
                result.append(modified_tag_for_search.replace('_',' '), 1)
                seen.add(tag)
            else:   #The user correctly did not put underscores in their tag
                continue
        else:
            for item in similar_words:
                similar_word, similarity = item
                if similar_word not in seen:
                    if similar_word in find_similar_tags.tag2aliases:
                        result.append((similar_word.replace('_', ' '), round(similarity, 3)))
                        seen.add(similar_word)
                    else:
                        for similar_tag in find_similar_tags.alias2tags.get(similar_word, []):
                            if similar_tag not in seen:
                                result.append((similar_tag.replace('_', ' '), round(similarity, 3)))
                                seen.add(similar_tag)

        #Adjust score based on context
        for i in range(len(result)):
            word, score = result[i]  # Unpack the tuple
            geometric_mean = geometric_mean_given_words(word.replace(' ','_'), [context_tag for context_tag in transformed_tags if context_tag != word and context_tag != tag], conditional_co_occurrence_matrix, conditional_vocabulary, conditional_doc_count, smoothing_value=conditional_smoothing)
            adjusted_score = (similarity_weight * geometric_mean) + ((1-similarity_weight)*score)  # Apply the adjustment function
            result[i] = (word, adjusted_score)  # Update the tuple with the adjusted score

        # Append tag and formatted similar tags to results_data
        result = sorted(result, key=lambda x: x[1], reverse=True)[:10]
        first_entry_for_tag = True
        for word, sim in result:
            if first_entry_for_tag:
                results_data.append([tag, word, sim])
                first_entry_for_tag = False
            else:
                results_data.append(["", word, sim])
        results_data.append(["", "", ""])  # Adds a blank line after each group of tags

    if not results_data:
        results_data.append(["No Unknown Tags Found", "", ""])

    return results_data  # Return list of lists for Dataframe

def find_similar_artists(new_tags_string, top_n, similarity_weight):
    try:
        new_tags_string = new_tags_string.lower()
        # Parse the prompt
        parsed = parser.parse(new_tags_string)
        # Extract tags from the parsed tree
        new_image_tags = extract_tags(parsed)
        new_image_tags = [tag.replace('_', ' ').strip() for tag in new_image_tags]
        
        ###unseen_tags = list(set(OrderedDict.fromkeys(new_image_tags)) - set(vectorizer.vocabulary_.keys()))   #We may want this line again later.  These are the tags that were not used to calculate the artists list.
        unseen_tags_data = find_similar_tags(new_image_tags, similarity_weight)

        X_new_image = vectorizer.transform([','.join(new_image_tags)])
        similarities = cosine_similarity(X_new_image, X_artist)[0]

        top_artist_indices = np.argsort(similarities)[-top_n:][::-1]
        top_artists = [(artist_names[i], similarities[i]) for i in top_artist_indices]

        top_artists_str = "\n".join([f"{rank+1}. {artist[3:]} ({score:.4f})" for rank, (artist, score) in enumerate(top_artists)])
        dynamic_prompts_formatted_artists = "{" + "|".join([artist for artist, _ in top_artists]) + "}"

        return unseen_tags_data, top_artists_str, dynamic_prompts_formatted_artists
    except ParseError as e:
        return [], "Parse Error: Check for mismatched parentheses or something", ""


iface = gr.Interface(
    fn=find_similar_artists,
    inputs=[
        gr.Textbox(label="Enter image tags", placeholder="e.g. fox, outside, detailed background, ..."),
        gr.Slider(minimum=1, maximum=100, value=10, step=1, label="Number of artists"),
        gr.Slider(minimum=0, maximum=1, value=0.5, step=0.1, label="Similarity weight")
    ],
    outputs=[
        gr.Dataframe(label="Unseen Tags", headers=["Tag", "Similar Tags", "Similarity"]),
        gr.Textbox(label="Top Artists", info="These are the artists most strongly associated with your tags.  The number in parenthes is a similarity score between 0 and 1, with higher numbers indicating greater similarity."),
        gr.Textbox(label="Dynamic Prompts Format", info="For if you're using the Automatic1111 webui (https://github.com/AUTOMATIC1111/stable-diffusion-webui) with the Dynamic Prompts extension activated (https://github.com/adieyal/sd-dynamic-prompts) and want to try them all individually.") 
    ],
    title="Tagset Completer",
    description="Enter a list of comma-separated e6 tags",
    article=faq_content 
)

iface.launch()