File size: 43,157 Bytes
40b69ae b7c4ce7 aa5cf88 b2c7214 40b69ae b2c7214 40b69ae b2c7214 50a3003 f7ca9e8 b2c7214 aa5cf88 50a3003 aa5cf88 db315c0 40b69ae b2c7214 40b69ae b2c7214 40b69ae aa5cf88 b7c4ce7 f7ca9e8 b7c4ce7 f7ca9e8 b7c4ce7 f7ca9e8 f784759 0a029f8 e1e2545 f784759 b7c4ce7 f784759 f7ca9e8 b7c4ce7 c56de2f f7ca9e8 53e9423 f7ca9e8 68bbfd3 c56de2f b7c4ce7 c56de2f 3d20c7d c56de2f b7c4ce7 c56de2f aa5cf88 b7c4ce7 f784759 50a3003 f784759 0c51235 aa5cf88 50a3003 f784759 50a3003 f7ca9e8 f784759 50a3003 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 aa5cf88 b7c4ce7 aa5cf88 6362a04 aa5cf88 c56de2f aa5cf88 b7c4ce7 f784759 50a3003 f784759 50a3003 aa5cf88 f784759 f7ca9e8 f784759 50a3003 f7ca9e8 f784759 50a3003 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 aa5cf88 b7c4ce7 aa5cf88 6362a04 aa5cf88 0c51235 68bbfd3 0c51235 68bbfd3 0c51235 aa5cf88 b7c4ce7 f784759 50a3003 f784759 50a3003 aa5cf88 f784759 aa5cf88 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 f784759 f7ca9e8 aa5cf88 c56de2f f784759 c56de2f f784759 c56de2f 53e9423 c56de2f f784759 c56de2f aa5cf88 b7c4ce7 aa5cf88 030623c b91416c 030623c f784759 e1e2545 f784759 e1e2545 f784759 aa5cf88 f784759 944dcdd aa5cf88 0c51235 aa5cf88 56285d0 aa5cf88 56285d0 aa5cf88 40b69ae 21a36a2 56285d0 21a36a2 aa5cf88 e1e2545 aa5cf88 40b69ae aa5cf88 db315c0 aa5cf88 944dcdd aa5cf88 db315c0 aa5cf88 db315c0 0c51235 db315c0 aa5cf88 944dcdd aa5cf88 db315c0 aa5cf88 944dcdd aa5cf88 db315c0 0c51235 db315c0 aa5cf88 827c2f9 944dcdd 827c2f9 944dcdd aa5cf88 944dcdd db315c0 e1e2545 aa5cf88 db315c0 827c2f9 aa5cf88 db315c0 0c51235 e1e2545 030623c f9c6571 50a3003 f9c6571 030623c e1e2545 b2c7214 b91416c db315c0 0c51235 db315c0 c56de2f e1e2545 b91416c e1e2545 b91416c e1e2545 50a3003 030623c 50a3003 db315c0 aa5cf88 f9c6571 db315c0 aa5cf88 50a3003 030623c 50a3003 aa5cf88 50a3003 aa5cf88 50a3003 aa5cf88 827c2f9 aa5cf88 f9c6571 aa5cf88 db315c0 030623c b2c7214 50a3003 40b69ae |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 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 573 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 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"source": [
"# @title β π Initialize\n",
"\n",
"import os\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",
"def fix_bad_symbols(txt):\n",
" result = txt\n",
" for symbol in ['^', '}', '{' , ')', '(', '[' , ']' , ':' , '=' ]:\n",
" result = result.replace(symbol,'\\\\' + symbol)\n",
" #------#\n",
" return result;\n",
"\n",
"def my_mkdirs(folder):\n",
" if os.path.exists(folder)==False:\n",
" os.makedirs(folder)\n",
"\n",
"#πΈπΉ\n",
"# Load the data if not already loaded\n",
"try:\n",
" loaded\n",
"except:\n",
" from safetensors.torch import load_file , save_file\n",
" import json , torch , requests , math\n",
" import pandas as pd\n",
" from PIL import Image\n",
" import cv2\n",
" from matplotlib import pyplot as plt\n",
" #----#\n",
" %cd {home_directory}\n",
" !git clone https://huggingface.co/datasets/codeShare/fusion-t2i-generator-data\n",
" loaded = True\n",
" %cd {home_directory + 'fusion-t2i-generator-data/'}\n",
" !unzip reference.zip\n",
"\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",
"%cd {home_directory + 'fusion-t2i-generator-data/' + 'reference'}\n",
"with open(f'reference_prompts.json', 'r') as f:\n",
" data = json.load(f)\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" target_prompts = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
"#------#\n",
"with open(f'reference_urls.json', 'r') as f:\n",
" data = json.load(f)\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" target_urls = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
"\n",
"#------#\n",
"dot_dtype = torch.float32\n",
"dim = 768\n",
"ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"\n",
"# title β Define parameters for visalizing the reference in a 16x16 grid <br> (the visualization settings has no effect on output)\n",
"from PIL import Image, ImageDraw\n",
"SCALE = 0.0002 # param {type:\"slider\", min:0.0001, max:0.001, step:0.00001}\n",
"ZERO_POINT = 100 # param {type:\"slider\", min:0, max:300, step:1}\n",
"CELL_SIZE = 16\n",
"image_size = 0.5 # param {type:\"slider\", min:0, max:1, step:0.01}\n",
"show_encoding = False # param {type:\"boolean\"}\n",
"#------#\n",
"\n",
"BORDER_THICKNESS = 4\n",
"\n",
"def visualize(_ref):\n",
" RGB_tensor = (torch.round(_ref/SCALE)+torch.ones(dim)*ZERO_POINT)\n",
" cellsize = CELL_SIZE\n",
" tick = round(cellsize/2)\n",
" border_offset = round(BORDER_THICKNESS/2)\n",
" width = 16*cellsize + BORDER_THICKNESS\n",
" height = 16*cellsize + BORDER_THICKNESS\n",
" image = Image.new('RGB', (width, height), (0, 0, 0))\n",
" draw = ImageDraw.Draw(image)\n",
" for row in range(16):\n",
" for col in range(16):\n",
" tmp = 3*row*col\n",
" r = max(0,min(255,int(RGB_tensor[tmp].item())))\n",
" g = max(0,min(255,int(RGB_tensor[tmp+1].item())))\n",
" b = max(0,min(255,int(RGB_tensor[tmp+2].item())))\n",
" fillColor = (r,g,b)\n",
" x0 = row*cellsize +border_offset\n",
" y0 = (15-col)*cellsize +border_offset\n",
" x1 = row*cellsize + 2*tick + border_offset\n",
" y1 = (15-col)*cellsize + 2*tick + border_offset\n",
" shape = [(x0, y0), (x1, y1)]\n",
" draw.rectangle(shape, fill=fillColor, outline=(0,0,0))\n",
" return (image)\n",
"\n",
"num_plots = 1\n",
"try:\n",
" %cd /content/\n",
" _ref = load_file('reference.safetensors' )\n",
" num_plots = num_plots+1\n",
"except: _ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"#-----#\n",
"try: ref\n",
"except: ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"\n",
"\n",
"if show_encoding:\n",
" # create figure\n",
" fig = plt.figure(figsize=(10*image_size, 10*image_size))\n",
" fig.patch.set_facecolor((56/255,56/255,56/255))\n",
" rows = 1\n",
" columns = num_plots\n",
" fig.add_subplot(rows, columns, 1)\n",
" plt.imshow( visualize(ref))\n",
" plt.axis('off')\n",
" plt.title( \"Encoding (local variable)\", color='white', fontsize=round(20*image_size))\n",
" if num_plots>1:\n",
" fig.add_subplot(rows, columns, 2)\n",
" plt.imshow( visualize( _ref['weights'].to(dot_dtype)))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (saved file)\", color='white', fontsize=round(20*image_size))\n",
" #------#\n",
"\n",
"print(f'Using settings SCALE = {SCALE} and ZERO_POINT = {ZERO_POINT} for visualizing the text_encoding')"
],
"metadata": {
"id": "TC5lMJrS1HCC",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# @title β π·π Use pre-encoded image+prompt pair\n",
"loaded_ref = False\n",
"try:\n",
" ref\n",
" loaded_ref = True\n",
"except:ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"if loaded_ref : prev_ref = ref.clone().detach()\n",
"\n",
"try:prompt\n",
"except: prompt = ''\n",
"\n",
"# @markdown πΌοΈ+π Choose a pre-encoded reference (note: some results are NSFW!)\n",
"index = 596 # @param {type:\"slider\", min:0, max:1666, step:1}\n",
"PROMPT_INDEX = index\n",
"prompt = target_prompts[f'{PROMPT_INDEX}']\n",
"url = target_urls[f'{PROMPT_INDEX}']\n",
"if url.find('perchance')>-1:\n",
" image = Image.open(requests.get(url, stream=True).raw)\n",
"#------#\n",
"%cd {home_directory + 'fusion-t2i-generator-data/' + 'reference'}\n",
"references = torch.load('reference_text_and_image_encodings.pt' , weights_only=False)\n",
"# @markdown βοΈ πΌοΈ encoding <-----?-----> π encoding </div> <br>\n",
"C = 0.3 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
"log_strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"method = 'Add to existing ref' # @param [\"Refresh\" , \"Add to existing ref\" , \"Subtract from existing ref\" , \"Do nothing\"]\n",
"image_size = 0.57 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
"show_encoding = True # @param {type:\"boolean\"}\n",
"\n",
"if(not method == 'Do nothing'):\n",
" if method == 'Refresh': ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
" if method == 'Subtract from existing ref':\n",
" ref = torch.sub(ref, math.pow(10 ,log_strength-1) * C * references[index][0].dequantize().to(dtype = torch.float32))\n",
" ref = torch.sub(ref, math.pow(10 ,log_strength-1) * (1-C) * references[index][1].dequantize().to(dtype = torch.float32))\n",
" else:\n",
" ref = torch.add(ref, math.pow(10 ,log_strength-1) * C * references[index][0].dequantize().to(dtype = torch.float32))\n",
" ref = torch.add(ref, math.pow(10 ,log_strength-1) * (1-C) * references[index][1].dequantize().to(dtype = torch.float32))\n",
" #---------#\n",
" references = '' # Clear up memory\n",
" ref = ref/ref.norm(p=2, dim=-1, keepdim=True)\n",
" ref = ref.clone().detach()\n",
" #------#\n",
" # create figure\n",
" fig = plt.figure(figsize=(10*image_size, 10*image_size))\n",
" fig.patch.set_facecolor((56/255,56/255,56/255))\n",
" rows = 1\n",
" columns = 1\n",
" if show_encoding: columns = columns+1\n",
" if show_encoding and loaded_ref : columns = columns+1\n",
" fig.add_subplot(rows, columns, 1)\n",
" plt.imshow(image)\n",
" plt.axis('off')\n",
" plt.title(f\"Reference image at index={index}\" , color='white' , fontsize=round(20*image_size))\n",
" #-----#\n",
" if show_encoding and loaded_ref:\n",
" fig.add_subplot(rows, columns, columns-1)\n",
" plt.imshow( visualize(prev_ref))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (before)\" , color='white' , fontsize=round(20*image_size))\n",
" print(f'Prompt for this image : \\n\\n \"{prompt} \" \\n\\n')\n",
"\n",
" if show_encoding:\n",
" fig.add_subplot(rows, columns, columns)\n",
" plt.imshow( visualize(ref))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (now)\" , color='white' , fontsize=round(20*image_size))\n",
" #------#\n"
],
"metadata": {
"id": "BwrEs5zVB0Sb",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Other methods"
],
"metadata": {
"id": "f9_AcquM7AYZ"
}
},
{
"cell_type": "code",
"source": [
"# @title β 𧩠Create an encoding\n",
"# @markdown π Write a text prompt (this will overwrite any savefile already stored)\n",
"NEW_ENCODING = '' # @param {type:'string' ,placeholder:'write a prompt'}\n",
"enable = True # @param {type:\"boolean\"}\n",
"# @markdown -----\n",
"# @markdown π Enhance/Penalize Similarity and skip items containing word(s)\n",
"POS = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"NEG = ''# @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"# @markdown -----\n",
"# @markdown logarithmic prompt strength x for value 10^(x-1)\n",
"_POS = 0 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"_NEG = 0 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"# @markdown -----\n",
"# @markdown Check similiarity for this encoding against any written prompt(s)\n",
"# @title β Evaluate saved reference similarity to select items (optional)\n",
"EVAL = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"\n",
"show_local_reference = True # @param {type:\"boolean\"}\n",
"show_encoding = True # @param {type:\"boolean\"}\n",
"\n",
"try:\n",
" %cd /content/\n",
" _ref = load_file('reference.safetensors' )\n",
" ref = _ref['weights'].to(dot_dtype)\n",
"except:\n",
" ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
" _ref = {}\n",
" _ref['weights'] = ref\n",
" %cd /content/\n",
" save_file(_ref, 'reference.safetensors')\n",
"#-----#\n",
"\n",
"if NEW_ENCODING.strip() != '':\n",
" item = NEW_ENCODING.strip()\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" ref = model.get_text_features(**inputs)[0]\n",
" ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n",
"#------#\n",
"\n",
"try: ref\n",
"except: ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"\n",
"if EVAL.strip() != '':\n",
" print(\"Saved Reference:\\n\")\n",
" for item in EVAL.split(','):\n",
" if item.strip()=='':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" test = model.get_text_features(**inputs)[0]\n",
" test = test/test.norm(p=2 , dim = -1 , keepdim = True)\n",
" ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n",
" eval = torch.dot(ref , test)\n",
" print(f'{item.strip()} : {round(eval.item()*100, 2)}%')\n",
" #-----#\n",
" if(show_local_reference):\n",
" print(\"\\n---------\\nLocal Reference with enchancements added :\\n\")\n",
"\n",
" for _item in POS.split(','):\n",
" item = _item.strip()\n",
" if item == '':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" ref = ref + math.pow(10,_POS-1) * model.get_text_features(**inputs)[0]\n",
" #-------#\n",
"\n",
" for _item in NEG.split(','):\n",
" item = _item.strip()\n",
" if item == '':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" ref = ref + math.pow(10,_NEG-1) * model.get_text_features(**inputs)[0]\n",
" #-------#\n",
"\n",
" ref= ref/ref.norm(p=2 , dim=-1 , keepdim=True)\n",
" for item in EVAL.split(','):\n",
" if item.strip()=='':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" test = model.get_text_features(**inputs)[0]\n",
" test = test/test.norm(p=2 , dim = -1 , keepdim = True)\n",
" eval = torch.dot(ref , test)\n",
" print(f'{item.strip()} : {round(eval.item()*100, 2)}%')\n",
" #-----#\n",
"\n",
" if show_encoding:\n",
" # create figure\n",
" fig = plt.figure(figsize=(10*image_size, 10*image_size))\n",
" fig.patch.set_facecolor((56/255,56/255,56/255))\n",
" rows = 1\n",
" columns = 3\n",
" fig.add_subplot(rows, columns, 1)\n",
" plt.imshow( visualize(ref))\n",
" plt.axis('off')\n",
" plt.title( \"Encoding (local variable)\", color='white', fontsize=round(20*image_size))\n",
" if num_plots>1:\n",
" fig.add_subplot(rows, columns, 2)\n",
" plt.imshow( visualize( _ref['weights'].to(dot_dtype)))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (saved file)\", color='white', fontsize=round(20*image_size))\n",
"\n",
" fig.add_subplot(rows, columns, 3)\n",
" plt.imshow( visualize(ref - _ref['weights'].to(dot_dtype)))\n",
" plt.axis('off')\n",
" plt.title(\"Changes\", color='white', fontsize=round(20*image_size))\n",
" #------#\n",
"\n",
"\n"
],
"metadata": {
"id": "Oxi6nOyrUTAe",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Use an image as a reference via URL (optional)**"
],
"metadata": {
"id": "KI9Ho6CG7m3Z"
}
},
{
"cell_type": "code",
"source": [
"# @title β ππΌοΈ Load an image via URL\n",
"loaded_ref = False\n",
"try:\n",
" ref\n",
" loaded_ref = True\n",
"except:ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"if loaded_ref : prev_ref = ref.clone().detach()\n",
"\n",
"try:prompt\n",
"except: prompt = ''\n",
"\n",
"# @markdown πΌοΈ Upload your own image for use as reference via URL (optional)\n",
"URL = '' # @param {type:'string' ,placeholder:'paste an url here'}\n",
"if URL.strip() != '':\n",
" image = Image.open(requests.get(URL, stream=True).raw)\n",
" log_strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
" method = 'Add to existing ref' # @param [\"Refresh\" , \"Add to existing ref\" , \"Subtract from existing ref\" , \"Do nothing\"]\n",
" image_size = 0.79 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
" show_encoding = True # @param {type:\"boolean\"}\n",
" #---------#\n",
" if(not method == 'Do nothing'):\n",
" # Get image features\n",
" inputs = processor(images=image, return_tensors=\"pt\")\n",
" image_features = model.get_image_features(**inputs)\n",
" image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True)\n",
" #-------#\n",
" if method == 'Refresh':\n",
" ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
" if method == 'Subtract from existing ref':\n",
" ref = ref - math.pow(10,log_strength-1)*image_features\n",
" else: ref = ref + math.pow(10,log_strength-1)*image_features\n",
" #-----#\n",
" ref = ref/ref.norm(p=2, dim=-1, keepdim=True)\n",
" ref = ref[0]\n",
" ref = ref.clone().detach()\n",
" #------#\n",
" # create figure\n",
" fig = plt.figure(figsize=(10*image_size, 10*image_size))\n",
" fig.patch.set_facecolor((56/255,56/255,56/255))\n",
" rows = 1\n",
" columns = 1\n",
" if show_encoding: columns = 2\n",
" if show_encoding and loaded_ref : columns = 3\n",
" fig.add_subplot(rows, columns, 1)\n",
" plt.imshow(image)\n",
" plt.axis('off')\n",
" plt.title(\"Reference image from URL\" , color='white' , fontsize=round(20*image_size))\n",
" #-----#\n",
" if show_encoding and loaded_ref:\n",
" fig.add_subplot(rows, columns, columns-1)\n",
" plt.imshow( visualize(prev_ref))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (before)\" , color='white' , fontsize=round(20*image_size))\n",
" if show_encoding:\n",
" fig.add_subplot(rows, columns, columns)\n",
" plt.imshow( visualize(ref))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (now)\" , color='white' , fontsize=round(20*image_size))\n",
" #------#"
],
"metadata": {
"id": "IqUsiQw2HU2C",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Use an image as a reference via uploading it to the /content/ folder (optional)**"
],
"metadata": {
"id": "MBPi7F8S7tg3"
}
},
{
"cell_type": "code",
"source": [
"# @title β ππΌοΈ Use an uploaded image as reference\n",
"loaded_ref = False\n",
"try:\n",
" ref\n",
" loaded_ref = True\n",
"except:ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"if loaded_ref : prev_ref = ref.clone().detach()\n",
"\n",
"try:prompt\n",
"except: prompt = ''\n",
"\n",
"# @markdown πΌοΈ Upload your own image for use as reference via URL (optional)\n",
"FILENAME = '' # @param {type:'string' ,placeholder:'IMG_123.png'}\n",
"log_strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"method = 'Add to existing ref' # @param [\"Refresh\" , \"Add to existing ref\" , \"Subtract from existing ref\" , \"Do nothing\"]\n",
"image_size = 0.5 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
"show_encoding = True # @param {type:\"boolean\"}\n",
"\n",
"if FILENAME.strip() != '':\n",
" %cd /content/\n",
" image = cv2.imread(FILENAME)\n",
" b,g,r = cv2.split(image)\n",
" image = cv2.merge([r,g,b])\n",
" #---------#\n",
" if(not method == 'Do nothing'):\n",
" # Get image features\n",
" inputs = processor(images=image, return_tensors=\"pt\")\n",
" image_features = model.get_image_features(**inputs)\n",
" image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True)\n",
" #-------#\n",
" if method == 'Refresh':\n",
" ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
" if method == 'Subtract from existing ref':\n",
" ref = ref - math.pow(10,log_strength-1)*image_features\n",
" else: ref = ref + math.pow(10,log_strength-1)*image_features\n",
" #-----#\n",
" ref = ref/ref.norm(p=2, dim=-1, keepdim=True)\n",
" ref = ref[0]\n",
" ref = ref.clone().detach()\n",
" #------#\n",
" # create figure\n",
" fig = plt.figure(figsize=(10*image_size, 10*image_size))\n",
" fig.patch.set_facecolor((56/255,56/255,56/255))\n",
" rows = 1\n",
" columns = 1\n",
" if show_encoding: columns = 2\n",
" if show_encoding and loaded_ref : columns = 3\n",
" fig.add_subplot(rows, columns, 1)\n",
" plt.imshow(image)\n",
" plt.axis('off')\n",
" plt.title(f\"Reference image from uploaded image {FILENAME}\" , color='white' , fontsize=round(20*image_size))\n",
" #-----#\n",
" if show_encoding and loaded_ref:\n",
" fig.add_subplot(rows, columns, columns-1)\n",
" plt.imshow( visualize(prev_ref))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (before)\" , color='white' , fontsize=round(20*image_size))\n",
" if show_encoding:\n",
" fig.add_subplot(rows, columns, columns)\n",
" plt.imshow( visualize(ref))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (now)\" , color='white' , fontsize=round(20*image_size))\n",
" #------#"
],
"metadata": {
"id": "I_-GOwFPKkha",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Search prompts using CLIP"
],
"metadata": {
"id": "UqrYOkhlEQdM"
}
},
{
"cell_type": "code",
"source": [
"# @title β πΎ Save the reference\n",
"\n",
"loaded_ref = False\n",
"try:\n",
" ref\n",
" loaded_ref = True\n",
"except:ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"if loaded_ref : prev_ref = ref.clone().detach()\n",
"\n",
"try:prompt\n",
"except: prompt = ''\n",
"\n",
"reset_everything = False # @param {type:\"boolean\"}\n",
"_ref = {}\n",
"ref = ref/ref.norm(p=2, dim=-1, keepdim=True)\n",
"if (reset_everything) : ref = torch.zeros(dim).to(dtype = dot_dtype)\n",
"_ref['weights'] = ref.to(dot_dtype)\n",
"%cd /content/\n",
"save_file(_ref , 'reference.safetensors' )\n",
"image_size = 0.5 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
"show_encoding = True # @param {type:\"boolean\"}\n",
"#------#\n",
"print(\"Saved local encoding to reference.safetensors\")\n",
"if show_encoding:\n",
" # create figure\n",
" fig = plt.figure(figsize=(10*image_size, 10*image_size))\n",
" fig.patch.set_facecolor((56/255,56/255,56/255))\n",
" rows = 1\n",
" columns = num_plots\n",
" fig.add_subplot(rows, columns, 1)\n",
" plt.imshow( visualize(ref))\n",
" plt.axis('off')\n",
" plt.title( \"Encoding (local variable)\", color='white', fontsize=round(20*image_size))\n",
" if num_plots>1:\n",
" fig.add_subplot(rows, columns, 2)\n",
" plt.imshow( visualize( _ref['weights'].to(dot_dtype)))\n",
" plt.axis('off')\n",
" plt.title(\"Encoding (saved file)\", color='white', fontsize=round(20*image_size))\n",
" #------#"
],
"metadata": {
"id": "lOQuTPfBMK82",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Run the interrogator**\n",
"\n",
" Since the list of items is large (>1 million items) you will need to select a range within the sorted results to print."
],
"metadata": {
"id": "ROKsoZrt7zMe"
}
},
{
"cell_type": "code",
"source": [
"# @title β π΅οΈββοΈ Run the CLIP Interrogator\n",
"LIST_SIZE = 1000 # @param {type:'number' , placeholder:'set how large the list should be'}\n",
"_START_AT = '0' # @param [\"0\", \"10000\", \"50000\"] {allow-input: true}\n",
"START_AT = 0\n",
"#-----#\n",
"if _START_AT.find('K')>-1:\n",
" START_AT = _START_AT.replace('K','')\n",
" if START_AT.isnumeric(): START_AT = int(START_AT)*1000\n",
"#------#\n",
"else:\n",
" if _START_AT.isnumeric(): START_AT = int(_START_AT)\n",
"#----#\n",
"\n",
"output_folder = home_directory + 'results/'\n",
"output_folder_sims = home_directory + 'results/sims/'\n",
"my_mkdirs(output_folder)\n",
"my_mkdirs(output_folder_sims)\n",
"\n",
"# @markdown -----\n",
"# @markdown Select vocab\n",
"general = True # @param {type:\"boolean\"}\n",
"civit9 = True # @param {type:\"boolean\"}\n",
"fanfic1 = False # @param {type:\"boolean\"}\n",
"fanfic2 = False # @param {type:\"boolean\"}\n",
"# @markdown -----\n",
"# @title β New interrogator code using quantized text corpus\n",
"%cd /content/\n",
"_ref = load_file('reference.safetensors' )\n",
"ref = _ref['weights'].to(dot_dtype)\n",
"# @markdown π Enhance/Penalize Similarity and skip items containing word(s)\n",
"POS1 = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"POS2 = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"NEG = ''# @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"SKIP = '' # @param {type:'string' ,placeholder:'item1 , item2 , ...'}\n",
"min_wordcount = 0 # @param {type:\"slider\", min:0, max:20, step:1}\n",
"def isBlacklisted(_txt):\n",
" blacklist = SKIP.lower().replace('</w>' , ' ').replace('{' , '').replace('}' , '').replace('|' , ',').strip()\n",
" if blacklist == '': return False\n",
" txt = _txt.lower().strip()\n",
" if len(txt)<min_wordcount: return True\n",
" if txt.isnumeric(): return True\n",
" #-----#\n",
" for item in list(blacklist.split(',')):\n",
" if item.strip() == '' : continue\n",
" if txt.find(item.strip())> -1 : return True\n",
" #------#\n",
" found = False\n",
" alphabet = 'abcdefghijklmnopqrstuvxyz'\n",
" for letter in alphabet:\n",
" found = txt.find(letter)>-1\n",
" if found:break\n",
" #------#\n",
" return not found\n",
"# @markdown -----\n",
"# @markdown logarithmic prompt strength x for value 10^(x-1)\n",
"_POS1 = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"_POS2 = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"_NEG = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
"# @markdown -----\n",
"# @markdown Save similarity as a list for later review (this will slow down the code)\n",
"save_similiarity = True # @param {type:\"boolean\"}\n",
"# @markdown -----\n",
"include_similiarity = False # @param {type:\"boolean\"}\n",
"print_as_list = False # @param {type:\"boolean\"}\n",
"N = 7 # @param {type:\"slider\", min:0, max:10, step:1}\n",
"#-----#\n",
"for _item in POS1.split(','):\n",
" item = _item.strip()\n",
" if item == '':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" ref = ref + math.pow(10,_POS1-1) * model.get_text_features(**inputs)[0]\n",
"#-------#\n",
"for _item in POS2.split(','):\n",
" item = _item.strip()\n",
" if item == '':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" ref = ref + math.pow(10,_POS2-1) * model.get_text_features(**inputs)[0]\n",
"#-------#\n",
"for _item in NEG.split(','):\n",
" item = _item.strip()\n",
" if item == '':continue\n",
" inputs = tokenizer(text = item.strip(), truncation = True , padding=True, return_tensors=\"pt\")\n",
" ref = ref + math.pow(10,_NEG-1) * model.get_text_features(**inputs)[0]\n",
"#------#\n",
"ref = (ref/ref.norm(p=2, dim=-1, keepdim=True)).to(dtype = dot_dtype)\n",
"vocab_to_load = ''\n",
"if (general): vocab_to_load = vocab_to_load + 'general , '\n",
"if (civit9): vocab_to_load = vocab_to_load + 'civit9 , '\n",
"if (fanfic1): vocab_to_load = vocab_to_load + 'fanfic1 , '\n",
"if (fanfic2): vocab_to_load = vocab_to_load + 'fanfic2 , '\n",
"vocab_to_load = (vocab_to_load +'}').replace(' , }' , '')\n",
"multi = vocab_to_load.find(',')>-1\n",
"#-----#\n",
"prompts_folder = f'{home_directory}fusion-t2i-generator-data/vocab-v2/text'\n",
"encodings_folder = f'{home_directory}fusion-t2i-generator-data/vocab-v2/text_encodings'\n",
"#----#\n",
"scale = 0.0043\n",
"size = 0\n",
"#------#\n",
"total_items = 0\n",
"for filename in os.listdir(prompts_folder):\n",
" if (not general and filename.find('general')>-1):continue\n",
" if (not civit9 and filename.find('civit9')>-1):continue\n",
" if (not fanfic1 and filename.find('fanfic1')>-1):continue\n",
" if (not fanfic2 and filename.find('fanfic2')>-1):continue\n",
" size = size + LIST_SIZE\n",
"#-------#\n",
"similiar_sims = torch.zeros(size)\n",
"similiar_prompts = {}\n",
"_index = 0\n",
"#-------#\n",
"similiar_encodings = {}\n",
"for filename in os.listdir(prompts_folder):\n",
" if (not general and filename.find('general')>-1):continue\n",
" if (not civit9 and filename.find('civit9')>-1):continue\n",
" if (not fanfic1 and filename.find('fanfic1')>-1):continue\n",
" if (not fanfic2 and filename.find('fanfic2')>-1):continue\n",
" #------#\n",
" root_filename = filename.replace('.json', '')\n",
" %cd {prompts_folder}\n",
" prompts = {}\n",
" with open(f'{root_filename}.json', 'r') as f:\n",
" data = json.load(f).items()\n",
" for key,value in data:\n",
" prompts[key] = value\n",
" num_items = int(prompts['num_items'])\n",
" total_items = total_items + num_items\n",
" #------#\n",
" try:vocab_loaded\n",
" except:\n",
" vocab_loaded = 'first'\n",
" #-----#\n",
" if vocab_loaded == 'first' or (vocab_loaded != vocab_to_load and not multi):\n",
" %cd {encodings_folder}\n",
" _text_encodings = load_file(f'{root_filename}.safetensors')['weights'].to(torch.uint8)\n",
" text_encodings = torch.zeros(num_items , dim)\n",
" tmp = torch.ones(dim).to(dot_dtype)\n",
" for index in range(num_items):\n",
" text_encodings[index] = torch.sub(_text_encodings[index][1:dim+1].to(dot_dtype) , tmp , alpha= _text_encodings[index][0].to(dot_dtype))\n",
" vocab_loaded = vocab_to_load\n",
" #------#\n",
" sims = torch.matmul(text_encodings*scale, ref.t())\n",
" sorted , indices = torch.sort(sims , dim=0 , descending = True)\n",
" tmp = {}\n",
" tmp['weights'] = sorted\n",
" %cd {output_folder_sims}\n",
" save_file(tmp, root_filename + '_sims.safetensors')\n",
" tmp={}\n",
" #-----#\n",
" for index in range(LIST_SIZE + START_AT):\n",
" if index<START_AT: continue\n",
" key = indices[index].item()\n",
" try:prompt = prompts[f'{key}']\n",
" except:continue\n",
" if(isBlacklisted(prompt)):continue\n",
" #-------#\n",
" similiar_sims[_index] = torch.tensor(round(sims[key].item(), 5))\n",
" similiar_prompts[f'{_index}'] = prompt\n",
" _index = _index + 1\n",
" #-------#\n",
" continue\n",
"#---------#\n",
"total_items = total_items + num_items+1\n",
"#-------#\n",
"print(f'\\nProcessed entire list of {total_items} items to find closest match.\\nSaved closest matching indices {START_AT} to {START_AT + LIST_SIZE} as the dict \"similiar_prompts\" with {LIST_SIZE} items.\\n')\n",
"\n",
"# Print results\n",
"sorted , indices = torch.sort(similiar_sims , dim=0 , descending = True)\n",
"if(print_as_list):\n",
" for index in range(LIST_SIZE):\n",
" key = indices[index].item()\n",
" sim = similiar_sims[key].item()\n",
" prompt = similiar_prompts[f'{key}']\n",
" if include_similiarity :print(f'{prompt} - {round(sim*100,1)} %')\n",
" else: print(f'{prompt}')\n",
"#-------#\n",
"else:\n",
" prompt = ''\n",
" for iter in range(N):\n",
" prompt = prompt + '{'\n",
" for index in range(LIST_SIZE):\n",
" key = indices[index].item()\n",
" sim = similiar_sims[key].item()\n",
" prompt = prompt + fix_bad_symbols(similiar_prompts[f'{key}']) + '|'\n",
" #-----#\n",
" prompt = (prompt + '}').replace('|}', '} ')\n",
" #------#\n",
" print(f'Similiar prompts: \\n\\n\\n{prompt} \\n\\n\\n//----//')\n",
"#-----#\n",
"\n",
"#Clear memory\n",
"_text_encodings = {}\n",
"prompts = {}\n",
"#-----#\n",
"\n",
"image\n"
],
"metadata": {
"id": "kOYZ8Ajn-DD8"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Evaluate Similarities**\n",
"\n",
"Run this cell to see how far down the list you can go before similarity to the reference is lost."
],
"metadata": {
"id": "yl1DYzUn8YCC"
}
},
{
"cell_type": "code",
"source": [
"# @title β π Test how unique the encoding is\n",
"%cd {output_folder_sims}\n",
"index = 0\n",
"for filename in os.listdir(output_folder_sims):\n",
" _sims = load_file(filename)\n",
" _sims = _sims['weights']\n",
" for _sim in _sims.tolist():\n",
" index = index + 1\n",
" #-------#\n",
"total_items = index\n",
"sims = torch.zeros(total_items)\n",
"index = 0\n",
"for filename in os.listdir(output_folder_sims):\n",
" _sims = load_file(filename)\n",
" _sims = _sims['weights']\n",
" for sim in _sims.tolist():\n",
" sims[index] = sim\n",
" index = index + 1\n",
" #-------#\n",
"#---------------#\n",
"_sorted , indices = torch.sort(sims , dim=0 , descending = True)\n",
"SCALE = 0.001\n",
"sorted = torch.round(_sorted/SCALE)\n",
"ZERO_POINT = sorted[total_items-1].item()\n",
"sorted = (sorted - torch.ones(total_items)*ZERO_POINT)\n",
"densities = torch.bincount(sorted.to(dtype = torch.int64))\n",
"yy = densities.tolist()\n",
"top = (sorted[0] + ZERO_POINT).to(dtype = torch.int64).item()\n",
"num_coords = round(top - ZERO_POINT)\n",
"xx = [round((ZERO_POINT + x)*100*SCALE,2) for x in range(num_coords+1)]\n",
"index = 0\n",
"for item in xx:\n",
" if item>0:break\n",
" index = index + 1\n",
"#----#\n",
"positive_bound = index\n",
"ss =list(xx)\n",
"tmp = 0\n",
"chunk = 1\n",
"CHUNK_SIZE = 1000\n",
"index = 0\n",
"for num in reversed(yy):\n",
" tmp = tmp + num\n",
" if(tmp>CHUNK_SIZE):\n",
" _tmp = math.floor(tmp/CHUNK_SIZE)\n",
" chunk = chunk + _tmp\n",
" tmp = tmp - CHUNK_SIZE * _tmp\n",
" ss[num_coords - index] = chunk\n",
" index = index + 1\n",
"#------#\n",
"fig, ax = plt.subplots()\n",
"fig.canvas.draw()\n",
"plt.plot(ss[positive_bound:], xx[positive_bound:])\n",
"plt.xlabel ('Search depth')\n",
"plt.ylabel ('Similarity')\n",
"plt.title ('Similarity to index')\n",
"plt.grid()\n",
"indices_depth = [item.get_text() for item in ax.get_xticklabels()]\n",
"sim_pcnts = [item.get_text() for item in ax.get_yticklabels()]\n",
"\n",
"index = 0\n",
"for index_depth in indices_depth:\n",
" indices_depth[index] = index_depth + 'K'\n",
" index = index + 1\n",
"#-------#\n",
"\n",
"index = 0\n",
"for sim_pcnt in sim_pcnts:\n",
" sim_pcnts[index] = sim_pcnt + '%'\n",
" index = index + 1\n",
"#-------#\n",
"ax.set_xticklabels(indices_depth)\n",
"ax.set_yticklabels(sim_pcnts)\n",
"plt.show()"
],
"metadata": {
"id": "ln6DsZPG99ez"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# @title β Save the results\n",
"\n",
"def mkdir(folder):\n",
" if os.path.exists(folder)==False:\n",
" os.makedirs(folder)\n",
"#-----#\n",
"output_folder = home_directory + 'results'\n",
"mkdir(output_folder)\n",
"#-----#\n",
"try: similiar_prompts\n",
"except:similiar_prompts = {}\n",
"%cd {output_folder}\n",
"print(f'Saving similiar_prompts.json to {output_folder}...')\n",
"with open('similiar_prompts.json', 'w') as f:\n",
" json.dump(similiar_prompts, f)\n",
"#-----#\n",
"try: similiar_sims\n",
"except: similiar_sims = torch.zeros(dim).to(dot_dtype)\n",
"#-------#\n",
"_similiar_sims = {}\n",
"_similiar_sims['weights'] = similiar_sims.to(dot_dtype)\n",
"%cd {output_folder}\n",
"print(f'Saving similiar_sims.safetensors to {output_folder}...')\n",
"save_file(_similiar_sims, 'similiar_sims.safetensors')\n"
],
"metadata": {
"id": "m-N553nXz9Jd",
"cellView": "form"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"\n",
"# @title β Print results\n",
"sorted , indices = torch.sort(similiar_sims , dim=0 , descending = True)\n",
"include_similiarity = False # @param {type:\"boolean\"}\n",
"print_as_list = False # @param {type:\"boolean\"}\n",
"N = 7 # @param {type:\"slider\", min:0, max:10, step:1}\n",
"FILENAME = '' # @param {type:'string' ,placeholder:'write .json file to load (optional)'}\n",
"_FILENAME = FILENAME.replace('.json' , '')\n",
"if _FILENAME.strip() == '': _FILENAME = 'similiar_prompts'\n",
"#------#\n",
"%cd {output_folder}\n",
"with open(f'{_FILENAME}.json', 'r') as f:\n",
" data = json.load(f)\n",
" _df = pd.DataFrame({'count': data})['count']\n",
" similiar_prompts = {\n",
" key : value for key, value in _df.items()\n",
" }\n",
"#-------#\n",
"_similiar_sims = load_file('similiar_sims.safetensors')\n",
"similiar_sims = _similiar_sims['weights'].to(dot_dtype)\n",
"\n",
"# @title β Run the CLIP interrogator on the saved reference\n",
"\n",
"# @markdown Select which values within the saved list to print\n",
"LIST_SIZE = 1000 # @param {type:'number' , placeholder:'set how large the list should be'}\n",
"START_AT = 0 # @param {type:'number' , placeholder:'set how large the list should be'}\n",
"\n",
"if(print_as_list):\n",
" for index in range(LIST_SIZE + START_AT):\n",
" if index<START_AT:continue\n",
" key = indices[index].item()\n",
" sim = similiar_sims[key].item()\n",
" prompt = similiar_prompts[f'{key}']\n",
" if include_similiarity :print(f'{prompt} - {round(sim*100,1)} %')\n",
" else: print(f'{prompt}')\n",
"#-------#\n",
"else:\n",
" prompt = ''\n",
" for iter in range(N):\n",
" prompt = prompt + '{'\n",
" for index in range(LIST_SIZE + START_AT):\n",
" if index<START_AT:continue\n",
" key = indices[index].item()\n",
" sim = similiar_sims[key].item()\n",
" prompt = prompt + fix_bad_symbols(similiar_prompts[f'{key}']) + '|'\n",
" #-----#\n",
" prompt = (prompt + '}').replace('|}', '} ')\n",
" #------#\n",
" print(f'Similiar prompts: \\n\\n {prompt} \\n\\n')\n",
"image\n",
"#-----#\n"
],
"metadata": {
"id": "XOMkIKc9-wZz",
"cellView": "form"
},
"execution_count": null,
"outputs": []
}
]
} |