{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "Try this Free online SD 1.5 generator with the results: https://perchance.org/fusion-ai-image-generator\n", "\n", " This Notebook is a Stable-diffusion tool which allows you to find similiar prompts to an existing prompt. It uses the Nearest Neighbor decoder method listed here:https://arxiv.org/pdf/2303.03032" ], "metadata": { "id": "cRV2YWomjMBU" } }, { "cell_type": "code", "execution_count": 1, "metadata": { "id": "UEYEdzjgOEOE", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "efa821e0-8c2d-4861-9d99-f08cacb2e85f" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "/content\n", "/content\n", "Cloning into 'text-to-image-prompts'...\n", "remote: Enumerating objects: 4504, done.\u001b[K\n", "remote: Counting objects: 100% (4504/4504), done.\u001b[K\n", "remote: Compressing objects: 100% (4029/4029), done.\u001b[K\n", "remote: Total 4504 (delta 659), reused 2366 (delta 418), pack-reused 0 (from 0)\u001b[K\n", "Receiving objects: 100% (4504/4504), 32.32 MiB | 3.25 MiB/s, done.\n", "Resolving deltas: 100% (659/659), done.\n", "Updating files: 100% (3062/3062), done.\n", "Filtering content: 100% (768/768), 2.21 GiB | 48.63 MiB/s, done.\n" ] } ], "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", "celebs = True # @param {\"type\":\"boolean\",\"placeholder\":\"πŸ†”πŸ‘¨\"}\n", "#-------#\n", "danbooru_tags = True # @param {\"type\":\"boolean\",\"placeholder\":\"πŸŽ€\"}\n", "lyrics = True # @param {\"type\":\"boolean\",\"placeholder\":\"🎼\"}\n", "tripple_nouns = True # @param {\"type\":\"boolean\",\"placeholder\":\"🎼\"}\n", "#-----#\n", "female_fullnames = True # @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 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 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": { "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", "#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 = 708 # @param {type:\"slider\", min:0, max:1666, step:1}\n", "\n", "PROMPT_INDEX = index\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 = False # @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 = 7 # @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": { "id": "XW3914T8O2uf" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "The savefile can be used here : https://perchance.org/fusion-ai-image-generator" ], "metadata": { "id": "JldNmWy1iyvK" } }, { "cell_type": "code", "source": [ "# @title \tβš„ Create fusion-generator .json savefile from result\n", "filename = 'blank.json'\n", "path = '/content/text-to-image-prompts/fusion/'\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", "_savefile = {\n", " key : value for key, value in _df.items()\n", "}\n", "#------#\n", "from safetensors.torch import load_file\n", "import json , os , torch\n", "import pandas as pd\n", "#----#\n", "def my_mkdirs(folder):\n", " if os.path.exists(folder)==False:\n", " os.makedirs(folder)\n", "#------#\n", "savefile_prompt = ''\n", "for i in range(N) : savefile_prompt = savefile_prompt + ' ' + __prompts\n", "_savefile['main'] = savefile_prompt.replace('\\n', ' ').replace(' ', ' ').replace(' ', ' ')\n", "#------#\n", "save_filename = f'fusion_C05_X7_1000_{PROMPT_INDEX}.json'\n", "output_folder = '/content/output/savefiles/'\n", "my_mkdirs(output_folder)\n", "#-----#\n", "%cd {output_folder}\n", "print(f'Saving segment {save_filename} to {output_folder}...')\n", "with open(save_filename, 'w') as f:\n", " json.dump(_savefile, f)\n" ], "metadata": { "id": "Q7vpNAXQilbf" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# @title \tβš„ Create a savefile-set from the entire range of pre-encoded items\n", "\n", "#image_index = 0 # @param {type:'number'}\n", "# @markdown πŸ“₯ Load the data (only required one time)\n", "load_the_data = True # @param {type:\"boolean\"}\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", "if(load_the_data):\n", " from PIL import Image\n", " import requests\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", "\n", "filename = 'blank.json'\n", "path = '/content/text-to-image-prompts/fusion/'\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", "_blank = {\n", " key : value for key, value in _df.items()\n", "}\n", "#------#\n", "\n", "root_savefile_name = 'fusion_C05_X7_1000_'\n", "output_folder = '/content/output/savefiles/'\n", "my_mkdirs(output_folder)\n", "NEG = '' # @param {type:'string'}\n", "strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.1}\n", "\n", "for index in range(1667):\n", "\n", " PROMPT_INDEX = index\n", "\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: continue #print(\"(No image for this ID)\")\n", "\n", " print(f\"no. {PROMPT_INDEX} : '{prompt}'\")\n", "\n", "\n", " if(True):\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", " # 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 = False # @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 = 7 # @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", " _savefile = _blank\n", " from safetensors.torch import load_file\n", " import json , os , torch\n", " import pandas as pd\n", " #----#\n", " def my_mkdirs(folder):\n", " if os.path.exists(folder)==False:\n", " os.makedirs(folder)\n", " #------#\n", " savefile_prompt = ''\n", " for i in range(N) : savefile_prompt = savefile_prompt + ' ' + __prompts\n", " _savefile['main'] = savefile_prompt.replace('\\n', ' ').replace(' ', ' ').replace(' ', ' ')\n", " #------#\n", " save_filename = f'{root_savefile_name}{PROMPT_INDEX}.json'\n", " #-----#\n", " %cd {output_folder}\n", " print(f'Saving savefile {save_filename} to {output_folder}...')\n", " with open(save_filename, 'w') as f:\n", " json.dump(_savefile, f)\n", " #---------#\n", " continue\n", "#-----------#\n", "\n" ], "metadata": { "id": "x1uAVXZEoL0T" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Determine if this notebook is running on Colab or Kaggle\n", "#Use https://www.kaggle.com/ if Google Colab GPU is busy\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", "# @title Download the text_encodings as .zip\n", "import os\n", "%cd {home_directory}\n", "#os.remove(f'{home_directory}results.zip')\n", "root_output_folder = home_directory + 'output/'\n", "zip_dest = f'{home_directory}results.zip'\n", "!zip -r {zip_dest} {root_output_folder}" ], "metadata": { "id": "zivBNrw9uSVD" }, "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": { "id": "EdBiAguJO9aX" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "output_folder = '/content/output/fusion-gen-savefiles/'\n", "index = 0\n", "path = '/content/text-to-image-prompts/fusion-gen-savefiles'\n", "\n", "def my_mkdirs(folder):\n", " if os.path.exists(folder)==False:\n", " os.makedirs(folder)\n", "\n", "my_mkdirs(output_folder)\n", "for filename in os.listdir(f'{path}'):\n", " if filename.find('fusion_C05_X7_1000_')<=-1: continue\n", " print(f'reading {filename}...')\n", " %cd {path}\n", " with open(f'{filename}', 'r') as f:\n", " data = json.load(f)\n", " _df = pd.DataFrame({'count': data})['count']\n", " _savefile = {\n", " key : value for key, value in _df.items()\n", " }\n", "\n", " _savefile2 = {}\n", "\n", " for key in _savefile:\n", " _savefile2[key] = _savefile[key]\n", " if(key == \"_main\") :\n", " _savefile2[key] = \"Prompt input only ✏️\"\n", " print(\"changed\")\n", " #----------#\n", "\n", " save_filename = f'fusion_C05_X7_1000_{index}.json'\n", " index = index + 1\n", "\n", " %cd {output_folder}\n", " print(f'Saving savefile {save_filename} to {output_folder}...')\n", " with open(save_filename, 'w') as f:\n", " json.dump(_savefile2, f)" ], "metadata": { "id": "A3ASDnO3IzSL" }, "execution_count": null, "outputs": [] } ] }