I am working on an image tagging python script using an ONNX based AI tagger, actually, several of them, which is what I need your help with.
I have this code snippet inside a generate_tags() function, which takes in an image(img) as a parameter, I have a dict of taggers(taggers) which I run .predict(img) on to make the tag predictions(how much each tag applies to the image), the tagger class also stores all the predictions inside self.tags['predictions'], self.tags being a DataFrame retrieved from a .csv file using pandas like so:
self.tags = pd.read_csv(self.tags_file)
The .get_tags() returns a filtered copy of this DataFrame based on a prediction threshold and tag category, here is that method:
Because of the two selections above, I also get this warning in the terminal:
code
D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py:76: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
return self.tags[self.tags['predictions'] > threshold][self.tags['category'] == category.value]
I would appreciate if you could tell me the correct way to filter the list with multiple options.
However, on to the main part, this is the code snippet where I iterate through a list of taggers and for now I just join the tag names from all taggers into a string, so obviously there will be duplicates, here is the function:
Since .get_tags() returns a filters copy of the DataFrame, I want to be able to combine these predictions together, removing any duplicate 'name' values, I would also like a way to remove any tags which 'name' matches a list of strings, and them form a tag_string with a cleaned list of tag names. I already have these variables in place ready to be used, also a string to prepend to the tags and one to append to the end, separated with a coma:
code
prepend = ""
append = ""
tags_to_remove = []
Assistant
Addressing DataFrame Index Warning
Before we tackle the core functionality of combining and filtering tags across different taggers, let’s first address the warning from your get_tags() method. The warning arises because you're performing chained indexing on the DataFrame which can lead to unexpected results. We should modify this method to use a single boolean mask for indexing:
This approach uses logical AND (&) to combine conditions which allows for a more reliable and efficient selection from the DataFrame without causing confusion about index alignment.
Combining Predictions and Filtering Tags
Next, to combine tags from various taggers without duplicates and eventually exclude unwanted tags, update your generate_tags() function. Here’s a streamlined and improved version of your function using Pandas capabilities extensively for handling duplicates and filtering out unwanted tags.
python
def generate_tags(img, prepend="", append="", tags_to_remove=[]):
combined_tags = pd.DataFrame()
for tagger_name, tagger in taggers.items():
predictions = tagger.predict(img) # Assuming predictions update internal state used by get_tags()
tags = tagger.get_tags()
print(f"tag count: {len(tags)}")
print(f"tags from {tagger_name}:\n{tags!r}")
combined_tags = combined_tags.append(tags, ignore_index=True)
# Remove duplication on 'name' by keeping the first occurrence
combined_tags = combined_tags.drop_duplicates(subset='name', keep='first')
# Filter out unwanted tags by names
if tags_to_remove:
combined_tags = combined_tags[~combined_tags['name'].isin(tags_to_remove)]
# Creating the string of tag names
tag_list = [name.replace('_', ' ').replace('(', '\(').replace(')', '\)') for name in combined_tags['name']]
tag_string = ", ".join(tag_list)
# Add prepend and append texts
full_tag_string = f"{prepend}{tag_string}{append}"
return full_tag_string
User
Most of it looks good, however there appears to be a mistake in what you gave me, at this line:
Traceback (most recent call last):
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 272, in <module>
caption = check_caption(img_dir, name, CaptioningMode.REPLACE)
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 119, in check_caption
tags_str = generate_tags(img)
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 211, in generate_tags
combined_tags = combined_tags.append(tags, ignore_index=True)
File "d:\AI Generation\Projects\AIToolkit\.conda\lib\site-packages\pandas\core\generic.py", line 5989, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'append'. Did you mean: '_append'?
Assistant
Ah, I see! It looks like you're using a version of pandas where DataFrame.append() has been deprecated or is no longer available. In recent versions of Pandas, you should use pd.concat() instead to combine DataFrames. Here’s how you should modify your function to adapt to this change:
python
import pandas as pd
def generate_tags(img, prepend="", append="", tags_to_remove=[]):
combined_tags_list = []
for tagger_name, tagger in taggers.items():
predictions = tagger.predict(img) # Assuming predictions update internal state used by get_tags()
tags = tagger.get_tags()
print(f"tag count: {len(tags)}")
print(f"tags from {tagger_name}:\n{tags!r}")
combined_tags_list.append(tags)
# Concatenate all DataFrames in the list into one DataFrame
combined_tags = pd.concat(combined_tags_list, ignore_index=True)
# Remove duplication on 'name' by keeping the first occurrence
combined_tags = combined_tags.drop_duplicates(subset='name', keep='first')
# Filter out unwanted tags by names
if tags_to_remove:
combined_tags = combined_tags[~combined_tags['name'].isin(tags_to_remove)]
# Creating the string of tag names
tag_list = [name.replace('_', ' ').replace('(', '\(').replace(')', '\)') for name in combined_tags['name']]
tag_string = ", ".join(tag_list)
# Add prepend and append texts
full_tag_string = f"{prepend}{tag_string}{append}"
return full_tag_string
Explanation:
Gather DataFrames: Instead of using append(), all tag DataFrames are gathered into a list combined_tags_list as they are generated.
Concatenate All DataFrames: Using pd.concat(), instead of appending to a DataFrame in a loop, concatenate all DataFrames in combined_tags_list once at the end.
This approach works with the latest versions of pandas and follows good practices for DataFrame manipulation, improving performance by reducing the number of operations. Note that repeatedly appending to or concatenating DataFrames in a loop can be inefficient and should be avoided when possible. Here, we've minimized the DataFrame creation operations to two key steps: gathering and finalizing.
User
Great, thanks, that seems to all be working as expected.
Moving on, I have this Enum(from import enum) and strings:
code
class TagCategory(Enum):
GENERAL = 0
CHARACTER = 4
RATING = 9
tagCategoryLabels = {
TagCategory.GENERAL: "general",
TagCategory.CHARACTER: "character",
TagCategory.RATING: "rating"
}
What I would like to also do, is be able to select all TagCategory for this line:
tags = tagger.get_tags()
so I get tags for all categories, I then, based on certain categories, in this case, RATING, I want to append the label to the tag name, for example if a tag with category 9 was "safe", the resulting tag that goes into the tag_string would be "rating_safe", however I do not want to do the same for general or character, I just want a tag in those categories, such as if a tag with category 0 was "1girl", the tag that goes into the tag_string remains unchanged and stays "1girl", and this has to be done without having '_' replaced with ' ', I still want that to happen to the tags themselves though.
Assistant
You can achieve this desired customization within your generate_tags() function by checking the category of each tag and then modifying the tag names accordingly before constructing the final string. We implement these changes as follows:
Modify get_tags() to accept and return tags of all categories, or a specific one if supplied.
Process each tag in generate_tags() based on its category to prepend the category label if needed.
First, let’s modify get_tags() to make category optional:
python
def get_tags(self, threshold=0.35, category=None):
if category is not None:
return self.tags[(self.tags['predictions'] > threshold) & (self.tags['category'] == category.value)]
else:
return self.tags[self.tags['predictions'] > threshold]
Next, you can adjust the generating tag logic to adapt the changes in how you want the tags formatted based on their category:
python
import pandas as pd
def generate_tags(img, prepend="", append="", tags_to_remove=[]):
combined_tags_list = []
for tagger_name, tagger in taggers.items():
predictions = tagger.predict(img) # update internal state used by get_tags()
tags = tagger.get_tags() # Get tags now returns tags of all categories
print(f"tag count: {len(tags)}")
print(f"tags from {tagger_name}:\n{tags!r}")
combined_tags_list.append(tags)
# Concatenate all DataFrames in the list into one DataFrame
combined_tags = pd.concat(combined_tags_list, ignore_index=True)
# Remove duplication on 'name' by keeping the first occurrence
combined_tags = combined_tags.drop_duplicates(subset='name', keep='first')
# Filter out unwanted tags by names
if tags_to_remove:
combined_tags = combined_tags[~combined_tags['name'].isin(tags_to_remove)]
# Modifying tag names based on category, and creating the string of tag names
tag_list = []
for index, row in combined_tags.iterrows():
tag_name = row['name'].replace('_', ' ')
if row['category'] == TagCategory.RATING.value:
tag_name = f"rating_{tag_name}"
tag_list.append(tag_name)
tag_string = ", ".join(tag_list)
# Add prepend and append texts
full_tag_string = f"{prepend}{tag_string}{append}"
return full_tag_string
User
Ok, new issue, one of the taggers I am attempting to use, the output DataFrame, instead of using 'name' for the tag name, it uses 'tag', so I added a new value to the tagger.tag_column, this works fine in the for loop where I am iterating over each tagger:
However, outside of the for loop, like where I am dropping duplicates or removing tags:
code
# Remove duplication on 'name' by keeping the first occurrence
combined_tags = combined_tags.drop_duplicates(subset='name', keep='first')
# Filter out unwanted tags by names
if tags_to_remove:
combined_tags = combined_tags[~combined_tags['name'].isin(tags_to_remove)]
Or even when I am making a string from the tags, the 'category' is also an issue:
code
# Modifying tag names based on category, and creating the string of tag names
tag_list = []
for index, row in combined_tags.iterrows():
tag_name = row['name'].replace('_', ' ').replace('(', '\(').replace(')', '\)')
# Handle special cases
if row['category'] == TagCategory.RATING.value:
# tag_name = f"rating_{tag_name}" # Might want this in the future, for now we just skip this tag
continue
tag_list.append(tag_name)
Assistant
To allow flexibility for handling different taggers where the columns for tag names and categories might be different, you can introduce a more universal approach in handling these columns by using standardized naming across your processing logic or dynamically adjusting based on each tagger's specifications.
Here are some adjustments you can make to handle the variations smoothly:
Introduce a way to standardize or adapt column names on-the-fly within your loop that processes these DataFrame outputs.
Extend this dynamic approach when processing the tags for duplication checks and string creation.
Step 1: Standardizing Column Names
Before merging or processing tags, standardize the DataFrame columns to a consistent naming schema, such as always expecting the fields 'name' and 'category'. This can either be done by renaming DataFrame columns within get_tags() or immediately after you fetch the tags in generate_tags():
python
def generate_tags(img, prepend="", append="", tags_to_remove=[]):
combined_tags_list = []
for tagger_name, tagger in taggers.items():
predictions = tagger.predict(img)
tags = tagger.get_tags()
# Standardize column names
rename_dict = {
tagger.tag_column: 'name',
tagger.category_column: 'category' # Assuming you also have a variable for category column similar to tag_column
}
tags = tags.rename(columns=rename_dict)
print(f"tag count: {len(tags)}")
print(f"tags from {tagger_name!r}:\n{tags!r}")
combined_tags_list.append(tags)
# Concatenate all DataFrames in the list into one DataFrame
combined_tags = pd.concat(combined_tags_list, ignore_index=True)
# Step 2: Handling duplicates, tag removal, and tag string construction
# ...
Step 2: Removing Duplicates and Processing Tags
Continue using the standardized column names 'name' and 'category' in the rest of your function. This includes duplicate management, tag removals, and creating the final tag strings:
User
Ok, one final thing I think, I added a new variable along side tags_to_remove called tags_required, like tags_to_remove this is also a list, however I want to ensure these tags are added into the tags, but I want to ensure there is still no duplicate tags, including these ones.
Assistant
To integrate a tags_required list, which ensures certain tags are always included, and at the same time maintain no duplicates even with these required tags, you can modify the code as follows:
Initial inclusion: After building up your combined tags through different taggers, you will make sure to include these tags_required.
De-duplication: Ensure that after adding the required tags, no duplicates exist between all the gathered and necessitated tags.
Code Integration
Update your generate_tags() to include and manage tags_required:
python
def generate_tags(img, prepend="", append="", tags_to_remove=[], tags_required=[]):
combined_tags_list = []
for tagger_name, tagger in taggers.items():
predictions = tagger.predict(img)
tags = tagger.get_tags()
# Standardize column names
rename_dict = {
tagger.tag_column: 'name',
tagger.category_column: 'category'
}
tags = tags.rename(columns=rename_dict)
print(f"tag count: {len(tags)}")
print(f"tags from {tagger_name!r}:\n{tags!r}")
combined_tags_list.append(tags)
# Concatenate all DataFrames in the list into one DataFrame
combined_tags = pd.concat(combined_tags_list, ignore_index=True)
# Add required tags, if any
if tags_required:
required_tags_df = pd.DataFrame(tags_required, columns=['name'])
required_tags_df['category'] = 'custom' # You can customize this or make it dynamic
combined_tags = pd.concat([combined_tags, required_tags_df], ignore_index=True)
# Remove duplication on 'name' by keeping the first occurrence
combined_tags = combined_tags.drop_duplicates(subset='name', keep='first')
# Filter out unwanted tags by names
if tags_to_remove:
combined_tags = combined_tags[~combined_tags['name'].isin(tags_to_remove)]
# Modifying tag names based on category, and creating the string of tag names
tag_list = []
for index, row in combined_tags.iterrows():
tag_name = row['name'].replace('_', ' ').replace('(', '\(').replace(')', '\)')
# Skip specific tags (e.g., ratings) if needed
tag_list.append(tag_name)
tag_string = ", ".join(tag_list)
full_tag_string = f"{prepend}{tag_string}{append}"
return full_tag_string
User
I want to create a progress bar in the control to keep track of the files I process, this is the for loop with a bit of added context:
code
# Process files
pairs = []
filestodelete = []
filestorename = []
# count = 1
for filename in os.listdir(img_dir):
# if count <= 0:
# break
name, ext = os.path.splitext(filename)
# Images
if img := load_image(os.path.join(img_dir, filename)):
# count -= 1
# Check the caption first, this is needed so we can delete it together with the image
caption = check_caption(img_dir, name, CaptioningMode.REPLACE)
# Check for invalid dimensions
if img.width < min_dim and img.height < min_dim:
# print(f'Invalid dimensions {filename} - {img.width}x{img.height}')
filestodelete.append(os.path.join(img_dir, filename))
filestodelete.append(os.path.join(img_dir, caption))
continue
# Convert to JPEG
if ext.lower() == '.jpeg':
filestorename.append((os.path.join(img_dir, filename), os.path.join(img_dir, filename.replace('.jpeg', '.jpg'))))
elif ext.lower() != '.jpg':
jpeg_path = f'{name}.jpg'
print(f'Converting {filename} to {jpeg_path}')
img.convert('RGB').save(os.path.join(img_dir, jpeg_path), 'JPEG', quality=100)
filestodelete.append(os.path.join(img_dir, filename))
# If we made it here we should have a valid image/caption pair
pairs.append((f"{name}.jpg", caption))
# print(f"Adding image/caption pair: ({name}.jpg, {caption})")
img.close()
elif ext.lower() in ('.jpeg', '.jpg', '.png', '.gif', '.webp', '.tif', '.bmp', '.tga'):
filestodelete.append(os.path.join(img_dir, filename))
# Process deleted files
delete_files(filestodelete)
filestodelete = []
Unfortunately I do not know what is an image until I reach the load_image if statement, however, tracking based on the number of files in os.listfir(img_dir) is fine. Let's do it in a step by step way to ensure the simplest and most efficient method is used, and ensure no steps are missed.
Assistant
To integrate a progress bar into your script, you can utilize the tqdm library, which is a straightforward and flexible way to add a progress bar to your loops in Python. Here is a step-by-step method to add a progress bar for your file processing loop:
Step 1: Install tqdm
If not already installed, you can install tqdm via pip:
bash
pip install tqdm
Step 2: Integrate tqdm with Your Loop
You'll add the tqdm progress bar to your for-loop which iterates over the files in img_dir. This will provide a visual indicator of the processing progress.
Modifications to Your Code:
Import the tqdm module.
Wrap your file iteration with tqdm for the progress bar.
Here's how you can modify your existing loop:
python
from tqdm import tqdm # Import tqdm
# Process files
pairs = []
filestodelete = []
filestorename = []
# Using tqdm to wrap around the os.listdir for progress tracking
for filename in tqdm(os.listdir(img_dir), desc="Processing files"):
name, ext = os.path.splitext(filename)
if img := load_image(os.path.join(img_dir, filename)):
caption = check_caption(img_dir, name, CaptioningMode.REPLACE)
if img.width < min_dim and img.height < min_dim:
filestodelete.append(os.path.join(img_dir, filename))
filestodelete.append(os.path.join(img_dir, caption))
continue
if ext.lower() == '.jpeg':
filestorename.append((os.path.join(img_dir, filename), os.path.join(img_dir, filename.replace('.jpeg', '.jpg'))))
elif ext.lower() != '.jpg':
jpeg_path = f'{name}.jpg'
print(f'Converting {filename} to {jpeg_path}')
img.convert('RGB').save(os.path.join(img_dir, jpeg_path), 'JPEG', quality=100)
filestodelete.append(os.path.join(img_dir, filename))
pairs.append((f"{name}.jpg", caption))
img.close()
elif ext.lower() in ('.jpeg', '.jpg', '.png', '.gif', '.webp', '.tif', '.bmp', '.tga'):
filestodelete.append(os.path.join(img_dir, filename))
# Process deleted files
delete_files(filestodelete)
User
I tried making the filtering more complicated in my get_tags method, for completeness, here is the whole class:
code
default_category_thresholds = {
TagCategory.GENERAL: 0.35,
TagCategory.ARTIST: 0.35,
TagCategory.COPYRIGHT: 0.35,
TagCategory.CHARACTER: 0.80,
TagCategory.SPECIES: 0.80,
TagCategory.META: 0.70,
TagCategory.LORE: 0.35,
TagCategory.RATING: 1.00,
}
# TODO: Finish this, too lazy right now.
class Tagger:
def __init__(self, model_file: str, tags_file: str, category_blacklist: list = [TagCategory.RATING], category_thresholds: list = default_category_thresholds, tag_column: str = "name", category_column: str = "category", count_column: str = "count") -> None:
self.model_file = model_file
self.tags_file = tags_file
self.session = ort.InferenceSession(self.model_file)
self.input_name = self.session.get_inputs()[0].name
self.output_name = self.session.get_outputs()[0].name
self.input_shape = self.session.get_inputs()[0].shape
self.category_blacklist = category_blacklist
self.category_thresholds = category_thresholds
self.tags = pd.read_csv(self.tags_file)
rename_dict = {
tag_column: 'name',
category_column: 'category',
count_column: 'count',
}
self.tags = self.tags.rename(columns=rename_dict)
def predict(self, image):
_, height, _, _ = self.session.get_inputs()[0].shape
img_np = fill_transparent(image)
img_np = np.asarray(img_np)[:, :, ::-1]
img_np = make_square(img_np, height)
img_np = smart_resize(img_np, height)
img_np = img_np.astype(np.float32)
img_np = np.expand_dims(img_np, 0)
results = self.session.run([self.output_name], {self.input_name: img_np})
predictions = results[0][0]
self.tags['predictions'] = predictions
return predictions
def get_tags(self, threshold = None, category: TagCategory = None):
# Blacklist categories
mask = (self.tags['category'] not in self.category_blacklist)
# Filter for each category
for cat, thresh in self.category_thresholds:
mask = (mask) & (self.tags['category'] == cat.value & self.tags['predictions'] > thresh)
if (category is not None) or (threshold is not None):
return self.tags[((self.tags['predictions'] > threshold) if threshold is not None else True) & ((self.tags['category'] == category.value) if category is not None else True)]
else:
return self.tags[mask]
Assistant
The error you're encountering is due to an incorrect boolean operation on the pandas Series. In pandas, logical operations like in cannot be directly applied to check if each element in a Series is in a list. You should use the .isin() method instead which is specifically designed for this kind of operation.
Also, there's logic in the get_tags computing a mask that contains multiple errors with logical operations and parentheses that need adjustment. Additionally, setting up the masking by separating concerns and ensuring all logical operations are handled correctly on Series objects will resolve these issues.
Here's the corrected get_tags method with explanation for each part:
python
def get_tags(self, threshold=None, category: TagCategory = None):
# Create a mask to exclude blacklist categories
mask = ~self.tags['category'].isin([cat.value for cat in self.category_blacklist])
# Apply category threshold filters
for cat, thresh in self.category_thresholds.items():
# This mask extension ensures it only affects rows where the category matches 'cat'
mask &= ((self.tags['category'] == cat.value) & (self.tags['predictions'] > thresh))
if (category is not None) or (threshold is not None):
# Extend the mask when specific category or threshold is provided
extra_mask = ((self.tags['predictions'] > threshold) if threshold is not None else True) & ((self.tags['category'] == category.value) if category is not None else True)
return self.tags[mask & extra_mask]
else:
return self.tags[mask]
Key Corrections:
Blacklist Masking: ~self.tags['category'].isin([cat.value for cat in self.category_blacklist]) correctly creates a mask that is True for all categories not in the blacklist.
Category Threshold Masking: Iterating over the dictionary, the mask is updated to reflect both the category and its associated prediction threshold. The operation is used with additional parentheses to ensure logical operations align properly with the intended categories and thresholds.
User
Ok, so I have this get_tags method now:
code
def get_tags(self, threshold = None, category: TagCategory = None):
# Blacklist categories
mask = ~self.tags['category'].isin([cat.value for cat in self.category_blacklist])
# Apply category threshold filters
for cat, thresh in self.category_thresholds.items():
# This mask extension ensures it only affects rows where the category matches 'cat'
mask &= ((self.tags['category'] == cat.value) & (self.tags['predictions'] > thresh))
if (category is not None) or (threshold is not None):
extra_mask = ((self.tags['predictions'] > threshold) if threshold is not None else True) & ((self.tags['category'] == category.value) if category is not None else True)
return self.tags[mask & extra_mask]
else:
return self.tags[mask]
However I appear to not be getting anything back, it looks like there is an issue with the masking and it is filtering everything instead.
Assistant
If you’re finding that you’re not getting any results (everything is being filtered out), one or more issues might be present in how the masks are being evaluated and combined. Let's review some common pitfalls and ensure all conditions in your mask formation are behaving as intended:
Category and Prediction Thresholds Overlap: Make sure that the categories and their respective thresholds don't inherently exclude all your tags. It's possible that the thresholds are set too high or the conditions are too restrictive.
Threshold Logic Checks: Ensure that the thresholds are defined correctly in the dictionary and are being applied appropriately to your data.
Check Data Types: Sometimes issues arise if data types do not match, e.g., the categories in self.tags['category'] might not match the types from Cat.value in the TagCategory.
Check Initial Data: Make sure self.tags has data that actually could pass the filters. If the data itself has anomalies (like very low predictions across the board), the applied masks might validly exclude all entries.
Debugging with Print Statements: Temporarily add print statements to inspect the data and intermediate masks.
Let's enhance the method to include some debugging information:
python
User
Ok, here is the console output, there is a bit of glitching due to tqdm, but that is normal, here is the output of one tagger model with those debug print statements:
Thank you for sharing the output. The primary issue evident from the output is that after successfully filtering the GENERAL category tags, the DataFrame becomes empty for subsequent filters (like ARTIST, COPYRIGHT, etc.), implying that the initial mask in your get_tags function might be overridden or incorrectly updated during each category's filter application.
The issue likely stems from an incorrect logical AND operation (&) in your get_tags loop, which progressively reduces the DataFrame to only those entries that match the very last filter in your loop. If any category in the filters does not match the categories in the original DataFrame after the first successful filter run, your DataFrame will be empty after that loop.
Adjusting the Mask Logic
In scenarios where mask becomes restrictive progressively, incorporating initially satisfied conditions into a separate or combined DataFrame before applying subsequent filters is key. I'll modify the piece of your code that updates the mask to accumulate valid tags instead of filtering them out for each category iteratively.
Revised Code Strategy
Instead of applying all filters directly through mask, collect valid data for each category first.
After collecting, combine these results (if that suits your desired logic; otherwise, ensure each category's mask doesn't overlap destructively).
Data Aggregation: Loop through each tagger, predict, get tags and append these to a combined DataFrame, combined_tags.
Handle Duplicates: Using drop_duplicates on DataFrame reduces duplicates based solely on the 'name' column. We keep the first occurrence because it might be the highest prediction (or based on another criterion you might choose).
Filter Out Unwanted Tags: Any tags listed in tags_to_remove are excluded from the combined results.
Format Tag Names: Clean and format tag names, ensuring that any underscores or parentheses are handled gracefully.
Construct Output String: Prepend and append texts are added to form the final string that lists all relevant and cleaned tags.
This comprehensive solution should address your requirements for merging tag data from multiple sources, managing duplications, filtering specifics, and formatting for final use. If you have additional output directives or formatting needs, extend the string manipulation as necessary.
Explanation:
All Categories: get_tags() can now process all categories if no category is specified.
Processing Tags Based on Category: When building the list of tag names, the function checks each tag's category. If it matches TagCategory.RATING, it prepends "rating_" to the tag name.
Conditional Formatting: Only ratings have a special formatting rule applied — others render as they were.
By these changes, the function becomes versatile to handle tags from different categories differently based on enumerated values, and implements the specific string formatting requirements you described.
python
# Remove duplication on 'name' by keeping the first occurrence
combined_tags = combined_tags.drop_duplicates(subset='name', keep='first')
# Filter out unwanted tags by names
if tags_to_remove:
combined_tags = combined_tags[~combined_tags['name'].isin(tags_to_remove)]
# Modifying tag names based on category, and creating the string of tag names
tag_list = []
for index, row in combined_tags.iterrows():
tag_name = row['name'].replace('_', ' ').replace('(', '\(').replace(')', '\)')
if row['category'] == TagCategory.RATING.value:
continue # Skip rating premise; adapt as necessary
tag_list.append(tag_name)
tag_string = ", ".join(tag_list)
full_tag_string = f"{prepend}{tag_string}{append}"
return full_tag_string
Conclusion
This approach makes your tagging script more robust and adaptable to different taggers with varying DataFrame output structures. By standardizing the DataFrame columns early in your processing, you simplify downstream tasks and avoid repeated conditional checks based on tagger-specific configurations.
Explanation
Adding Required Tags: Before handling duplicates, the tags_required are converted into a DataFrame and appended. You'll need to ensure that this DataFrame follows the same structure (namely columns like 'name' and 'category') as the combined_tags DataFrame.
Handling Duplicates: Post appending tags_required, the drop_duplicates() function is crucial as it ensures there are no repetitions, including those potentially introduced by required tags.
Final Output: Before returning, the function constructs a tags string, adhering to all specified modifications while ensuring no duplicates.
This approach keeps your tag processing robust and ensures specific required tags are included every time without redundancy, adhering to any specified exclusions as well. If the tags_required are more complex or require specific handling (e.g., custom categories or additional influencing conditions per tag), adjust the DataFrame creation accordingly.
How It Works:
tqdm(os.listdir(img_dir), desc="Processing files"): This wraps the file directory listing with tqdm, which will provide a progress bar in your terminal as files are being processed. The desc parameter is a prefix text to show before the progress bar which adds clarity on what the script is currently processing.
This method provides a simple and effective way to visually track the progression of your file processing within the directory. Each step, as described, is crucial for a clean and efficient implementation of a progress bar. Using tqdm is highly recommended for its ease of use and minimal impact on performance.
But I get an error:
code
Traceback (most recent call last):
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 360, in <module>
caption = check_caption(img_dir, name, CaptioningMode.REPLACE)
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 197, in check_caption
tags_str = generate_tags(img)
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 260, in generate_tags
tags = tagger.get_tags()
File "D:\AI Generation\Projects\AIToolkit\rem-noimagecaps.py", line 109, in get_tags
mask = (self.tags['category'] not in self.category_blacklist)
File "d:\AI Generation\Projects\AIToolkit\.conda\lib\site-packages\pandas\core\generic.py", line 1466, in __nonzero__
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
category_thresholds
&
Specific Category/Threshold Filtering: The method allows for additional filtering based on an optional category or threshold. The mask computed from blacklist and threshold logic is further refined based on these optional parameters.
Miscellaneous: Note the use of .items() in the category thresholds loop, which is the correct method for iterating over a dictionary's key-value pairs in Python.
This redesign helps maintain clarity, correctness in logical operations on pandas DataFrames, and adherence to Python's syntax and pandas API conventions. The get_tags method is now more robust, handling multiple filtering layers efficiently.
def get_tags(self, threshold = None, category: TagCategory = None):
print("Original Data:", self.tags.head()) # Preview original data
# Blacklist categories
mask = ~self.tags['category'].isin([cat.value for cat in self.category_blacklist])
print("After blacklist filter:", self.tags[mask].head()) # Check after applying blacklist
# Apply category threshold filters
for cat, thresh in self.category_thresholds.items():
category_mask = ((self.tags['category'] == cat.value) & (self.tags['predictions'] > thresh))
# Apply mask only to respective category
if mask.any(): # Ensure initial mask isn't empty
mask &= category_mask
else:
mask = category_mask
print(f"After filtering {cat.name} categories:", self.tags[mask].head()) # Output intermediate view after each category filter
# If there is a specific category/threshold filtering
if (category is not None) or (threshold is not None):
extra_mask = ((self.tags['predictions'] > threshold) if threshold is not None else True) & ((self.tags['category'] == category.value) if category is not None else True)
final_tags = self.tags[mask & extra_mask]
print("With specific category or threshold filter:", final_tags.head())
return final_tags
else:
print("Final Filtered Data:", self.tags[mask].head()) # Finally, show what passes all conditions
return self.tags[mask]
Additional Debug Suggestions:
Step-by-step Validation: Validate thresholds for each category manually by temporarily setting them to a very low value to check if any data passes the filters.
Data Inspection: Manually inspect the dataset for any anomalies or unexpected patterns in categories or predictions.
Test with Simpler Conditions: Simplify conditions or reduce the number of conditions to trace which particular filter is overly restrictive.
By adding these debugging steps, you should get better insight into where the data is getting excessively filtered out and adjust your thresholds or conditions accordingly.
def get_tags(self, threshold=None, category: TagCategory=None):
print("Original Data:", self.tags.head()) # Preview original data
# Create a DataFrame to collect valid tags across all categories
valid_tags = pd.DataFrame()
# Iterate over each category to filter and collect tags
for cat, thresh in self.category_thresholds.items():
category_mask = (self.tags['category'] == cat.value) & (self.tags['predictions'] > thresh)
# Collect valid tags per category
filtered_tags = self.tags[category_mask]
print(f"After filtering {cat.name} categories:", filtered_tags.head()) # Check filtering result per category
valid_tags = pd.concat([valid_tags, filtered_tags]).drop_duplicates().reset_index(drop=True)
# Apply blacklist
valid_tags = valid_tags[~valid_tags['category'].isin([cat.value for cat in self.category_blacklist])]
print("After blacklist filter:", valid_tags.head())
if category is not None or threshold is not None:
extra_mask = ((valid_tags['predictions'] > threshold) if threshold is not None else True) & ((valid_tags['category'] == category.value) if category is not None else True)
final_tags = valid_tags[extra_mask]
print("With specific category or threshold filter:", final_tags.head())
return final_tags
else:
print("Final Filtered Data:", valid_tags.head())
return valid_tags
Explanation
Collect then Filter: Instead of initially applying a universal filter and refining, this approach collects valid tags for each category initially and then combines them. This prevents any category with no matching tags from emptying the entire DataFrame.
Manage Blacklist After Collection: The blacklist filter is applied after collecting valid tags to exclude any unwanted categories post-collection.
Avoid Overlapping Filters: Separately handles checking each category against its threshold, accumulates them, ensuring no one category’s exclusive condition wipes other valid tags.
This modification should help to ensure you see a meaningful subset of your data after each category’s filter without losing all entries due to combined conditions.