Spaces:
Running
Running
FoodDesert
commited on
Commit
•
5a1477b
1
Parent(s):
f48183d
Upload app.py
Browse files
app.py
CHANGED
@@ -1,686 +1,750 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
from sklearn.metrics.pairwise import cosine_similarity
|
3 |
-
from scipy.sparse import csr_matrix
|
4 |
-
import numpy as np
|
5 |
-
import joblib
|
6 |
-
from joblib import load
|
7 |
-
import h5py
|
8 |
-
from io import BytesIO
|
9 |
-
import csv
|
10 |
-
import re
|
11 |
-
import random
|
12 |
-
import compress_fasttext
|
13 |
-
from collections import OrderedDict
|
14 |
-
from lark import Lark, Tree, Token
|
15 |
-
from lark.exceptions import ParseError
|
16 |
-
import json
|
17 |
-
import zipfile
|
18 |
-
from PIL import Image
|
19 |
-
import io
|
20 |
-
import os
|
21 |
-
import glob
|
22 |
-
import itertools
|
23 |
-
from itertools import islice
|
24 |
-
from pathlib import Path
|
25 |
-
import logging
|
26 |
-
|
27 |
-
# Set up logging
|
28 |
-
logging.basicConfig(filename='error.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s')
|
29 |
-
|
30 |
-
|
31 |
-
faq_content="""
|
32 |
-
#4-20-2024 Why aren't there example images for most artists?
|
33 |
-
|
34 |
-
We recently updated the underlying data used to calculate the Suggested Artists section.
|
35 |
-
We have not yet generated example images for all the new artists.
|
36 |
-
|
37 |
-
# Questions:
|
38 |
-
|
39 |
-
## What is the purpose of this tool?
|
40 |
-
|
41 |
-
Since Stable Diffusion's initial release in 2022, users have developed a myriad of fine-tuned text to image models, each with unique "linguistic" preferences depending on the data from which it was fine-tuned.
|
42 |
-
Some models react best when prompted with verbose scene descriptions akin to DALL-E, while others fine-tuned on images scraped from popular image boards understand those boards' tag sets.
|
43 |
-
This tool serves as a linguistic bridge to the e621 image board tag lexicon, on which many popular models such as Fluffyrock, Fluffusion, and Pony Diffusion v6 were trained.
|
44 |
-
|
45 |
-
When you enter a txt2img prompt and press the "submit" button, Prompt Squirrel parses your prompt and checks that all your tags are valid e621 tags.
|
46 |
-
If it finds any that are not, it recommends some valid e621 tags you can use to replace them in the "Unknown Tags" section.
|
47 |
-
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.
|
48 |
-
This is useful to align your prompt with the expected input to an e621-trained model.
|
49 |
-
|
50 |
-
## Does input order matter?
|
51 |
-
|
52 |
-
No
|
53 |
-
|
54 |
-
## Should I use underscores or spaces in the input tags?
|
55 |
-
|
56 |
-
As a rule, e621-trained models replace underscores in tags with spaces, so spaces are preferred.
|
57 |
-
|
58 |
-
## Can I use parentheses or weights as in the Stable Diffusion Automatic1111 WebUI?
|
59 |
-
|
60 |
-
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.
|
61 |
-
An example that illustrates acceptable parentheses and weight formatting is:
|
62 |
-
((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)
|
63 |
-
|
64 |
-
## Why are some valid tags marked as "unknown", and why don't some artists ever get returned?
|
65 |
-
|
66 |
-
Some data is excluded from consideration if it did not occur frequently enough in the sample from which the application makes its calculations.
|
67 |
-
If an artist or tag is too infrequent, we might not think we have enough data to make predictions about it.
|
68 |
-
|
69 |
-
## Why do some suggested tags not have summaries or wiki links?
|
70 |
-
|
71 |
-
Both of these features are extracted from the tag wiki pages, but some valid e621 tags do not have wiki pages.
|
72 |
-
|
73 |
-
## Are there any special tags?
|
74 |
-
|
75 |
-
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.
|
76 |
-
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"
|
77 |
-
in your list to bias the output toward artists with higher or lower scoring images.
|
78 |
-
|
79 |
-
## Are there any other special tricks?
|
80 |
-
|
81 |
-
Yes. If you want to more strongly bias the artist output toward a specific tag, you can just list it multiple times.
|
82 |
-
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"
|
83 |
-
than the query "red fox, score:7".
|
84 |
-
|
85 |
-
## Why is this space tagged "not-for-all-audience"
|
86 |
-
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.
|
87 |
-
The app will try not to display nsfw tags unless the "Allow NSFW Tags" is checked, but the filter is not perfect.
|
88 |
-
|
89 |
-
## How does the tag corrector work?
|
90 |
-
|
91 |
-
We collect the tag sets from over 4 million e621 posts, treating the tag set from each image as an individual document.
|
92 |
-
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
|
93 |
-
(e.g. "canine" gets replaced with one of {k9,canines,mongrel,cannine,cnaine,feral_canine,anthro_canine}).
|
94 |
-
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
|
95 |
-
the vector for a tag and the vectors for its aliases are all close together (because the model has seen them in similar contexts).
|
96 |
-
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.
|
97 |
-
|
98 |
-
To enhance the tag corrector further, we leverage conditional probabilities to refine our predictions.
|
99 |
-
Using the same 4 million post dataset, we calculate the conditional probability of each tag given the context of other tags appearing within the same document.
|
100 |
-
This is done by creating a co-occurrence matrix from our dataset, which records how frequently each pair of tags appears together across all documents.
|
101 |
-
By considering the context in which tags are used, we can now not only correct misspellings and rephrasings but also make more contextually relevant suggestions.
|
102 |
-
The "similarity weight" slider controls how much weight these conditional probabilities are given vs how much weight the FastText similarity model is given when suggesting replacements for invalid tags.
|
103 |
-
A similarity weight slider value of 0 means that only the FastText model's predictions will be used to calculate similarity scores, and a value of 1 means only the conditional probabilities are used (although the FastText model is still used to trim the list of candidates).
|
104 |
-
|
105 |
-
## How is the artist list calculated?
|
106 |
-
|
107 |
-
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.
|
108 |
-
Similarly, when you input a set of tags, the system creates a pseudo-document for your query out of all the tags.
|
109 |
-
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.
|
110 |
-
This method helps identify artists whose work is closely aligned with the themes or elements you're interested in.
|
111 |
-
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.
|
112 |
-
You can read more about TF-IDF on its [Wikipedia page](https://en.wikipedia.org/wiki/Tf%E2%80%93idf).
|
113 |
-
|
114 |
-
## How do the sample images work?
|
115 |
-
|
116 |
-
In the first row of galleries, for each artist in the dataset, we generated a sample image with the model Fluffyrock Unleashed using the prompt "by artist, soyjak, anthro, male, bust portrait, meme, grin" where "artist" is the name of an artist.
|
117 |
-
The simplicity of the prompt, the the simplicty of the default style, and the recognizability of the character make it easier to understand how artist names affect generated image styles.
|
118 |
-
The image on the left captioned "No Artist" was generated with the same prompt, but with no artist name.
|
119 |
-
You should compare all the images to the first to see how the artist names affect the output.
|
120 |
-
Each subsequent row of images was generated using the same process, but with a different prompt.
|
121 |
-
See SamplePrompts.csv for the list of prompts used and their descriptions.
|
122 |
-
"""
|
123 |
-
|
124 |
-
|
125 |
-
nsfw_threshold = 0.95 # Assuming the threshold value is defined here
|
126 |
-
|
127 |
-
css = """
|
128 |
-
.scrollable-content {
|
129 |
-
max-height: 500px;
|
130 |
-
overflow-y: auto;
|
131 |
-
}
|
132 |
-
"""
|
133 |
-
|
134 |
-
grammar=r"""
|
135 |
-
!start: (prompt | /[][():]/+)*
|
136 |
-
prompt: (emphasized | plain | comma | WHITESPACE)*
|
137 |
-
!emphasized: "(" prompt ")"
|
138 |
-
| "(" prompt ":" [WHITESPACE] NUMBER [WHITESPACE] ")"
|
139 |
-
comma: ","
|
140 |
-
WHITESPACE: /\s+/
|
141 |
-
plain: /([^,\\\[\]():|]|\\.)+/
|
142 |
-
%import common.SIGNED_NUMBER -> NUMBER
|
143 |
-
"""
|
144 |
-
|
145 |
-
# Initialize the parser
|
146 |
-
parser = Lark(grammar, start='start')
|
147 |
-
|
148 |
-
# Function to extract tags
|
149 |
-
def extract_tags(tree):
|
150 |
-
tags_with_positions = []
|
151 |
-
def _traverse(node):
|
152 |
-
if isinstance(node, Token) and node.type == '__ANON_1':
|
153 |
-
tag_position = node.start_pos
|
154 |
-
tag_text = node.value
|
155 |
-
tags_with_positions.append((tag_text, tag_position, "tag"))
|
156 |
-
elif not isinstance(node, Token):
|
157 |
-
for child in node.children:
|
158 |
-
_traverse(child)
|
159 |
-
_traverse(tree)
|
160 |
-
return tags_with_positions
|
161 |
-
|
162 |
-
|
163 |
-
special_tags = ["score:0", "score:1", "score:2", "score:3", "score:4", "score:5", "score:6", "score:7", "score:8", "score:9", "rating:s", "rating:q", "rating:e"]
|
164 |
-
def remove_special_tags(original_string):
|
165 |
-
tags = [tag.strip() for tag in original_string.split(",")]
|
166 |
-
remaining_tags = [tag for tag in tags if tag not in special_tags]
|
167 |
-
removed_tags = [tag for tag in tags if tag in special_tags]
|
168 |
-
return ", ".join(remaining_tags), removed_tags
|
169 |
-
|
170 |
-
|
171 |
-
# Define a function to load all necessary components
|
172 |
-
def load_model_components(file_path):
|
173 |
-
# Ensure the file path is a Path object for robust path handling
|
174 |
-
file_path = Path(file_path)
|
175 |
-
|
176 |
-
# Check if the file exists
|
177 |
-
if not file_path.is_file():
|
178 |
-
raise FileNotFoundError(f"The specified joblib file was not found: {file_path}")
|
179 |
-
|
180 |
-
# Load all the model components from the joblib file
|
181 |
-
model_components = joblib.load(file_path)
|
182 |
-
|
183 |
-
# Create a reverse mapping from row index to tag
|
184 |
-
if 'tag_to_row_index' in model_components:
|
185 |
-
model_components['row_to_tag'] = {idx: tag for tag, idx in model_components['tag_to_row_index'].items()}
|
186 |
-
|
187 |
-
return model_components
|
188 |
-
|
189 |
-
# Load all components at the start
|
190 |
-
tf_idf_components = load_model_components('tf_idf_files_420.joblib')
|
191 |
-
|
192 |
-
|
193 |
-
nsfw_tags = set() # Initialize an empty set to store words meeting the threshold
|
194 |
-
# Open and read the CSV file
|
195 |
-
with open("word_rating_probabilities.csv", 'r', newline='', encoding='utf-8') as csvfile:
|
196 |
-
reader = csv.reader(csvfile)
|
197 |
-
next(reader, None) # Skip the header row
|
198 |
-
for row in reader:
|
199 |
-
word = row[0] # The word is in the first column
|
200 |
-
probability_sum = float(row[1]) # The sum of probabilities is in the second column, convert to float for comparison
|
201 |
-
# Check if the probability sum meets the threshold and add the word to the set if it does
|
202 |
-
if probability_sum >= nsfw_threshold:
|
203 |
-
nsfw_tags.add(word)
|
204 |
-
|
205 |
-
|
206 |
-
# Read the set of valid artists into memory.
|
207 |
-
artist_set = set()
|
208 |
-
with open("fluffyrock_3m.csv", 'r', newline='', encoding='utf-8') as csvfile:
|
209 |
-
"""
|
210 |
-
Load artist names from a CSV file and store them in the global set.
|
211 |
-
Artist tags start with 'by_' and the prefix will be removed.
|
212 |
-
"""
|
213 |
-
reader = csv.reader(csvfile)
|
214 |
-
for row in reader:
|
215 |
-
tag_name = row[0] # Assuming the first column contains the tag names
|
216 |
-
if tag_name.startswith('by_'):
|
217 |
-
# Strip 'by_' from the start of the tag name and add to the set
|
218 |
-
artist_name = tag_name[3:] # Remove the first three characters 'by_'
|
219 |
-
artist_set.add(artist_name)
|
220 |
-
def is_artist(name):
|
221 |
-
return name in artist_set
|
222 |
-
|
223 |
-
|
224 |
-
sample_images_directory_path = 'sampleimages'
|
225 |
-
def generate_artist_image_tuples(top_artists, image_directory):
|
226 |
-
json_files = glob.glob(f'{image_directory}/*.json')
|
227 |
-
json_file_path = json_files[0] if json_files else None
|
228 |
-
with open(json_file_path, 'r') as json_file:
|
229 |
-
artist_to_file_map = json.load(json_file)
|
230 |
-
|
231 |
-
filename = artist_to_file_map.get("")
|
232 |
-
image_path = os.path.join(image_directory, filename)
|
233 |
-
if os.path.exists(image_path):
|
234 |
-
baseline_tuple = [(image_path, "No Artist")]
|
235 |
-
|
236 |
-
artist_image_tuples = []
|
237 |
-
for artist in top_artists:
|
238 |
-
filename = artist_to_file_map.get(artist)
|
239 |
-
if filename:
|
240 |
-
image_path = os.path.join(image_directory, filename)
|
241 |
-
if os.path.exists(image_path):
|
242 |
-
artist_image_tuples.append((image_path, artist if artist else "No Artist"))
|
243 |
-
|
244 |
-
return baseline_tuple, artist_image_tuples
|
245 |
-
|
246 |
-
|
247 |
-
def clean_tag(tag):
|
248 |
-
return ''.join(char for char in tag if ord(char) < 128)
|
249 |
-
|
250 |
-
|
251 |
-
#Normally returns tag to aliases, but when reverse=True, returns alias to tags
|
252 |
-
def build_aliases_dict(filename, reverse=False):
|
253 |
-
aliases_dict = {}
|
254 |
-
with open(filename, 'r', newline='', encoding='utf-8') as csvfile:
|
255 |
-
reader = csv.reader(csvfile)
|
256 |
-
for row in reader:
|
257 |
-
tag = clean_tag(row[0])
|
258 |
-
alias_list = [] if row[3] == "null" else [clean_tag(alias) for alias in row[3].split(',')]
|
259 |
-
if reverse:
|
260 |
-
for alias in alias_list:
|
261 |
-
aliases_dict.setdefault(alias, []).append(tag)
|
262 |
-
else:
|
263 |
-
aliases_dict[tag] = alias_list
|
264 |
-
return aliases_dict
|
265 |
-
|
266 |
-
|
267 |
-
def build_tag_count_dict(filename):
|
268 |
-
with open(filename, 'r', newline='', encoding='utf-8') as csvfile:
|
269 |
-
reader = csv.reader(csvfile)
|
270 |
-
result_dict = {}
|
271 |
-
for row in reader:
|
272 |
-
key = row[0]
|
273 |
-
value = int(row[2]) if row[2].isdigit() else None
|
274 |
-
if value is not None:
|
275 |
-
result_dict[key] = value
|
276 |
-
return result_dict
|
277 |
-
|
278 |
-
import csv
|
279 |
-
|
280 |
-
|
281 |
-
def build_tag_id_wiki_dict(filename='wiki_pages-2023-08-08.csv'):
|
282 |
-
"""
|
283 |
-
Reads a CSV file and returns a dictionary mapping tag names to tuples of
|
284 |
-
(number, most relevant line from the wiki entry). Rows with a non-integer in the first column are ignored.
|
285 |
-
The most relevant line is the first line that does not start with "thumb" and is not blank.
|
286 |
-
|
287 |
-
Parameters:
|
288 |
-
- filename: The path to the CSV file.
|
289 |
-
|
290 |
-
Returns:
|
291 |
-
- A dictionary where each key is a tag name and each value is a tuple (number, most relevant wiki entry line).
|
292 |
-
"""
|
293 |
-
tag_data = {}
|
294 |
-
with open(filename, 'r', encoding='utf-8') as csvfile:
|
295 |
-
reader = csv.reader(csvfile)
|
296 |
-
|
297 |
-
# Skip the header row
|
298 |
-
next(reader)
|
299 |
-
|
300 |
-
for row in reader:
|
301 |
-
try:
|
302 |
-
# Attempt to convert the first column to an integer
|
303 |
-
number = int(row[0])
|
304 |
-
except ValueError:
|
305 |
-
# If conversion fails, skip this row
|
306 |
-
continue
|
307 |
-
|
308 |
-
tag = row[3]
|
309 |
-
wiki_entry_full = row[4]
|
310 |
-
|
311 |
-
# Process the wiki_entry to find the most relevant line
|
312 |
-
relevant_line = ''
|
313 |
-
for line in wiki_entry_full.split('\n'):
|
314 |
-
if line.strip() and not line.startswith("thumb"):
|
315 |
-
relevant_line = line
|
316 |
-
break
|
317 |
-
|
318 |
-
# Map the tag to a tuple of (number, relevant_line)
|
319 |
-
tag_data[tag] = (number, relevant_line)
|
320 |
-
|
321 |
-
return tag_data
|
322 |
-
|
323 |
-
|
324 |
-
def create_html_tables_for_tags(subtable_heading, word_similarity_tuples, tag2count, tag2idwiki):
|
325 |
-
# Wrap the tag part in a <span> with styles for bold and larger font
|
326 |
-
html_str = f"<div style='display: inline-block; margin: 20px; vertical-align: top;'><table><thead><tr><th colspan='3' style='text-align: center; padding-bottom: 10px;'><span style='font-weight: bold; font-size: 20px;'>{subtable_heading}</span></th></tr></thead><tbody><tr style='border-bottom: 1px solid #000;'><th>
|
327 |
-
# Loop through the results and add table rows for each
|
328 |
-
for word, sim in word_similarity_tuples:
|
329 |
-
word_with_underscores = word.replace(' ', '_')
|
330 |
-
word_with_escaped_parentheses = word.replace("\\(", "(").replace("\\)", ")").replace("(", "\\(").replace(")", "\\)")
|
331 |
-
count = tag2count.get(word_with_underscores.replace("\\(", "(").replace("\\)", ")"), 0) # Get the count if available, otherwise default to 0
|
332 |
-
tag_id, wiki_entry = tag2idwiki.get(word_with_underscores, (None, ''))
|
333 |
-
# Check if tag_id and wiki_entry are valid
|
334 |
-
if tag_id is not None and wiki_entry:
|
335 |
-
# Construct the URL for the tag's wiki page
|
336 |
-
wiki_url = f"https://e621.net/wiki_pages/{tag_id}"
|
337 |
-
# Make the tag a hyperlink with a tooltip
|
338 |
-
tag_element = f"<a href='{wiki_url}' target='_blank' title='{wiki_entry}'>{word_with_escaped_parentheses}</a>"
|
339 |
-
else:
|
340 |
-
# Display the word without any hyperlink or tooltip
|
341 |
-
tag_element = word_with_escaped_parentheses
|
342 |
-
# Include the tag element in the table row
|
343 |
-
html_str += f"<tr><td style='border: none; padding: 5px; height: 20px;'>{tag_element}</td><td style='border: none; padding: 5px; height: 20px;'>{round(sim, 3)}</td><td style='border: none; padding: 5px; height: 20px;'>{count}</td></tr>"
|
344 |
-
|
345 |
-
html_str += "</tbody></table></div>"
|
346 |
-
return html_str
|
347 |
-
|
348 |
-
|
349 |
-
def create_top_artists_table(top_artists):
|
350 |
-
# Add a heading above the table
|
351 |
-
html_str = "<div class=\"scrollable-content\" style='display: inline-block; margin: 20px; text-align: center;'>"
|
352 |
-
html_str += "<h1>Top Artists</h1>" # Heading for the table
|
353 |
-
# Start the table with increased font size and no borders between rows
|
354 |
-
html_str += "<table style='font-size: 20px; border-collapse: collapse;'>"
|
355 |
-
html_str += "<thead><tr><th>Artist</th><th>Similarity</th></tr></thead><tbody>"
|
356 |
-
# Loop through the top artists and add a row for each without the rank and without borders between rows
|
357 |
-
for artist, score in top_artists:
|
358 |
-
artist_name = artist[3:] if artist.startswith("by ") else artist # Remove "by " prefix
|
359 |
-
similarity_percentage = "{:.1f}%".format(score * 100) # Convert score to percentage string with one decimal
|
360 |
-
html_str += f"<td style='padding: 3px 20px; border: none;'>{artist_name}</td><td style='padding: 3px 20px; border: none;'>{similarity_percentage}</td></tr>"
|
361 |
-
|
362 |
-
# Close the table HTML
|
363 |
-
html_str += "</tbody></table></div>"
|
364 |
-
|
365 |
-
return html_str
|
366 |
-
|
367 |
-
|
368 |
-
def construct_pseudo_vector(pseudo_doc_terms, idf_loaded, tag_to_row_loaded):
|
369 |
-
# Initialize a vector of zeros with the length of the term_to_index mapping
|
370 |
-
pseudo_vector = np.zeros(len(tag_to_row_loaded))
|
371 |
-
|
372 |
-
# Fill in the vector for terms in the pseudo document
|
373 |
-
for term in pseudo_doc_terms:
|
374 |
-
if term in tag_to_row_loaded:
|
375 |
-
index = tag_to_row_loaded[term]
|
376 |
-
pseudo_vector[index] = idf_loaded.get(term, 0)
|
377 |
-
|
378 |
-
# Return the vector as a 2D array for compatibility with SVD transform
|
379 |
-
return pseudo_vector.reshape(1, -1)
|
380 |
-
|
381 |
-
|
382 |
-
def get_top_indices(reduced_pseudo_vector, reduced_matrix):
|
383 |
-
# Compute cosine similarities
|
384 |
-
similarities = cosine_similarity(reduced_pseudo_vector, reduced_matrix).flatten()
|
385 |
-
|
386 |
-
# Get sorted tag indices based on similarities, in descending order
|
387 |
-
sorted_indices = np.argsort(-similarities)
|
388 |
-
|
389 |
-
# Return the top N indices
|
390 |
-
return sorted_indices
|
391 |
-
|
392 |
-
|
393 |
-
def get_tfidf_reduced_similar_tags(pseudo_doc_terms, allow_nsfw_tags):
|
394 |
-
idf = tf_idf_components['idf']
|
395 |
-
term_to_column_index = tf_idf_components['tag_to_column_index']
|
396 |
-
row_to_tag = tf_idf_components['row_to_tag']
|
397 |
-
reduced_matrix = tf_idf_components['reduced_matrix']
|
398 |
-
svd = tf_idf_components['svd_model']
|
399 |
-
|
400 |
-
# Construct the TF-IDF vector
|
401 |
-
pseudo_tfidf_vector = construct_pseudo_vector(pseudo_doc_terms, idf, term_to_column_index)
|
402 |
-
|
403 |
-
# Reduce the dimensionality of the pseudo-document vector for the reduced matrix
|
404 |
-
reduced_pseudo_vector = svd.transform(pseudo_tfidf_vector)
|
405 |
-
|
406 |
-
# Compute cosine similarities in the reduced space
|
407 |
-
cosine_similarities_reduced = cosine_similarity(reduced_pseudo_vector, reduced_matrix).flatten()
|
408 |
-
|
409 |
-
# Sort the indices by descending cosine similarity
|
410 |
-
top_indices_reduced = np.argsort(cosine_similarities_reduced)
|
411 |
-
|
412 |
-
# Map indices to tags with their similarities
|
413 |
-
tag_similarity_dict = {row_to_tag[i]: cosine_similarities_reduced[i] for i in top_indices_reduced if i in row_to_tag}
|
414 |
-
|
415 |
-
if not allow_nsfw_tags:
|
416 |
-
tag_similarity_dict = {tag: sim for tag, sim in tag_similarity_dict.items() if tag not in nsfw_tags}
|
417 |
-
|
418 |
-
tag_similarity_dict = {"by " + tag if is_artist(tag) else tag: sim for tag, sim in tag_similarity_dict.items()}
|
419 |
-
|
420 |
-
# Sort and transform tag names
|
421 |
-
sorted_tag_similarity_dict = OrderedDict(sorted(tag_similarity_dict.items(), key=lambda x: x[1], reverse=True))
|
422 |
-
transformed_sorted_tag_similarity_dict = OrderedDict(
|
423 |
-
(key.replace('_', ' ').replace('(', '\\(').replace(')', '\\)'), value)
|
424 |
-
for key, value in sorted_tag_similarity_dict.items()
|
425 |
-
)
|
426 |
-
|
427 |
-
return transformed_sorted_tag_similarity_dict
|
428 |
-
|
429 |
-
|
430 |
-
def create_html_placeholder(title="", content="", placeholder_height=400, placeholder_width="100%"):
|
431 |
-
# Include a title in the same style as the top artists table heading
|
432 |
-
html_placeholder = f"<div class=\"scrollable-content\" style='text-align: center;'><h1>{title}</h1></div>"
|
433 |
-
# Conditionally add content if present
|
434 |
-
if content:
|
435 |
-
html_placeholder += f"<div style='text-align: center; margin-bottom: 20px;'><p>{content}</p></div>"
|
436 |
-
# Add the placeholder div with specified height and width
|
437 |
-
html_placeholder += f"<div style='height: {placeholder_height}px; width: {placeholder_width}; margin: 20px auto; background: transparent;'></div>"
|
438 |
-
return html_placeholder
|
439 |
-
|
440 |
-
|
441 |
-
def find_similar_tags(test_tags, tag_to_context_similarity, context_similarity_weight, allow_nsfw_tags):
|
442 |
-
#Initialize stuff
|
443 |
-
if not hasattr(find_similar_tags, "fasttext_small_model"):
|
444 |
-
find_similar_tags.fasttext_small_model = compress_fasttext.models.CompressedFastTextKeyedVectors.load('e621FastTextModel010Replacement_small.bin')
|
445 |
-
tag_aliases_file = 'fluffyrock_3m.csv'
|
446 |
-
if not hasattr(find_similar_tags, "tag2aliases"):
|
447 |
-
find_similar_tags.tag2aliases = build_aliases_dict(tag_aliases_file)
|
448 |
-
if not hasattr(find_similar_tags, "alias2tags"):
|
449 |
-
find_similar_tags.alias2tags = build_aliases_dict(tag_aliases_file, reverse=True)
|
450 |
-
if not hasattr(find_similar_tags, "tag2count"):
|
451 |
-
find_similar_tags.tag2count = build_tag_count_dict(tag_aliases_file)
|
452 |
-
if not hasattr(find_similar_tags, "tag2idwiki"):
|
453 |
-
find_similar_tags.tag2idwiki = build_tag_id_wiki_dict()
|
454 |
-
|
455 |
-
modified_tags = [tag_info['modified_tag'] for tag_info in test_tags]
|
456 |
-
transformed_tags = [tag.replace(' ', '_') for tag in modified_tags]
|
457 |
-
|
458 |
-
# Find similar tags and prepare data for tables
|
459 |
-
html_content = "<div class=\"scrollable-content\" style='display: inline-block; margin: 20px; text-align: center;'>"
|
460 |
-
html_content += "<h1>Unknown Tags</h1>" # Heading for the table
|
461 |
-
tags_added = False
|
462 |
-
bad_entities = []
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
index = match.start(1)
|
573 |
-
bad_entities.append({"entity":
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
#
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
3 |
+
from scipy.sparse import csr_matrix
|
4 |
+
import numpy as np
|
5 |
+
import joblib
|
6 |
+
from joblib import load
|
7 |
+
import h5py
|
8 |
+
from io import BytesIO
|
9 |
+
import csv
|
10 |
+
import re
|
11 |
+
import random
|
12 |
+
import compress_fasttext
|
13 |
+
from collections import OrderedDict
|
14 |
+
from lark import Lark, Tree, Token
|
15 |
+
from lark.exceptions import ParseError
|
16 |
+
import json
|
17 |
+
import zipfile
|
18 |
+
from PIL import Image
|
19 |
+
import io
|
20 |
+
import os
|
21 |
+
import glob
|
22 |
+
import itertools
|
23 |
+
from itertools import islice
|
24 |
+
from pathlib import Path
|
25 |
+
import logging
|
26 |
+
|
27 |
+
# Set up logging
|
28 |
+
logging.basicConfig(filename='error.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s')
|
29 |
+
|
30 |
+
|
31 |
+
faq_content="""
|
32 |
+
#4-20-2024 Why aren't there example images for most artists?
|
33 |
+
|
34 |
+
We recently updated the underlying data used to calculate the Suggested Artists section.
|
35 |
+
We have not yet generated example images for all the new artists.
|
36 |
+
|
37 |
+
# Questions:
|
38 |
+
|
39 |
+
## What is the purpose of this tool?
|
40 |
+
|
41 |
+
Since Stable Diffusion's initial release in 2022, users have developed a myriad of fine-tuned text to image models, each with unique "linguistic" preferences depending on the data from which it was fine-tuned.
|
42 |
+
Some models react best when prompted with verbose scene descriptions akin to DALL-E, while others fine-tuned on images scraped from popular image boards understand those boards' tag sets.
|
43 |
+
This tool serves as a linguistic bridge to the e621 image board tag lexicon, on which many popular models such as Fluffyrock, Fluffusion, and Pony Diffusion v6 were trained.
|
44 |
+
|
45 |
+
When you enter a txt2img prompt and press the "submit" button, Prompt Squirrel parses your prompt and checks that all your tags are valid e621 tags.
|
46 |
+
If it finds any that are not, it recommends some valid e621 tags you can use to replace them in the "Unknown Tags" section.
|
47 |
+
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.
|
48 |
+
This is useful to align your prompt with the expected input to an e621-trained model.
|
49 |
+
|
50 |
+
## Does input order matter?
|
51 |
+
|
52 |
+
No
|
53 |
+
|
54 |
+
## Should I use underscores or spaces in the input tags?
|
55 |
+
|
56 |
+
As a rule, e621-trained models replace underscores in tags with spaces, so spaces are preferred.
|
57 |
+
|
58 |
+
## Can I use parentheses or weights as in the Stable Diffusion Automatic1111 WebUI?
|
59 |
+
|
60 |
+
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.
|
61 |
+
An example that illustrates acceptable parentheses and weight formatting is:
|
62 |
+
((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)
|
63 |
+
|
64 |
+
## Why are some valid tags marked as "unknown", and why don't some artists ever get returned?
|
65 |
+
|
66 |
+
Some data is excluded from consideration if it did not occur frequently enough in the sample from which the application makes its calculations.
|
67 |
+
If an artist or tag is too infrequent, we might not think we have enough data to make predictions about it.
|
68 |
+
|
69 |
+
## Why do some suggested tags not have summaries or wiki links?
|
70 |
+
|
71 |
+
Both of these features are extracted from the tag wiki pages, but some valid e621 tags do not have wiki pages.
|
72 |
+
|
73 |
+
## Are there any special tags?
|
74 |
+
|
75 |
+
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.
|
76 |
+
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"
|
77 |
+
in your list to bias the output toward artists with higher or lower scoring images.
|
78 |
+
|
79 |
+
## Are there any other special tricks?
|
80 |
+
|
81 |
+
Yes. If you want to more strongly bias the artist output toward a specific tag, you can just list it multiple times.
|
82 |
+
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"
|
83 |
+
than the query "red fox, score:7".
|
84 |
+
|
85 |
+
## Why is this space tagged "not-for-all-audience"
|
86 |
+
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.
|
87 |
+
The app will try not to display nsfw tags unless the "Allow NSFW Tags" is checked, but the filter is not perfect.
|
88 |
+
|
89 |
+
## How does the tag corrector work?
|
90 |
+
|
91 |
+
We collect the tag sets from over 4 million e621 posts, treating the tag set from each image as an individual document.
|
92 |
+
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
|
93 |
+
(e.g. "canine" gets replaced with one of {k9,canines,mongrel,cannine,cnaine,feral_canine,anthro_canine}).
|
94 |
+
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
|
95 |
+
the vector for a tag and the vectors for its aliases are all close together (because the model has seen them in similar contexts).
|
96 |
+
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.
|
97 |
+
|
98 |
+
To enhance the tag corrector further, we leverage conditional probabilities to refine our predictions.
|
99 |
+
Using the same 4 million post dataset, we calculate the conditional probability of each tag given the context of other tags appearing within the same document.
|
100 |
+
This is done by creating a co-occurrence matrix from our dataset, which records how frequently each pair of tags appears together across all documents.
|
101 |
+
By considering the context in which tags are used, we can now not only correct misspellings and rephrasings but also make more contextually relevant suggestions.
|
102 |
+
The "similarity weight" slider controls how much weight these conditional probabilities are given vs how much weight the FastText similarity model is given when suggesting replacements for invalid tags.
|
103 |
+
A similarity weight slider value of 0 means that only the FastText model's predictions will be used to calculate similarity scores, and a value of 1 means only the conditional probabilities are used (although the FastText model is still used to trim the list of candidates).
|
104 |
+
|
105 |
+
## How is the artist list calculated?
|
106 |
+
|
107 |
+
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.
|
108 |
+
Similarly, when you input a set of tags, the system creates a pseudo-document for your query out of all the tags.
|
109 |
+
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.
|
110 |
+
This method helps identify artists whose work is closely aligned with the themes or elements you're interested in.
|
111 |
+
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.
|
112 |
+
You can read more about TF-IDF on its [Wikipedia page](https://en.wikipedia.org/wiki/Tf%E2%80%93idf).
|
113 |
+
|
114 |
+
## How do the sample images work?
|
115 |
+
|
116 |
+
In the first row of galleries, for each artist in the dataset, we generated a sample image with the model Fluffyrock Unleashed using the prompt "by artist, soyjak, anthro, male, bust portrait, meme, grin" where "artist" is the name of an artist.
|
117 |
+
The simplicity of the prompt, the the simplicty of the default style, and the recognizability of the character make it easier to understand how artist names affect generated image styles.
|
118 |
+
The image on the left captioned "No Artist" was generated with the same prompt, but with no artist name.
|
119 |
+
You should compare all the images to the first to see how the artist names affect the output.
|
120 |
+
Each subsequent row of images was generated using the same process, but with a different prompt.
|
121 |
+
See SamplePrompts.csv for the list of prompts used and their descriptions.
|
122 |
+
"""
|
123 |
+
|
124 |
+
|
125 |
+
nsfw_threshold = 0.95 # Assuming the threshold value is defined here
|
126 |
+
|
127 |
+
css = """
|
128 |
+
.scrollable-content {
|
129 |
+
max-height: 500px;
|
130 |
+
overflow-y: auto;
|
131 |
+
}
|
132 |
+
"""
|
133 |
+
|
134 |
+
grammar=r"""
|
135 |
+
!start: (prompt | /[][():]/+)*
|
136 |
+
prompt: (emphasized | plain | comma | WHITESPACE)*
|
137 |
+
!emphasized: "(" prompt ")"
|
138 |
+
| "(" prompt ":" [WHITESPACE] NUMBER [WHITESPACE] ")"
|
139 |
+
comma: ","
|
140 |
+
WHITESPACE: /\s+/
|
141 |
+
plain: /([^,\\\[\]():|]|\\.)+/
|
142 |
+
%import common.SIGNED_NUMBER -> NUMBER
|
143 |
+
"""
|
144 |
+
|
145 |
+
# Initialize the parser
|
146 |
+
parser = Lark(grammar, start='start')
|
147 |
+
|
148 |
+
# Function to extract tags
|
149 |
+
def extract_tags(tree):
|
150 |
+
tags_with_positions = []
|
151 |
+
def _traverse(node):
|
152 |
+
if isinstance(node, Token) and node.type == '__ANON_1':
|
153 |
+
tag_position = node.start_pos
|
154 |
+
tag_text = node.value
|
155 |
+
tags_with_positions.append((tag_text, tag_position, "tag"))
|
156 |
+
elif not isinstance(node, Token):
|
157 |
+
for child in node.children:
|
158 |
+
_traverse(child)
|
159 |
+
_traverse(tree)
|
160 |
+
return tags_with_positions
|
161 |
+
|
162 |
+
|
163 |
+
special_tags = ["score:0", "score:1", "score:2", "score:3", "score:4", "score:5", "score:6", "score:7", "score:8", "score:9", "rating:s", "rating:q", "rating:e"]
|
164 |
+
def remove_special_tags(original_string):
|
165 |
+
tags = [tag.strip() for tag in original_string.split(",")]
|
166 |
+
remaining_tags = [tag for tag in tags if tag not in special_tags]
|
167 |
+
removed_tags = [tag for tag in tags if tag in special_tags]
|
168 |
+
return ", ".join(remaining_tags), removed_tags
|
169 |
+
|
170 |
+
|
171 |
+
# Define a function to load all necessary components
|
172 |
+
def load_model_components(file_path):
|
173 |
+
# Ensure the file path is a Path object for robust path handling
|
174 |
+
file_path = Path(file_path)
|
175 |
+
|
176 |
+
# Check if the file exists
|
177 |
+
if not file_path.is_file():
|
178 |
+
raise FileNotFoundError(f"The specified joblib file was not found: {file_path}")
|
179 |
+
|
180 |
+
# Load all the model components from the joblib file
|
181 |
+
model_components = joblib.load(file_path)
|
182 |
+
|
183 |
+
# Create a reverse mapping from row index to tag
|
184 |
+
if 'tag_to_row_index' in model_components:
|
185 |
+
model_components['row_to_tag'] = {idx: tag for tag, idx in model_components['tag_to_row_index'].items()}
|
186 |
+
|
187 |
+
return model_components
|
188 |
+
|
189 |
+
# Load all components at the start
|
190 |
+
tf_idf_components = load_model_components('tf_idf_files_420.joblib')
|
191 |
+
|
192 |
+
|
193 |
+
nsfw_tags = set() # Initialize an empty set to store words meeting the threshold
|
194 |
+
# Open and read the CSV file
|
195 |
+
with open("word_rating_probabilities.csv", 'r', newline='', encoding='utf-8') as csvfile:
|
196 |
+
reader = csv.reader(csvfile)
|
197 |
+
next(reader, None) # Skip the header row
|
198 |
+
for row in reader:
|
199 |
+
word = row[0] # The word is in the first column
|
200 |
+
probability_sum = float(row[1]) # The sum of probabilities is in the second column, convert to float for comparison
|
201 |
+
# Check if the probability sum meets the threshold and add the word to the set if it does
|
202 |
+
if probability_sum >= nsfw_threshold:
|
203 |
+
nsfw_tags.add(word)
|
204 |
+
|
205 |
+
|
206 |
+
# Read the set of valid artists into memory.
|
207 |
+
artist_set = set()
|
208 |
+
with open("fluffyrock_3m.csv", 'r', newline='', encoding='utf-8') as csvfile:
|
209 |
+
"""
|
210 |
+
Load artist names from a CSV file and store them in the global set.
|
211 |
+
Artist tags start with 'by_' and the prefix will be removed.
|
212 |
+
"""
|
213 |
+
reader = csv.reader(csvfile)
|
214 |
+
for row in reader:
|
215 |
+
tag_name = row[0] # Assuming the first column contains the tag names
|
216 |
+
if tag_name.startswith('by_'):
|
217 |
+
# Strip 'by_' from the start of the tag name and add to the set
|
218 |
+
artist_name = tag_name[3:] # Remove the first three characters 'by_'
|
219 |
+
artist_set.add(artist_name)
|
220 |
+
def is_artist(name):
|
221 |
+
return name in artist_set
|
222 |
+
|
223 |
+
|
224 |
+
sample_images_directory_path = 'sampleimages'
|
225 |
+
def generate_artist_image_tuples(top_artists, image_directory):
|
226 |
+
json_files = glob.glob(f'{image_directory}/*.json')
|
227 |
+
json_file_path = json_files[0] if json_files else None
|
228 |
+
with open(json_file_path, 'r') as json_file:
|
229 |
+
artist_to_file_map = json.load(json_file)
|
230 |
+
|
231 |
+
filename = artist_to_file_map.get("")
|
232 |
+
image_path = os.path.join(image_directory, filename)
|
233 |
+
if os.path.exists(image_path):
|
234 |
+
baseline_tuple = [(image_path, "No Artist")]
|
235 |
+
|
236 |
+
artist_image_tuples = []
|
237 |
+
for artist in top_artists:
|
238 |
+
filename = artist_to_file_map.get(artist)
|
239 |
+
if filename:
|
240 |
+
image_path = os.path.join(image_directory, filename)
|
241 |
+
if os.path.exists(image_path):
|
242 |
+
artist_image_tuples.append((image_path, artist if artist else "No Artist"))
|
243 |
+
|
244 |
+
return baseline_tuple, artist_image_tuples
|
245 |
+
|
246 |
+
|
247 |
+
def clean_tag(tag):
|
248 |
+
return ''.join(char for char in tag if ord(char) < 128)
|
249 |
+
|
250 |
+
|
251 |
+
#Normally returns tag to aliases, but when reverse=True, returns alias to tags
|
252 |
+
def build_aliases_dict(filename, reverse=False):
|
253 |
+
aliases_dict = {}
|
254 |
+
with open(filename, 'r', newline='', encoding='utf-8') as csvfile:
|
255 |
+
reader = csv.reader(csvfile)
|
256 |
+
for row in reader:
|
257 |
+
tag = clean_tag(row[0])
|
258 |
+
alias_list = [] if row[3] == "null" else [clean_tag(alias) for alias in row[3].split(',')]
|
259 |
+
if reverse:
|
260 |
+
for alias in alias_list:
|
261 |
+
aliases_dict.setdefault(alias, []).append(tag)
|
262 |
+
else:
|
263 |
+
aliases_dict[tag] = alias_list
|
264 |
+
return aliases_dict
|
265 |
+
|
266 |
+
|
267 |
+
def build_tag_count_dict(filename):
|
268 |
+
with open(filename, 'r', newline='', encoding='utf-8') as csvfile:
|
269 |
+
reader = csv.reader(csvfile)
|
270 |
+
result_dict = {}
|
271 |
+
for row in reader:
|
272 |
+
key = row[0]
|
273 |
+
value = int(row[2]) if row[2].isdigit() else None
|
274 |
+
if value is not None:
|
275 |
+
result_dict[key] = value
|
276 |
+
return result_dict
|
277 |
+
|
278 |
+
import csv
|
279 |
+
|
280 |
+
|
281 |
+
def build_tag_id_wiki_dict(filename='wiki_pages-2023-08-08.csv'):
|
282 |
+
"""
|
283 |
+
Reads a CSV file and returns a dictionary mapping tag names to tuples of
|
284 |
+
(number, most relevant line from the wiki entry). Rows with a non-integer in the first column are ignored.
|
285 |
+
The most relevant line is the first line that does not start with "thumb" and is not blank.
|
286 |
+
|
287 |
+
Parameters:
|
288 |
+
- filename: The path to the CSV file.
|
289 |
+
|
290 |
+
Returns:
|
291 |
+
- A dictionary where each key is a tag name and each value is a tuple (number, most relevant wiki entry line).
|
292 |
+
"""
|
293 |
+
tag_data = {}
|
294 |
+
with open(filename, 'r', encoding='utf-8') as csvfile:
|
295 |
+
reader = csv.reader(csvfile)
|
296 |
+
|
297 |
+
# Skip the header row
|
298 |
+
next(reader)
|
299 |
+
|
300 |
+
for row in reader:
|
301 |
+
try:
|
302 |
+
# Attempt to convert the first column to an integer
|
303 |
+
number = int(row[0])
|
304 |
+
except ValueError:
|
305 |
+
# If conversion fails, skip this row
|
306 |
+
continue
|
307 |
+
|
308 |
+
tag = row[3]
|
309 |
+
wiki_entry_full = row[4]
|
310 |
+
|
311 |
+
# Process the wiki_entry to find the most relevant line
|
312 |
+
relevant_line = ''
|
313 |
+
for line in wiki_entry_full.split('\n'):
|
314 |
+
if line.strip() and not line.startswith("thumb"):
|
315 |
+
relevant_line = line
|
316 |
+
break
|
317 |
+
|
318 |
+
# Map the tag to a tuple of (number, relevant_line)
|
319 |
+
tag_data[tag] = (number, relevant_line)
|
320 |
+
|
321 |
+
return tag_data
|
322 |
+
|
323 |
+
|
324 |
+
def create_html_tables_for_tags(subtable_heading, item_heading, word_similarity_tuples, tag2count, tag2idwiki):
|
325 |
+
# Wrap the tag part in a <span> with styles for bold and larger font
|
326 |
+
html_str = f"<div style='display: inline-block; margin: 20px; vertical-align: top;'><table><thead><tr><th colspan='3' style='text-align: center; padding-bottom: 10px;'><span style='font-weight: bold; font-size: 20px;'>{subtable_heading}</span></th></tr></thead><tbody><tr style='border-bottom: 1px solid #000;'><th>{item_heading}</th><th>Similarity</th><th>Count</th></tr>"
|
327 |
+
# Loop through the results and add table rows for each
|
328 |
+
for word, sim in word_similarity_tuples:
|
329 |
+
word_with_underscores = word.replace(' ', '_')
|
330 |
+
word_with_escaped_parentheses = word.replace("\\(", "(").replace("\\)", ")").replace("(", "\\(").replace(")", "\\)")
|
331 |
+
count = tag2count.get(word_with_underscores.replace("\\(", "(").replace("\\)", ")"), 0) # Get the count if available, otherwise default to 0
|
332 |
+
tag_id, wiki_entry = tag2idwiki.get(word_with_underscores, (None, ''))
|
333 |
+
# Check if tag_id and wiki_entry are valid
|
334 |
+
if tag_id is not None and wiki_entry:
|
335 |
+
# Construct the URL for the tag's wiki page
|
336 |
+
wiki_url = f"https://e621.net/wiki_pages/{tag_id}"
|
337 |
+
# Make the tag a hyperlink with a tooltip
|
338 |
+
tag_element = f"<a href='{wiki_url}' target='_blank' title='{wiki_entry}'>{word_with_escaped_parentheses}</a>"
|
339 |
+
else:
|
340 |
+
# Display the word without any hyperlink or tooltip
|
341 |
+
tag_element = word_with_escaped_parentheses
|
342 |
+
# Include the tag element in the table row
|
343 |
+
html_str += f"<tr><td style='border: none; padding: 5px; height: 20px;'>{tag_element}</td><td style='border: none; padding: 5px; height: 20px;'>{round(sim, 3)}</td><td style='border: none; padding: 5px; height: 20px;'>{count}</td></tr>"
|
344 |
+
|
345 |
+
html_str += "</tbody></table></div>"
|
346 |
+
return html_str
|
347 |
+
|
348 |
+
|
349 |
+
def create_top_artists_table(top_artists):
|
350 |
+
# Add a heading above the table
|
351 |
+
html_str = "<div class=\"scrollable-content\" style='display: inline-block; margin: 20px; text-align: center;'>"
|
352 |
+
html_str += "<h1>Top Artists</h1>" # Heading for the table
|
353 |
+
# Start the table with increased font size and no borders between rows
|
354 |
+
html_str += "<table style='font-size: 20px; border-collapse: collapse;'>"
|
355 |
+
html_str += "<thead><tr><th>Artist</th><th>Similarity</th></tr></thead><tbody>"
|
356 |
+
# Loop through the top artists and add a row for each without the rank and without borders between rows
|
357 |
+
for artist, score in top_artists:
|
358 |
+
artist_name = artist[3:] if artist.startswith("by ") else artist # Remove "by " prefix
|
359 |
+
similarity_percentage = "{:.1f}%".format(score * 100) # Convert score to percentage string with one decimal
|
360 |
+
html_str += f"<td style='padding: 3px 20px; border: none;'>{artist_name}</td><td style='padding: 3px 20px; border: none;'>{similarity_percentage}</td></tr>"
|
361 |
+
|
362 |
+
# Close the table HTML
|
363 |
+
html_str += "</tbody></table></div>"
|
364 |
+
|
365 |
+
return html_str
|
366 |
+
|
367 |
+
|
368 |
+
def construct_pseudo_vector(pseudo_doc_terms, idf_loaded, tag_to_row_loaded):
|
369 |
+
# Initialize a vector of zeros with the length of the term_to_index mapping
|
370 |
+
pseudo_vector = np.zeros(len(tag_to_row_loaded))
|
371 |
+
|
372 |
+
# Fill in the vector for terms in the pseudo document
|
373 |
+
for term in pseudo_doc_terms:
|
374 |
+
if term in tag_to_row_loaded:
|
375 |
+
index = tag_to_row_loaded[term]
|
376 |
+
pseudo_vector[index] = idf_loaded.get(term, 0)
|
377 |
+
|
378 |
+
# Return the vector as a 2D array for compatibility with SVD transform
|
379 |
+
return pseudo_vector.reshape(1, -1)
|
380 |
+
|
381 |
+
|
382 |
+
def get_top_indices(reduced_pseudo_vector, reduced_matrix):
|
383 |
+
# Compute cosine similarities
|
384 |
+
similarities = cosine_similarity(reduced_pseudo_vector, reduced_matrix).flatten()
|
385 |
+
|
386 |
+
# Get sorted tag indices based on similarities, in descending order
|
387 |
+
sorted_indices = np.argsort(-similarities)
|
388 |
+
|
389 |
+
# Return the top N indices
|
390 |
+
return sorted_indices
|
391 |
+
|
392 |
+
|
393 |
+
def get_tfidf_reduced_similar_tags(pseudo_doc_terms, allow_nsfw_tags):
|
394 |
+
idf = tf_idf_components['idf']
|
395 |
+
term_to_column_index = tf_idf_components['tag_to_column_index']
|
396 |
+
row_to_tag = tf_idf_components['row_to_tag']
|
397 |
+
reduced_matrix = tf_idf_components['reduced_matrix']
|
398 |
+
svd = tf_idf_components['svd_model']
|
399 |
+
|
400 |
+
# Construct the TF-IDF vector
|
401 |
+
pseudo_tfidf_vector = construct_pseudo_vector(pseudo_doc_terms, idf, term_to_column_index)
|
402 |
+
|
403 |
+
# Reduce the dimensionality of the pseudo-document vector for the reduced matrix
|
404 |
+
reduced_pseudo_vector = svd.transform(pseudo_tfidf_vector)
|
405 |
+
|
406 |
+
# Compute cosine similarities in the reduced space
|
407 |
+
cosine_similarities_reduced = cosine_similarity(reduced_pseudo_vector, reduced_matrix).flatten()
|
408 |
+
|
409 |
+
# Sort the indices by descending cosine similarity
|
410 |
+
top_indices_reduced = np.argsort(cosine_similarities_reduced)
|
411 |
+
|
412 |
+
# Map indices to tags with their similarities
|
413 |
+
tag_similarity_dict = {row_to_tag[i]: cosine_similarities_reduced[i] for i in top_indices_reduced if i in row_to_tag}
|
414 |
+
|
415 |
+
if not allow_nsfw_tags:
|
416 |
+
tag_similarity_dict = {tag: sim for tag, sim in tag_similarity_dict.items() if tag not in nsfw_tags}
|
417 |
+
|
418 |
+
tag_similarity_dict = {"by " + tag if is_artist(tag) else tag: sim for tag, sim in tag_similarity_dict.items()}
|
419 |
+
|
420 |
+
# Sort and transform tag names
|
421 |
+
sorted_tag_similarity_dict = OrderedDict(sorted(tag_similarity_dict.items(), key=lambda x: x[1], reverse=True))
|
422 |
+
transformed_sorted_tag_similarity_dict = OrderedDict(
|
423 |
+
(key.replace('_', ' ').replace('(', '\\(').replace(')', '\\)'), value)
|
424 |
+
for key, value in sorted_tag_similarity_dict.items()
|
425 |
+
)
|
426 |
+
|
427 |
+
return transformed_sorted_tag_similarity_dict
|
428 |
+
|
429 |
+
|
430 |
+
def create_html_placeholder(title="", content="", placeholder_height=400, placeholder_width="100%"):
|
431 |
+
# Include a title in the same style as the top artists table heading
|
432 |
+
html_placeholder = f"<div class=\"scrollable-content\" style='text-align: center;'><h1>{title}</h1></div>"
|
433 |
+
# Conditionally add content if present
|
434 |
+
if content:
|
435 |
+
html_placeholder += f"<div style='text-align: center; margin-bottom: 20px;'><p>{content}</p></div>"
|
436 |
+
# Add the placeholder div with specified height and width
|
437 |
+
html_placeholder += f"<div style='height: {placeholder_height}px; width: {placeholder_width}; margin: 20px auto; background: transparent;'></div>"
|
438 |
+
return html_placeholder
|
439 |
+
|
440 |
+
|
441 |
+
def find_similar_tags(test_tags, tag_to_context_similarity, context_similarity_weight, allow_nsfw_tags):
|
442 |
+
#Initialize stuff
|
443 |
+
if not hasattr(find_similar_tags, "fasttext_small_model"):
|
444 |
+
find_similar_tags.fasttext_small_model = compress_fasttext.models.CompressedFastTextKeyedVectors.load('e621FastTextModel010Replacement_small.bin')
|
445 |
+
tag_aliases_file = 'fluffyrock_3m.csv'
|
446 |
+
if not hasattr(find_similar_tags, "tag2aliases"):
|
447 |
+
find_similar_tags.tag2aliases = build_aliases_dict(tag_aliases_file)
|
448 |
+
if not hasattr(find_similar_tags, "alias2tags"):
|
449 |
+
find_similar_tags.alias2tags = build_aliases_dict(tag_aliases_file, reverse=True)
|
450 |
+
if not hasattr(find_similar_tags, "tag2count"):
|
451 |
+
find_similar_tags.tag2count = build_tag_count_dict(tag_aliases_file)
|
452 |
+
if not hasattr(find_similar_tags, "tag2idwiki"):
|
453 |
+
find_similar_tags.tag2idwiki = build_tag_id_wiki_dict()
|
454 |
+
|
455 |
+
modified_tags = [tag_info['modified_tag'] for tag_info in test_tags]
|
456 |
+
transformed_tags = [tag.replace(' ', '_') for tag in modified_tags]
|
457 |
+
|
458 |
+
# Find similar tags and prepare data for tables
|
459 |
+
html_content = "<div class=\"scrollable-content\" style='display: inline-block; margin: 20px; text-align: center;'>"
|
460 |
+
html_content += "<h1>Unknown Tags</h1>" # Heading for the table
|
461 |
+
tags_added = False
|
462 |
+
bad_entities = []
|
463 |
+
known_entities_in_prompt = []
|
464 |
+
encountered_modified_tags = set()
|
465 |
+
for tag_info in test_tags:
|
466 |
+
original_tag = tag_info['original_tag']
|
467 |
+
modified_tag = tag_info['modified_tag']
|
468 |
+
start_pos = tag_info['start_pos']
|
469 |
+
end_pos = tag_info['end_pos']
|
470 |
+
node_type = tag_info['node_type']
|
471 |
+
|
472 |
+
if modified_tag in special_tags:
|
473 |
+
bad_entities.append({"entity":"Special", "start":start_pos, "end":end_pos})
|
474 |
+
continue
|
475 |
+
|
476 |
+
if modified_tag in encountered_modified_tags:
|
477 |
+
bad_entities.append({"entity":"Duplicate", "start":start_pos, "end":end_pos})
|
478 |
+
continue
|
479 |
+
encountered_modified_tags.add(modified_tag)
|
480 |
+
|
481 |
+
if node_type == "double_comma":
|
482 |
+
bad_entities.append({"entity":"Double Comma", "start":start_pos, "end":end_pos})
|
483 |
+
continue
|
484 |
+
|
485 |
+
modified_tag_for_search = modified_tag.replace(' ','_')
|
486 |
+
similar_words = find_similar_tags.fasttext_small_model.most_similar(modified_tag_for_search, topn = 100)
|
487 |
+
result, seen = [], set(transformed_tags)
|
488 |
+
|
489 |
+
if modified_tag_for_search in find_similar_tags.tag2aliases:
|
490 |
+
if modified_tag in find_similar_tags.tag2aliases and "_" in modified_tag: #Implicitly tell the user that they should get rid of the underscore
|
491 |
+
result.append(modified_tag_for_search.replace('_',' '), 1)
|
492 |
+
seen.add(modified_tag)
|
493 |
+
else: #The user correctly did not put underscores in their tag
|
494 |
+
count = find_similar_tags.tag2count.get(modified_tag_for_search, 0) # Get the count if available, otherwise default to 0
|
495 |
+
tag_id, wiki_entry = find_similar_tags.tag2idwiki.get(modified_tag_for_search, (None, ''))
|
496 |
+
# Check if tag_id and wiki_entry are valid
|
497 |
+
wiki_url = ""
|
498 |
+
if tag_id is not None and wiki_entry:
|
499 |
+
# Construct the URL for the tag's wiki page
|
500 |
+
wiki_url = f"https://e621.net/wiki_pages/{tag_id}"
|
501 |
+
known_entities_in_prompt.append({"entity":"Known Tag", "start":start_pos, "end":end_pos, "count":count, "wiki_url":wiki_url, "wiki_entry":wiki_entry})
|
502 |
+
continue
|
503 |
+
else:
|
504 |
+
for item in similar_words:
|
505 |
+
similar_word, similarity = item
|
506 |
+
if similar_word not in seen:
|
507 |
+
if similar_word in find_similar_tags.tag2aliases:
|
508 |
+
result.append((similar_word.replace('_', ' '), round(similarity, 3)))
|
509 |
+
seen.add(similar_word)
|
510 |
+
else:
|
511 |
+
for similar_tag in find_similar_tags.alias2tags.get(similar_word, []):
|
512 |
+
if similar_tag not in seen:
|
513 |
+
result.append((similar_tag.replace('_', ' '), round(similarity, 3)))
|
514 |
+
seen.add(similar_tag)
|
515 |
+
|
516 |
+
#Remove NSFW tags if appropriate.
|
517 |
+
if not allow_nsfw_tags:
|
518 |
+
result = [(word, score) for word, score in result if word.replace(' ','_') not in nsfw_tags]
|
519 |
+
|
520 |
+
#Adjust score based on context
|
521 |
+
for i in range(len(result)):
|
522 |
+
word, score = result[i] # Unpack the tuple
|
523 |
+
context_score = tag_to_context_similarity.get(word,0)
|
524 |
+
result[i] = (word, .5 * ((context_similarity_weight * context_score) + ((1 - context_similarity_weight) * score)))
|
525 |
+
|
526 |
+
result = sorted(result, key=lambda x: x[1], reverse=True)[:10]
|
527 |
+
html_content += create_html_tables_for_tags(modified_tag, "Corrected Tag", result, find_similar_tags.tag2count, find_similar_tags.tag2idwiki)
|
528 |
+
|
529 |
+
bad_entities.append({"entity":"Unknown Tag", "start":start_pos, "end":end_pos})
|
530 |
+
|
531 |
+
tags_added=True
|
532 |
+
# If no tags were processed, add a message
|
533 |
+
if not tags_added:
|
534 |
+
html_content = create_html_placeholder(title="Unknown Tags", content="No Unknown Tags Found")
|
535 |
+
|
536 |
+
return html_content, bad_entities, known_entities_in_prompt # Return list of lists for Dataframe
|
537 |
+
|
538 |
+
|
539 |
+
def build_tag_offsets_dicts(new_image_tags_with_positions):
|
540 |
+
# Structure the data for HighlightedText
|
541 |
+
tag_data = []
|
542 |
+
for tag_text, start_pos, nodetype in new_image_tags_with_positions:
|
543 |
+
# Modify the tag
|
544 |
+
modified_tag = tag_text.replace('_', ' ').replace('\\(', '(').replace('\\)', ')').strip()
|
545 |
+
artist_matrix_tag = tag_text.replace('_', ' ').replace('\\(', '\(').replace('\\)', '\)').strip()
|
546 |
+
tf_idf_matrix_tag = re.sub(r'\\([()])', r'\1', re.sub(r' ', '_', tag_text.strip().removeprefix('by ').removeprefix('by_')))
|
547 |
+
# Calculate the end position based on the original tag length
|
548 |
+
end_pos = start_pos + len(tag_text)
|
549 |
+
# Append the structured data for each tag
|
550 |
+
tag_data.append({
|
551 |
+
"original_tag": tag_text,
|
552 |
+
"start_pos": start_pos,
|
553 |
+
"end_pos": end_pos,
|
554 |
+
"modified_tag": modified_tag,
|
555 |
+
"artist_matrix_tag": artist_matrix_tag,
|
556 |
+
"tf_idf_matrix_tag": tf_idf_matrix_tag,
|
557 |
+
"node_type": nodetype
|
558 |
+
})
|
559 |
+
return tag_data
|
560 |
+
|
561 |
+
|
562 |
+
def augment_bad_entities_with_regex(text):
|
563 |
+
bad_entities = []
|
564 |
+
|
565 |
+
#comma at end
|
566 |
+
match = re.search(r',(?=\s*$)', text)
|
567 |
+
if match:
|
568 |
+
index = match.start()
|
569 |
+
bad_entities.append({"entity":"Remove Final Comma", "start":index, "end":index+1})
|
570 |
+
match = re.search(r'\([^()]*(,)\s*\)\s*$', text)
|
571 |
+
if match:
|
572 |
+
index = match.start(1)
|
573 |
+
bad_entities.append({"entity":"Remove Final Comma", "start":index, "end":index+1})
|
574 |
+
match = re.search(r'\([^()]*(,)\s*:\s*\d+(\.\d+)?\s*\)\s*$', text)
|
575 |
+
if match:
|
576 |
+
index = match.start(1)
|
577 |
+
bad_entities.append({"entity":"Remove Final Comma", "start":index, "end":index+1})
|
578 |
+
|
579 |
+
# Comma after parentheses, multiple occurrences
|
580 |
+
for match in re.finditer(r'(?<!\\)\)\s*(,)\s*[^\s]', text):
|
581 |
+
index = match.start(1)
|
582 |
+
bad_entities.append({"entity": "Move Comma Inside Parentheses", "start": index, "end": index + 1})
|
583 |
+
|
584 |
+
return bad_entities
|
585 |
+
|
586 |
+
def escape_html(text):
|
587 |
+
return text.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'")
|
588 |
+
|
589 |
+
def format_annotated_html(bad_entities, known_entities, text):
|
590 |
+
tooltip_map = {
|
591 |
+
"Unknown Tag": "This may not be a valid e621 tag. Consider removing or replacing it with tag(s) from the \"Unknown Tags\" section.",
|
592 |
+
"Duplicate": "This tag has appeared multiple times in your prompt. Consider removing the copies.",
|
593 |
+
"Remove Final Comma": "There should be no comma at the end of your prompt. Consider removing it.",
|
594 |
+
"Move Comma Inside Parentheses": "In most e621-based models, the comma following a tag functions as an "attention anchor", carrying most of the tag's information. It should therefore be assigned the same weight as the rest of the tag. So instead of "(lineless:1.1),", consider "(lineless,:1.1)" or "(lineless,)"",
|
595 |
+
"Double Comma": "One comma between tags is considered ample."
|
596 |
+
}
|
597 |
+
color_map = {
|
598 |
+
"Unknown Tag": ("white", "red"), # White text on red background
|
599 |
+
"Duplicate": ("black", "yellow"), # Black text on yellow background
|
600 |
+
"Remove Final Comma": ("white", "blue"), # White text on blue background
|
601 |
+
"Move Comma Inside Parentheses": ("white", "green"), # White text on green background
|
602 |
+
"Double Comma": ("white","orange")
|
603 |
+
}
|
604 |
+
|
605 |
+
# Combine and sort entities
|
606 |
+
combined_entities = bad_entities + known_entities
|
607 |
+
combined_entities = sorted(combined_entities, key=lambda x: x['start'],reverse=True)
|
608 |
+
|
609 |
+
# Generate HTML for the main text
|
610 |
+
html_text = text
|
611 |
+
for entity in combined_entities:
|
612 |
+
start = entity['start']
|
613 |
+
end = entity['end']
|
614 |
+
label = entity['entity']
|
615 |
+
if label == "Known Tag":
|
616 |
+
wiki_url = entity.get('wiki_url', '')
|
617 |
+
count = entity['count']
|
618 |
+
wiki_entry = entity.get('wiki_entry', '')
|
619 |
+
sanitized_wiki_entry = escape_html(wiki_entry) if wiki_entry else 'Unavailable'
|
620 |
+
if wiki_url: # Check if wiki_url is not empty
|
621 |
+
html_part = f'<a href="{wiki_url}" target="_blank" title="Count: {count}\tWiki: {sanitized_wiki_entry}" style="text-decoration: none; color: white; cursor: pointer; font-style: italic;">{text[start:end]}</a>'
|
622 |
+
else:
|
623 |
+
html_part = f'<span title="Count: {count}\tWiki: {sanitized_wiki_entry}" style="text-decoration: none; color: white; cursor: help; font-style: italic;">{text[start:end]}</span>'
|
624 |
+
else:
|
625 |
+
color = color_map.get(label, ("black", "white"))
|
626 |
+
html_part = f'<span style="background-color: {color[1]}; color: {color[0]};">{text[start:end]}</span>'
|
627 |
+
html_text = html_text[:start] + html_part + html_text[end:]
|
628 |
+
|
629 |
+
# Generate HTML for the color key
|
630 |
+
color_key_html = "<div style='text-align: right; margin-top: 20px;'>Key:"
|
631 |
+
used_labels = set(entity['entity'] for entity in bad_entities)
|
632 |
+
for label, colors in color_map.items():
|
633 |
+
if label in used_labels:
|
634 |
+
tooltip = tooltip_map.get(label, "")
|
635 |
+
# Adding margin-right for spacing between items
|
636 |
+
color_key_html += f" <span style='background-color: {colors[1]}; color: {colors[0]}; margin-right: 10px;' title='{tooltip}'>{label}</span>"
|
637 |
+
color_key_html += "</div>"
|
638 |
+
|
639 |
+
return f'<div style="padding: 10px; font-size: 16px;">{html_text}</div>{color_key_html}'
|
640 |
+
|
641 |
+
|
642 |
+
def find_similar_artists(original_tags_string, top_n, context_similarity_weight, allow_nsfw_tags):
|
643 |
+
try:
|
644 |
+
new_tags_string = original_tags_string.lower()
|
645 |
+
new_tags_string, removed_tags = remove_special_tags(new_tags_string)
|
646 |
+
|
647 |
+
# Parse the prompt
|
648 |
+
parsed = parser.parse(new_tags_string)
|
649 |
+
# Extract tags from the parsed tree
|
650 |
+
new_image_tags = extract_tags(parsed)
|
651 |
+
tag_data = build_tag_offsets_dicts(new_image_tags)
|
652 |
+
|
653 |
+
#Suggested tags stuff
|
654 |
+
suggested_tags_html_content = "<div class=\"scrollable-content\" style='display: inline-block; margin: 20px; text-align: center;'>"
|
655 |
+
suggested_tags_html_content += "<h1>Suggested Tags</h1>" # Heading for the table
|
656 |
+
suggested_tags = get_tfidf_reduced_similar_tags([item["tf_idf_matrix_tag"] for item in tag_data] + removed_tags, allow_nsfw_tags)
|
657 |
+
|
658 |
+
unseen_tags_data, bad_entities, known_entities = find_similar_tags(tag_data, suggested_tags, context_similarity_weight, allow_nsfw_tags)
|
659 |
+
|
660 |
+
#Bad tags stuff
|
661 |
+
bad_entities.extend(augment_bad_entities_with_regex(new_tags_string))
|
662 |
+
bad_entities.sort(key=lambda x: x['start'])
|
663 |
+
#bad_tags_illustrated_string = {"text":new_tags_string, "entities":bad_entities}
|
664 |
+
bad_tags_illustrated_html = format_annotated_html(bad_entities, known_entities, new_tags_string)
|
665 |
+
|
666 |
+
# Create a set of tags that should be filtered out
|
667 |
+
filter_tags = {entry["original_tag"].strip() for entry in tag_data}
|
668 |
+
# Use this set to filter suggested_tags
|
669 |
+
suggested_tags_filtered = OrderedDict((k, v) for k, v in suggested_tags.items() if k not in filter_tags)
|
670 |
+
|
671 |
+
# Splitting the dictionary into two based on the condition
|
672 |
+
suggested_artist_tags_filtered = OrderedDict((k, v) for k, v in suggested_tags_filtered.items() if k.startswith("by "))
|
673 |
+
suggested_non_artist_tags_filtered = OrderedDict((k, v) for k, v in suggested_tags_filtered.items() if not k.startswith("by ") and k not in special_tags)
|
674 |
+
|
675 |
+
topnsuggestions = list(islice(suggested_non_artist_tags_filtered.items(), 100))
|
676 |
+
suggested_tags_html_content += create_html_tables_for_tags("-", "Suggested Tag", topnsuggestions, find_similar_tags.tag2count, find_similar_tags.tag2idwiki)
|
677 |
+
|
678 |
+
#Artist stuff
|
679 |
+
excluded_artists = ["by conditional dnp", "by unknown artist"]
|
680 |
+
top_artists = [(key, value) for key, value in suggested_artist_tags_filtered.items() if key.lower() not in excluded_artists][:top_n]
|
681 |
+
top_artists_str = create_top_artists_table(top_artists)
|
682 |
+
dynamic_prompts_formatted_artists = "{" + "|".join([artist for artist, _ in top_artists]) + "}"
|
683 |
+
|
684 |
+
image_galleries = []
|
685 |
+
for root, dirs, files in os.walk(sample_images_directory_path):
|
686 |
+
for name in dirs:
|
687 |
+
baseline, artists = generate_artist_image_tuples([name[3:] for name, _ in top_artists], os.path.join(root, name))
|
688 |
+
image_galleries.append(baseline) # Add baseline as its own gallery item
|
689 |
+
image_galleries.append(artists) # Extend the list with artist tuples
|
690 |
+
|
691 |
+
return (unseen_tags_data, bad_tags_illustrated_html, suggested_tags_html_content, top_artists_str, dynamic_prompts_formatted_artists, *image_galleries)
|
692 |
+
except ParseError as e:
|
693 |
+
return [], "Parse Error: Check for mismatched parentheses or something", "", "", None, None
|
694 |
+
|
695 |
+
|
696 |
+
with gr.Blocks(css=css) as app:
|
697 |
+
with gr.Group():
|
698 |
+
with gr.Row():
|
699 |
+
with gr.Column(scale=3):
|
700 |
+
image_tags = gr.Textbox(label="Enter Prompt", placeholder="e.g. fox, outside, detailed background, ...")
|
701 |
+
#bad_tags_illustrated_string = gr.HighlightedText(show_legend=True, color_map={"Unknown Tag":"red","Duplicate":"yellow","Remove Final Comma":"purple","Move Comma Inside Parentheses":"green"}, label="Annotated Prompt")
|
702 |
+
bad_tags_illustrated_string = gr.HTML()
|
703 |
+
with gr.Column(scale=1):
|
704 |
+
#image_path = os.path.join("https://huggingface.co/spaces/FoodDesert/Prompt_Squirrel/resolve/main", "transparentsquirrel.png")
|
705 |
+
#gr.Image(label=" ", value=image_path, height=155, width=140)
|
706 |
+
gr.HTML('<div style="text-align: center;"><img src="https://huggingface.co/spaces/FoodDesert/Prompt_Squirrel/resolve/main/mascotimages/transparentsquirrel.png" alt="Cute Mascot" style="max-height: 180px; background: transparent;"></div><br>')
|
707 |
+
#gr.HTML("<br>" * 2) # Adjust the number of line breaks ("<br>") as needed to push the button down
|
708 |
+
#image_path = os.path.join('mascotimages', "transparentsquirrel.png")
|
709 |
+
#random_image_path = os.path.join('mascotimages', random.choice([f for f in os.listdir('mascotimages') if os.path.isfile(os.path.join('mascotimages', f))]))
|
710 |
+
#with Image.open(random_image_path) as img:
|
711 |
+
# gr.Image(value=img,show_label=False, show_download_button=False, show_share_button=False, height=200)
|
712 |
+
#gr.Image(value="https://huggingface.co/spaces/FoodDesert/Prompt_Squirrel/resolve/main/mascotimages/transparentsquirrel.png",show_label=False, show_download_button=False, show_share_button=False, height=200)
|
713 |
+
#I posted the image to discord, and that's where this link came from. This is a very ugly way to do this, but I could not, no matter what I tried, get it to display an image from within the space itself. The galleries work fine for some reason, but not this.
|
714 |
+
#gr.Image(value="https://res.cloudinary.com/dnse84ol6/image/upload/v1713538125/transparentsquirrel_zhou7f.png",show_label=False, show_download_button=False, show_share_button=False, height=200)
|
715 |
+
submit_button = gr.Button(variant="primary")
|
716 |
+
with gr.Row():
|
717 |
+
with gr.Column(scale=3):
|
718 |
+
with gr.Group():
|
719 |
+
with gr.Row():
|
720 |
+
context_similarity_weight = gr.Slider(minimum=0, maximum=1, value=0.5, step=0.1, label="Context Similarity Weight")
|
721 |
+
allow_nsfw = gr.Checkbox(label="Allow NSFW Tags", value=False)
|
722 |
+
with gr.Row():
|
723 |
+
with gr.Column(scale=2):
|
724 |
+
unseen_tags = gr.HTML(label="Unknown Tags", value=create_html_placeholder(title="Unknown Tags"))
|
725 |
+
with gr.Column(scale=1):
|
726 |
+
suggested_tags = gr.HTML(label="Suggested Tags", value=create_html_placeholder(title="Suggested Tags"))
|
727 |
+
with gr.Column(scale=1):
|
728 |
+
with gr.Group():
|
729 |
+
num_artists = gr.Slider(minimum=1, maximum=100, value=10, step=1, label="Number of artists")
|
730 |
+
top_artists = gr.HTML(label="Top Artists", value=create_html_placeholder(title="Top Artists"))
|
731 |
+
dynamic_prompts = 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.")
|
732 |
+
galleries = []
|
733 |
+
for root, dirs, files in os.walk(sample_images_directory_path):
|
734 |
+
for name in dirs:
|
735 |
+
with gr.Row():
|
736 |
+
baseline = gr.Gallery(allow_preview=False, rows=1, columns=1, height=420, scale=3)
|
737 |
+
styles = gr.Gallery(preview=False, rows=2, columns=5, height=420, scale=8)
|
738 |
+
galleries.extend([baseline, styles])
|
739 |
+
|
740 |
+
submit_button.click(
|
741 |
+
find_similar_artists,
|
742 |
+
inputs=[image_tags, num_artists, context_similarity_weight, allow_nsfw],
|
743 |
+
outputs=[unseen_tags, bad_tags_illustrated_string, suggested_tags, top_artists, dynamic_prompts] + galleries
|
744 |
+
)
|
745 |
+
|
746 |
+
gr.Markdown(faq_content)
|
747 |
+
|
748 |
+
|
749 |
+
app.launch()
|
750 |
+
|