Automatically Tag and Import NovelAI Images for Hydrus
by MiyaNya/.yamii.
This is a script for generating "sidecars" which are files containing tags that Hydrus will import alongside your NovelAI generated images.
Prerequisites:
Using the script:
- Create a folder to set up the process. DO NOT PUT IT IN THE SAME FOLDER AS HYDRUS.
- Inside this folder, create a file named
generate_sidecars.py
- Add the code below inside it. Save the file.
- Make a folder called
import_images
, and put your images there. - Run CMD in the folder with the py file. Then, execute
py -m pip install pillow
. - Once pillow is installed,
py generate_sidecars.py
- Now your import folder will be full of text files containing the tags for the images.
Importing to Hydrus:
- file -> import files...
- Add folder, find the import_images folder.
- Add tags/urls with the import >>
- At the top, click the sidecars tab.
- add -> add -> a .txt sidecar
- Check "remove file .ext?"
- apply -> apply -> apply
Code
import os
from PIL import Image
import json
import re
def main():
= ".\\import_images" # rename this to your folder of choice
dirPath
= os.listdir(dirPath)
filelist
for root, dirs, files in reversed(list(os.walk(dirPath))):
for filename in reversed(files):
if not(filename.endswith(".png")):
continue
= os.path.join(root, filename)
image_path = os.path.splitext(image_path)[0] + ".txt"
sidecar_path
if os.path.isfile(sidecar_path):
continue
= Image.open(image_path)
im = json.loads(im.info['Comment']) if 'Comment' in im.info else ''
comment
= ''
tags if 'actual_prompts' in comment:
= comment["actual_prompts"]["prompt"]["base_caption"].lower()
tags for char_prompt in comment["actual_prompts"]["prompt"]["char_captions"]:
+= ', ' + char_prompt["char_caption"].lower()
tags elif 'Description' in im.info:
= im.info['Description'].lower()
tags if 'v4_prompt' in comment and 'char_captions' in comment['v4_prompt']['caption']:
for char_prompt in comment['v4_prompt']['caption']['char_captions']:
+= ', ' + char_prompt['char_caption'].lower()
tags else:
print(im.info)
continue
= tags.replace("[","")
tags = tags.replace("]","")
tags = tags.replace("{","")
tags = tags.replace("}","")
tags = re.sub(r'-\d*\.?\d*::.*?::', '', tags) # remove tags with negative emphasis
tags = re.sub(r'-?\d*\.?\d*::', '', tags) # remove all ## and any number behind it
tags #tags = re.sub(r'(?<!\d)\b(girl|boy)\b', '', tags)
= [x.strip() for x in re.split(r'[.,|]', tags)]
tag_array
'model:' + im.info["Source"])
tag_array.append('sampler:' + comment["sampler"])
tag_array.append(
= '\n'.join(tag_array)
sidecar_text
print(sidecar_path)
write_to_file(sidecar_path, sidecar_text)
def write_to_file (output_file, output_string):
with open(output_file, 'w', encoding='utf-8') as file:
file.write(output_string)
if __name__ == '__main__':
main()
# by .yamii.```