{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"id": "UEYEdzjgOEOE"
},
"outputs": [],
"source": [
"# @title β³οΈ Load/initialize values\n",
"#Imports\n",
"#!pip install safetensors\n",
"from safetensors.torch import load_file\n",
"import json , os , shelve , torch\n",
"import pandas as pd\n",
"#----#\n",
"\n",
"def my_mkdirs(folder):\n",
" if os.path.exists(folder)==False:\n",
" os.makedirs(folder)\n",
"\n",
"def fix_bad_symbols(txt):\n",
" result = txt\n",
" for symbol in ['^', '}', '{' , ')', '(', '[' , ']' , ':' , '=' ]:\n",
" result = result.replace(symbol,'\\\\' + symbol)\n",
" #------#\n",
" return result;\n",
"\n",
"\n",
"def getPrompts(_path, separator):\n",
"\n",
" path = _path + '/text'\n",
" path_enc = _path + '/text_encodings'\n",
" #-----#\n",
" index = 0\n",
" file_index = 0\n",
" prompts = {}\n",
" text_encodings = {}\n",
" _text_encodings = {}\n",
" #-----#\n",
" for filename in os.listdir(f'{path}'):\n",
"\n",
" print(f'reading {filename}....')\n",
" _index = 0\n",
" %cd {path}\n",
" with open(f'{filename}', 'r') as f:\n",
" data = json.load(f)\n",
" #------#\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" _prompts = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
" for key in _prompts:\n",
" _index = int(key)\n",
" value = _prompts[key]\n",
"\n",
" #Read the 'header' file in the JSON\n",
" if _index <= 0 :\n",
" _NUM_ITEMS = int(value)\n",
" prompts[f'{index}'] = _prompts[f'{_index}'] + separator\n",
" index = index + 1\n",
" continue\n",
" if _index <= 1 :\n",
" _file_name = f'{value}'\n",
" %cd {path_enc}\n",
" _text_encodings = load_file(f'{_file_name}.safetensors')\n",
" #Store text_encodings for the header items\n",
" text_encodings[f'{index-1}'] = _text_encodings[f'{_index-1}']\n",
" text_encodings[f'{index}'] = _text_encodings[f'{_index}']\n",
" #------#\n",
" prompts[f'{index}'] = _prompts[f'{_index}'] + separator\n",
" index = index + 1\n",
" continue\n",
" #------#\n",
" #Read the text_encodings + prompts\n",
" text_encodings[f'{index}'] = _text_encodings[f'{_index}']\n",
" prompts[f'{index}'] = _prompts[f'{_index}'] + separator\n",
" index = index + 1\n",
" continue\n",
" #-------#\n",
" #--------#\n",
" #_text_encodings.close() #close the text_encodings file\n",
" file_index = file_index + 1\n",
" #----------#\n",
" NUM_ITEMS = index -1\n",
" return prompts , text_encodings , NUM_ITEMS\n",
"#--------#\n",
"\n",
"def append_from_url(dictA, tensA , nA , url , separator):\n",
" dictB , tensB, nB = getPrompts(url, separator)\n",
" dictAB = dictA\n",
" tensAB = tensA\n",
" nAB = nA\n",
" for key in dictB:\n",
" nAB = nAB + 1\n",
" dictAB[f'{nA + int(key)}'] = dictB[key]\n",
" tensAB[f'{nA + int(key)}'] = tensB[key]\n",
" #-----#\n",
" return dictAB, tensAB , nAB-1\n",
"#-------#\n",
"\n",
"home_directory = '/content/'\n",
"using_Kaggle = os.environ.get('KAGGLE_URL_BASE','')\n",
"if using_Kaggle : home_directory = '/kaggle/working/'\n",
"%cd {home_directory}\n",
"\n",
"#πΈπΉ\n",
"# Load the data if not already loaded\n",
"try:\n",
" loaded\n",
"except:\n",
" %cd {home_directory}\n",
" !git clone https://huggingface.co/datasets/codeShare/text-to-image-prompts\n",
" loaded = True\n",
"#--------#\n",
"\n",
"#default NEG values\n",
"try: name_NEG\n",
"except: name_NEG = ''\n",
"try: image_NEG\n",
"except: image_NEG = ''\n",
"try: strength_image_NEG\n",
"except: strength_image_NEG = 1\n",
"try: strength_NEG\n",
"except: strength_NEG = 1\n",
"try: NUM_VOCAB_ITEMS\n",
"except: NUM_VOCAB_ITEMS = 0\n",
"try: using_NEG\n",
"except: using_NEG = False\n",
"try: using_image_NEG\n",
"except: using_image_NEG = False\n",
"#------#\n",
"\n",
"def getJSON(path , filename):\n",
" %cd {path}\n",
" with open(f'{filename}', 'r') as f:\n",
" data = json.load(f)\n",
" #------#\n",
" print(f'reading {filename}....')\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" _prompts = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
" return _prompts\n",
"\n",
"#----#\n",
"\n",
"def getPromptsAndLinks(_path):\n",
" path = _path + '/text'\n",
" path_enc = _path + '/text_encodings'\n",
" #-----#\n",
" path_images = _path + '/images'\n",
" path_enc_images = _path + '/image_encodings'\n",
" #----#\n",
" _file_name = ''\n",
" _file_name_image = ''\n",
" #-----#\n",
" index = 0\n",
" prompts = {}\n",
" _prompts = {}\n",
" #-------#\n",
" urls = {}\n",
" _urls = {}\n",
" #------#\n",
" text_encodings = {}\n",
" _text_encodings = {}\n",
" image_encodings = {}\n",
" _image_encodings = {}\n",
" #-----#\n",
" for filename in os.listdir(f'{path}'):\n",
"\n",
" print(f'reading {filename}.json...')\n",
" _index = 0\n",
" %cd {path}\n",
" with open(f'{filename}', 'r') as f:\n",
" data = json.load(f)\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" _prompts = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
"\n",
" for key in _prompts:\n",
" _index = int(key)\n",
" value = _prompts[key]\n",
" if _index<=0: continue\n",
" if _index<=1:\n",
" _file_name = f'{value}'\n",
" _file_name_images = _prompts[f'{0}']\n",
" #-------#\n",
" print(f'reading {_file_name_images}.json..')\n",
" %cd {path_images}\n",
" with open(f'{_file_name_images}.json', 'r') as f:\n",
" data = json.load(f)\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" _urls = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
" #--------#\n",
" %cd {path_enc}\n",
" _text_encodings = load_file(f'{_file_name}.safetensors')\n",
" text_encodings[f'{index-1}'] = _text_encodings[f'{_index-1}']\n",
" text_encodings[f'{index}'] = _text_encodings[f'{_index}']\n",
" #-------#\n",
" %cd {path_enc_images}\n",
" _image_encodings = load_file(f'{_file_name_images}.safetensors')\n",
" image_encodings[f'{index-1}'] = _image_encodings[f'{_index-1}']\n",
" image_encodings[f'{index}'] = _image_encodings[f'{_index}']\n",
" #-------#\n",
" prompts[f'{index-1}'] = _prompts[f'{_index-1}']\n",
" urls[f'{index-1}'] = _urls[f'{_index-1}']\n",
" prompts[f'{index}'] = _prompts[f'{_index}']\n",
" urls[f'{index}'] = _urls[f'{_index}']\n",
" #-------#\n",
" index = index + 1\n",
" continue\n",
" #--------#\n",
" #Read the text_encodings + prompts\n",
" text_encodings[f'{index}'] = _text_encodings[f'{_index}']\n",
" image_encodings[f'{index}'] = _image_encodings[f'{_index}']\n",
" prompts[f'{index}'] = _prompts[f'{_index}']\n",
" urls[f'{index}'] = _urls[f'{_index}']\n",
" index = index + 1\n",
" continue\n",
" #-------#\n",
" #--------#\n",
" #----------#\n",
" NUM_ITEMS = index -1\n",
" return prompts , text_encodings , urls , image_encodings , NUM_ITEMS\n",
"#--------#\n",
"\n"
]
},
{
"cell_type": "code",
"source": [
"# @title π Select items to sample from\n",
"\n",
"prompt_features = True # @param {\"type\":\"boolean\",\"placeholder\":\"π¦\"}\n",
"civitai_blue_set = True # @param {\"type\":\"boolean\",\"placeholder\":\"π\"}\n",
"suffix = True # @param {\"type\":\"boolean\",\"placeholder\":\"πΉ\"}\n",
"prefix = False # @param {\"type\":\"boolean\",\"placeholder\":\"πΈ\"}\n",
"emojis = True # @param {\"type\":\"boolean\",\"placeholder\":\"π\"}\n",
"#------#\n",
"\n",
"first_names = False # @param {\"type\":\"boolean\",\"placeholder\":\"πΉ\"}\n",
"last_names = False # @param {\"type\":\"boolean\",\"placeholder\":\"πΈ\"}\n",
"full_names = False # @param {\"type\":\"boolean\",\"placeholder\":\"π\"}\n",
"celebs = False # @param {\"type\":\"boolean\",\"placeholder\":\"ππ¨\"}\n",
"#-------#\n",
"danbooru_tags = True # @param {\"type\":\"boolean\",\"placeholder\":\"π\"}\n",
"lyrics = False # @param {\"type\":\"boolean\",\"placeholder\":\"πΌ\"}\n",
"tripple_nouns = True # @param {\"type\":\"boolean\",\"placeholder\":\"πΌ\"}\n",
"#-----#\n",
"female_fullnames = False # @param {\"type\":\"boolean\",\"placeholder\":\"π\"}\n",
"debug = False\n",
"#------#\n",
"prompts = {}\n",
"text_encodings = {}\n",
"nA = 0\n",
"#--------#\n",
"\n",
"\n",
"if tripple_nouns:\n",
" url = '/content/text-to-image-prompts/nouns'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"\n",
"if lyrics:\n",
" url = '/content/text-to-image-prompts/lyrics'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"\n",
"if danbooru_tags:\n",
" url = '/content/text-to-image-prompts/danbooru'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if first_names:\n",
" url = '/content/text-to-image-prompts/names/firstnames'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if last_names:\n",
" url = '/content/text-to-image-prompts/names/lastnames'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if full_names:\n",
" url = '/content/text-to-image-prompts/names/fullnames'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if celebs:\n",
" url = '/content/text-to-image-prompts/names/celebs/mixed'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if celebs_young :\n",
" url = '/content/text-to-image-prompts/names/celebs/young'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if female_fullnames:\n",
" url = '/content/text-to-image-prompts/names/fullnames'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"\n",
"if prompt_features:\n",
" url = '/content/text-to-image-prompts/civitai-prompts/green'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"\n",
"if emojis:\n",
" url = '/content/text-to-image-prompts/vocab/text_encodings/emoji'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"\n",
"if civitai_blue_set:\n",
" url = '/content/text-to-image-prompts/civitai-prompts/blue'\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#--------#\n",
"\n",
"if suffix :\n",
" tmp = '/content/text-to-image-prompts/vocab/text_encodings/suffix/'\n",
" for item in ['common','average','rare','weird','exotic'] :\n",
" url = tmp + item\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '')\n",
"#------#\n",
"\n",
"if prefix :\n",
" tmp = '/content/text-to-image-prompts/vocab/text_encodings/prefix/'\n",
" for item in ['common','average','rare','weird','exotic'] :\n",
" url = tmp + item\n",
" prompts , text_encodings, nA = append_from_url(prompts , text_encodings, nA , url , '-')\n",
"#------#\n",
"\n",
"if debug:\n",
" index = 0\n",
" for key in prompts: index = index + 1\n",
" print(index)\n",
" index = 0\n",
" for key in text_encodings : index = index + 1\n",
" print(index)\n",
"#------#\n",
"\n",
"NUM_VOCAB_ITEMS = nA\n",
"text_tensor = torch.zeros(NUM_VOCAB_ITEMS,768)\n",
"for index in range(NUM_VOCAB_ITEMS):\n",
" text_tensor[index] = text_encodings[f'{index}']\n",
"#---------#\n"
],
"metadata": {
"cellView": "form",
"id": "CF53WIAKObg3"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# @title \tβ Use a pre-encoded prompt + image pair from the fusion gen (note: NSFW!)\n",
"\n",
"\n",
"#image_index = 0 # @param {type:'number'}\n",
"# @markdown π₯ Load the data (only required one time)\n",
"load_the_data = False # @param {type:\"boolean\"}\n",
"\n",
"# @markdown πΌοΈ Choose a pre-encoded reference\n",
"index = 829 # @param {type:\"slider\", min:0, max:1668, step:1}\n",
"\n",
"# @markdown βοΈ Set the value for C in the reference
sim = C* text_enc + image_enc*(1-C)
\n",
"\n",
"C = 0.5 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
"\n",
"# @markdown π« Penalize similarity to this prompt(optional)\n",
"\n",
"NEG = '' # @param {type:'string'}\n",
"strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.1}\n",
"\n",
"# @markdown Calculate most similiar items using above settings?\n",
"enable = True # @param {type:\"boolean\"}\n",
"\n",
"if (load_the_data):\n",
" target_prompts , target_text_encodings , urls , target_image_encodings , NUM_ITEMS = getPromptsAndLinks('/content/text-to-image-prompts/fusion')\n",
" from transformers import AutoTokenizer\n",
" tokenizer = AutoTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\", clean_up_tokenization_spaces = False)\n",
" from transformers import CLIPProcessor, CLIPModel\n",
" processor = CLIPProcessor.from_pretrained(\"openai/clip-vit-large-patch14\" , clean_up_tokenization_spaces = True)\n",
" model = CLIPModel.from_pretrained(\"openai/clip-vit-large-patch14\")\n",
" logit_scale = model.logit_scale.exp() #logit_scale = 100.00000762939453\n",
"\n",
"from PIL import Image\n",
"import requests\n",
"prompt = target_prompts[f'{index}']\n",
"url = urls[f'{index}']\n",
"if url.find('perchance')>-1:\n",
" image = Image.open(requests.get(url, stream=True).raw)\n",
"else: print(\"(No image for this ID)\")\n",
"\n",
"print(\"\")\n",
"print(f\"'{prompt}'\")\n",
"print(\"\")\n",
"\n",
"if(enable):\n",
" text_features_A = target_text_encodings[f'{index}']\n",
" image_features_A = target_image_encodings[f'{index}']\n",
"\n",
" # text-similarity\n",
" sims = C * torch.matmul(text_tensor, text_features_A.t())\n",
"\n",
" neg_sims = 0*sims\n",
" if(NEG != ''):\n",
"\n",
" # Get text features for user input\n",
" inputs = tokenizer(text = NEG, padding=True, return_tensors=\"pt\")\n",
" text_features_NEG = model.get_text_features(**inputs)\n",
" text_features_NEG = text_features_A/text_features_A.norm(p=2, dim=-1, keepdim=True)\n",
"\n",
" # text-similarity\n",
" neg_sims = strength*torch.matmul(text_tensor, text_features_NEG.t())\n",
" #------#\n",
"\n",
" # plus image-similarity\n",
" sims = sims + (1-C) * torch.matmul(text_tensor, image_features_A.t()) * logit_scale\n",
"\n",
"\n",
" # minus NEG-similarity\n",
" sims = sims - neg_sims\n",
"\n",
" # Sort the items\n",
" sorted , indices = torch.sort(sims,dim=0 , descending=True)\n",
"\n",
" # @title βοΈπ Print the results (Advanced)\n",
" list_size = 1000 # param {type:'number'}\n",
" start_at_index = 0 # param {type:'number'}\n",
" print_Similarity = True # param {type:\"boolean\"}\n",
" print_Prompts = True # param {type:\"boolean\"}\n",
" print_Prefix = True # param {type:\"boolean\"}\n",
" print_Descriptions = True # param {type:\"boolean\"}\n",
" compact_Output = True # param {type:\"boolean\"}\n",
"\n",
" # @markdown -----------\n",
" # @markdown βοΈπ Printing options\n",
" newline_Separator = True # @param {type:\"boolean\"}\n",
"\n",
" import random\n",
" list_size2 = 1000 # param {type:'number'}\n",
" start_at_index2 = 10000 # param {type:'number'}\n",
" rate_percent = 0 # param {type:\"slider\", min:0, max:100, step:1}\n",
"\n",
" # @markdown Repeat output N times\n",
" N = 6 # @param {type:\"slider\", min:0, max:10, step:1}\n",
"\n",
" # title Show the 100 most similiar suffix and prefix text-encodings to the text encoding\n",
" RANGE = list_size\n",
" separator = '|'\n",
" if newline_Separator : separator = separator + '\\n'\n",
"\n",
" _prompts = ''\n",
" _sims = ''\n",
" for _index in range(start_at_index + RANGE):\n",
" if _index < start_at_index : continue\n",
" index = indices[_index].item()\n",
"\n",
" prompt = prompts[f'{index}']\n",
" if rate_percent >= random.randint(0,100) : prompt = prompts[f'{random.randint(start_at_index2 , start_at_index2 + list_size2)}']\n",
"\n",
" #Remove duplicates\n",
" if _prompts.find(prompt + separator)<=-1:\n",
" _sims = _sims + f'{round(100*sims[index].item(), 2)} %' + separator\n",
" #-------#\n",
" _prompts = _prompts.replace(prompt + separator,'')\n",
" _prompts = _prompts + prompt + separator\n",
" #------#\n",
" #------#\n",
" __prompts = fix_bad_symbols(__prompts)\n",
" __prompts = ('{' + _prompts + '}').replace(separator + '}', '}')\n",
" __sims = ('{' + _sims + '}').replace(separator + '}', '}')\n",
" #------#\n",
"\n",
" if(not print_Prompts): __prompts = ''\n",
" if(not print_Similarity): __sims = ''\n",
"\n",
" if(not compact_Output):\n",
" if(print_Descriptions):\n",
" print(f'The {start_at_index}-{start_at_index + RANGE} most similiar items to prompt : \\n\\n ')\n",
" for i in range(N) : print(__prompts)\n",
" print(f'The {start_at_index}-{start_at_index + RANGE} similarity % for items : \\n\\n' + __sims)\n",
" print('')\n",
" else:\n",
" for i in range(N) : print(__prompts)\n",
" else:\n",
" for i in range(N) : print(__prompts)\n",
" #-------#\n",
" #-------#\n",
"#-------#\n",
"image\n"
],
"metadata": {
"cellView": "form",
"id": "XW3914T8O2uf"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# @title βοΈπ Print the results (Advanced)\n",
"list_size = 1000 # @param {type:'number'}\n",
"start_at_index = 0 # @param {type:'number'}\n",
"print_Similarity = True # @param {type:\"boolean\"}\n",
"print_Prompts = True # @param {type:\"boolean\"}\n",
"print_Descriptions = True # @param {type:\"boolean\"}\n",
"compact_Output = True # @param {type:\"boolean\"}\n",
"newline_Separator = False # @param {type:\"boolean\"}\n",
"\n",
"import random\n",
"# @markdown -----------\n",
"# @markdown Mix with...\n",
"list_size2 = 1000 # @param {type:'number'}\n",
"start_at_index2 = 10000 # @param {type:'number'}\n",
"rate_percent = 0 # @param {type:\"slider\", min:0, max:100, step:1}\n",
"\n",
"# @markdown -----------\n",
"# @markdown Repeat output N times\n",
"N = 6 # @param {type:\"slider\", min:0, max:10, step:1}\n",
"\n",
"# title Show the 100 most similiar suffix and prefix text-encodings to the text encoding\n",
"RANGE = list_size\n",
"separator = '|'\n",
"if newline_Separator : separator = separator + '\\n'\n",
"\n",
"_prompts = ''\n",
"_sims = ''\n",
"for _index in range(start_at_index + RANGE):\n",
" if _index < start_at_index : continue\n",
" index = indices[_index].item()\n",
"\n",
" prompt = prompts[f'{index}']\n",
" if rate_percent >= random.randint(0,100) : prompt = prompts[f'{random.randint(start_at_index2 , start_at_index2 + list_size2)}']\n",
"\n",
" #Remove duplicates\n",
" if _prompts.find(prompt + separator)<=-1:\n",
" _sims = _sims + f'{round(100*sims[index].item(), 2)} %' + separator\n",
" #-------#\n",
" _prompts = _prompts.replace(prompt + separator,'')\n",
" _prompts = _prompts + prompt + separator\n",
" #------#\n",
"#------#\n",
"__prompts = fix_bad_symbols(__prompts)\n",
"__prompts = ('{' + _prompts + '}').replace(separator + '}', '}')\n",
"__sims = ('{' + _sims + '}').replace(separator + '}', '}')\n",
"#------#\n",
"\n",
"if(not print_Prompts): __prompts = ''\n",
"if(not print_Similarity): __sims = ''\n",
"\n",
"if(not compact_Output):\n",
" if(print_Descriptions):\n",
" print(f'The {start_at_index}-{start_at_index + RANGE} most similiar items to prompt : \\n\\n ')\n",
" for i in range(N) : print(__prompts)\n",
" print(f'The {start_at_index}-{start_at_index + RANGE} similarity % for items : \\n\\n' + __sims)\n",
" print('')\n",
" else:\n",
" for i in range(N) : print(__prompts)\n",
"else:\n",
" for i in range(N) : print(__prompts)\n",
"#-------#"
],
"metadata": {
"cellView": "form",
"id": "EdBiAguJO9aX"
},
"execution_count": null,
"outputs": []
}
]
}