File size: 30,459 Bytes
be82bb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
984d3e7
 
 
 
 
 
 
 
 
 
 
be82bb1
 
 
16237fc
 
542f65d
 
 
 
 
be82bb1
 
 
a6ab21f
be82bb1
 
 
 
542f65d
 
 
be82bb1
 
 
 
 
 
542f65d
 
 
 
 
 
 
 
16237fc
 
 
 
 
 
 
 
 
 
be82bb1
542f65d
 
 
 
 
 
 
 
 
 
 
 
 
 
a6ab21f
be82bb1
16237fc
 
 
be82bb1
 
d1ca5a4
be82bb1
542f65d
 
be82bb1
16237fc
 
 
 
 
 
 
 
 
be82bb1
 
 
16237fc
 
984d3e7
542f65d
 
 
 
 
16237fc
 
 
542f65d
d1ca5a4
16237fc
542f65d
 
16237fc
 
d1ca5a4
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ca5a4
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ca5a4
16237fc
 
 
d1ca5a4
 
 
16237fc
c4972f8
a05998f
c4972f8
 
d1ca5a4
 
 
 
 
 
 
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ca5a4
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ca5a4
16237fc
 
 
 
 
d1ca5a4
16237fc
 
 
 
 
 
 
 
 
d1ca5a4
be82bb1
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ca5a4
16237fc
be82bb1
 
16237fc
542f65d
 
 
 
 
 
 
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542f65d
 
16237fc
984d3e7
e46266a
 
984d3e7
0c8190e
16237fc
0c8190e
16237fc
0c8190e
 
16237fc
 
0c8190e
984d3e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6ab21f
 
984d3e7
 
 
 
 
 
 
 
 
 
 
 
a6ab21f
 
 
 
 
 
 
 
 
 
 
984d3e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6ab21f
 
 
984d3e7
 
a6ab21f
 
 
 
 
 
 
 
 
 
 
 
 
 
984d3e7
 
 
 
 
 
 
 
 
 
 
 
 
a6ab21f
 
 
 
984d3e7
a6ab21f
 
 
 
 
 
984d3e7
a6ab21f
 
984d3e7
a6ab21f
 
984d3e7
a6ab21f
 
984d3e7
a6ab21f
 
984d3e7
a6ab21f
 
 
 
 
 
 
 
 
984d3e7
 
 
 
 
 
 
 
 
a6ab21f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
984d3e7
 
 
a6ab21f
984d3e7
 
a6ab21f
984d3e7
 
a6ab21f
 
984d3e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542f65d
984d3e7
 
 
d1ca5a4
 
542f65d
 
 
 
 
 
 
16237fc
542f65d
16237fc
 
 
542f65d
16237fc
 
d1ca5a4
16237fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ca5a4
16237fc
 
 
 
 
 
 
 
d1ca5a4
 
 
16237fc
d1ca5a4
 
 
 
 
 
 
16237fc
 
 
 
 
542f65d
 
16237fc
e46266a
 
 
be82bb1
 
 
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
{
  "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",
      "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",
        "  #----#\n",
        "  %cd {home_directory}\n",
        "  !git clone https://huggingface.co/datasets/codeShare/fusion-t2i-generator-data\n",
        "  loaded = True\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",
        "%cd {home_directory + 'fusion-t2i-generator-data/'}\n",
        "!unzip reference.zip\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",
        "reference = torch.zeros(dim).to(dtype = dot_dtype)"
      ],
      "metadata": {
        "id": "TC5lMJrS1HCC"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Feel free to skip these cells if you do not plan on using them\n"
      ],
      "metadata": {
        "id": "Xf9zoq-Za3wi"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @markdown 🖼️+📝 Choose a pre-encoded reference (optional)\n",
        "index = 657 # @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",
        "try: reference\n",
        "except: reference = torch.zeros(dim).to(dtype = dot_dtype)\n",
        "if reference == '': reference = torch.zeros(dim).to(dtype = dot_dtype)\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",
        "%cd {home_directory + 'fusion-t2i-generator-data/' + 'reference'}\n",
        "references = torch.load('reference_text_and_image_encodings.pt'  , weights_only=False)\n",
        "reference = torch.add(reference, math.pow(10 ,log_strength-1) * C * references[index][0].dequantize().to(dtype = torch.float32))\n",
        "reference = torch.add(reference, math.pow(10 ,log_strength-1) * (1-C) * references[index][1].dequantize().to(dtype = torch.float32))\n",
        "references = '' # Clear up memory\n",
        "ref = reference.clone().detach()\n",
        "#------#\n",
        "print(f'Prompt for this image : \\n\\n \"{prompt} \" \\n\\n')\n",
        "image"
      ],
      "metadata": {
        "id": "BwrEs5zVB0Sb"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @markdown 🖼️ Upload your own image for use as reference via URL (optional)\n",
        "URL = '' # @param {type:'string' ,placeholder:'paste an url here'}\n",
        "image = Image.open(requests.get(URL, stream=True).raw)\n",
        "#---------#\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",
        "log_strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
        "ref = ref + math.pow(10,log_strength-1)*image_features\n",
        "image"
      ],
      "metadata": {
        "id": "IqUsiQw2HU2C"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @markdown 🖼️ Upload your own image in the /content/ folder for use as reference (optional)\n",
        "FILENAME = '' # @param {type:'string' ,placeholder:'IMG_123.png'}\n",
        "import cv2\n",
        "image = cv2.imread(FILENAME)\n",
        "image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n",
        "\n",
        "#---------#\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",
        "log_strength = 1 # @param {type:\"slider\", min:-5, max:5, step:0.01}\n",
        "ref = ref + math.pow(10,log_strength-1)*image_features\n",
        "image"
      ],
      "metadata": {
        "id": "I_-GOwFPKkha"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Save the reference prior to running the Interrogator"
      ],
      "metadata": {
        "id": "zeu6JcM-mk9z"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title ⚄ Save the reference\n",
        "try: ref\n",
        "except: ref = torch.zeros(dim)\n",
        "_ref = {}\n",
        "_ref['weights'] = ref.to(dot_dtype)\n",
        "%cd /content/\n",
        "save_file(_ref , 'reference.safetensors' )"
      ],
      "metadata": {
        "id": "lOQuTPfBMK82"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title ⚄ Run the CLIP interrogator on the saved reference\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",
        "# @markdown -----\n",
        "# @markdown Select vocab\n",
        "general = False # @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",
        "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",
        "#-----#\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",
        "  #------#\n",
        "  try:vocab_loaded\n",
        "  except:\n",
        "    vocab_loaded = 'first'\n",
        "  #-----#\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",
        "\n",
        "\n",
        "  sims = torch.matmul(text_encodings*scale, ref.t())\n",
        "  sorted , indices = torch.sort(sims , dim=0 , descending = True)\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",
        "print(f'\\n\\nProcessed entire list of {total_items} items to find closest match. Saved closest matching indices {START_AT} to {START_AT + LIST_SIZE} as the dict \"similiar_prompts\" with {LIST SIZE} items. \\n\\n')\n"
      ],
      "metadata": {
        "id": "kOYZ8Ajn-DD8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "\n",
        "# @title ⚄ Printing results from text corpus\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",
        "\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 {prompt} \\n\\n')\n",
        "  image\n",
        "#-----#\n"
      ],
      "metadata": {
        "id": "XOMkIKc9-wZz"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "OTHER STUFF BELOW - Code for the modules below are work-in-progress."
      ],
      "metadata": {
        "id": "FRIqYJDEebpf"
      }
    },
    {
      "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",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title \t⚄ Create a savefile-set from the entire range of pre-encoded items\n",
        "\n",
        "# @markdown 📥 Load the data (only required one time)\n",
        "load_the_data = True # @param {type:\"boolean\"}\n",
        "\n",
        "import math\n",
        "from safetensors.torch import load_file\n",
        "import json , os , torch\n",
        "import pandas as pd\n",
        "from PIL import Image\n",
        "import requests\n",
        "\n",
        "def my_mkdirs(folder):\n",
        "  if os.path.exists(folder)==False:\n",
        "    os.makedirs(folder)\n",
        "\n",
        "# @markdown ⚖️ Set the value for C in the reference  <br> <br> sim = C* text_enc + image_enc*(1-C) <br><br>\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",
        "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",
        "\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'\n",
        "\n",
        "%cd /content/\n",
        "output_folder = '/content/output/savefiles/'\n",
        "my_mkdirs(output_folder)\n",
        "my_mkdirs('/content/output2/savefiles/')\n",
        "my_mkdirs('/content/output3/savefiles/')\n",
        "my_mkdirs('/content/output4/savefiles/')\n",
        "my_mkdirs('/content/output5/savefiles/')\n",
        "my_mkdirs('/content/output6/savefiles/')\n",
        "my_mkdirs('/content/output7/savefiles/')\n",
        "my_mkdirs('/content/output8/savefiles/')\n",
        "my_mkdirs('/content/output9/savefiles/')\n",
        "my_mkdirs('/content/output10/savefiles/')\n",
        "my_mkdirs('/content/output11/savefiles/')\n",
        "my_mkdirs('/content/output12/savefiles/')\n",
        "my_mkdirs('/content/output13/savefiles/')\n",
        "\n",
        "\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",
        "  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",
        "  text_features_A = target_text_encodings[f'{index}']\n",
        "  image_features_A =  target_image_encodings[f'{index}']\n",
        "  # text-similarity\n",
        "  sims =  C * torch.matmul(text_tensor, text_features_A.t())\n",
        "\n",
        "  neg_sims = 0*sims\n",
        "  if(NEG != ''):\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",
        "    # 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",
        "  # @markdown Repeat output N times\n",
        "  RANGE = 1000\n",
        "  NUM_CHUNKS = 10+\n",
        "  separator = '|'\n",
        "  _savefiles = {}\n",
        "  #-----#\n",
        "  for chunk in range(NUM_CHUNKS):\n",
        "    if chunk=<10:continue\n",
        "    start_at_index = chunk * RANGE\n",
        "    _prompts = ''\n",
        "    for _index in range(start_at_index + RANGE):\n",
        "      if _index < start_at_index : continue\n",
        "      index = indices[_index].item()\n",
        "      prompt = prompts[f'{index}']\n",
        "      _prompts = _prompts.replace(prompt + separator,'')\n",
        "      _prompts = _prompts  + prompt + separator\n",
        "    #------#\n",
        "    _prompts = fix_bad_symbols(_prompts)\n",
        "    _prompts = ('{' + _prompts + '}').replace(separator + '}', '}')\n",
        "    _savefiles[f'{chunk}'] = _prompts\n",
        "  #---------#\n",
        "  save_filename = f'{root_savefile_name}_{start_at_index + RANGE}_{PROMPT_INDEX}.json'\n",
        "\n",
        "\n",
        "  if (chunk=<20 && chunk>10): %cd '/content/output2/savefiles/'\n",
        "  if (chunk<=30 && chunk>20): %cd '/content/output3/savefiles/'\n",
        "  if (chunk=<40 && chunk>30): %cd '/content/output4/savefiles/'\n",
        "  if (chunk<=50 && chunk>40): %cd '/content/output5/savefiles/'\n",
        "  if (chunk=<60 && chunk>50): %cd '/content/output6/savefiles/'\n",
        "  if (chunk<=70 && chunk>60): %cd '/content/output7/savefiles/'\n",
        "  if (chunk=<80 && chunk>70): %cd '/content/output8/savefiles/'\n",
        "  if (chunk<=90 && chunk>80): %cd '/content/output9/savefiles/'\n",
        "  if (chunk=<100 && chunk>90): %cd '/content/output10/savefiles/'\n",
        "  if (chunk<=110 && chunk>100): %cd '/content/output11/savefiles/'\n",
        "  if (chunk=<120 && chunk>110): %cd '/content/output12/savefiles/'\n",
        "  if (chunk<=130 && chunk>120): %cd '/content/output13/savefiles/'\n",
        "\n",
        "\n",
        "  #------#\n",
        "  print(f'Saving savefile {save_filename} to {output_folder}...')\n",
        "  with open(save_filename, 'w') as f:\n",
        "      json.dump(_savefiles, f)\n",
        "  #---------#\n",
        "  continue\n",
        "#-----------#"
      ],
      "metadata": {
        "id": "x1uAVXZEoL0T",
        "cellView": "form"
      },
      "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'/content/results.zip' #drive/MyDrive\n",
        "!zip -r {zip_dest} {root_output_folder}"
      ],
      "metadata": {
        "id": "zivBNrw9uSVD",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title \t⚄ Quick fix for normalizing encoded text corpus tensors\n",
        "\n",
        "import os\n",
        "my_mkdirs('/content/output')\n",
        "my_mkdirs('/content/output/text_encodings')\n",
        "\n",
        "for filename in os.listdir(f'{prompts_folder}'):\n",
        "  %cd {prompts_folder}\n",
        "  prompts = {}\n",
        "  with open(f'{filename}', 'r') as f:\n",
        "    data = json.load(f).items()\n",
        "    for key,value in data:\n",
        "      prompts[key] = value\n",
        "    #------#\n",
        "  num_items = int(prompts['num_items'])\n",
        "\n",
        "  %cd {encodings_folder}\n",
        "  enc_filename = filename.replace('json', 'safetensors')\n",
        "  _text_encodings = load_file(f'{enc_filename}')['weights'].to(torch.uint8)\n",
        "  text_encodings = torch.zeros(num_items , dim)\n",
        "  tmp = torch.ones(dim)\n",
        "  tmp2 = torch.tensor(1/0.0043)\n",
        "  zero_point = 0\n",
        "  for index in range(num_items):\n",
        "    text_encodings[index] = torch.tensor(0.0043) * torch.sub(_text_encodings[index][1:dim+1] , tmp , alpha= _text_encodings[index][0]).to(torch.float32)\n",
        "    text_encodings[index] = tmp2*text_encodings[index]/text_encodings[index].norm(p=2, dim=-1, keepdim = True)\n",
        "    test = torch.round( torch.add(text_encodings[index],tmp*zero_point))\n",
        "    less_than_zero = test<0\n",
        "    while(torch.any(less_than_zero).item()):\n",
        "      zero_point = zero_point + 1\n",
        "      test = torch.round( torch.add(text_encodings[index],tmp*zero_point))\n",
        "      less_than_zero = test<0\n",
        "    #------#\n",
        "    _text_encodings[index][0]  = zero_point\n",
        "    _text_encodings[index][1:dim+1] = test\n",
        "  #-------#\n",
        "  %cd /content/output/text_encodings\n",
        "\n",
        "  tmp = {}\n",
        "  tmp['weights'] =  _text_encodings.to(torch.uint8)\n",
        "  tmp['num_items'] = torch.tensor(num_items).to(torch.uint8)\n",
        "  tmp['scale'] = torch.tensor(0.0043)\n",
        "  save_file(tmp , f'{enc_filename}')\n",
        "#------#"
      ],
      "metadata": {
        "cellView": "form",
        "id": "9qgHW1Wr7kZn"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Check the average value for this set\n",
        "sims = torch.matmul(vocab_encodings.dequantize(),average.t())\n",
        "sorted , indices = torch.sort(sims,dim=0 , descending=True)\n",
        "for index in range(10):\n",
        "  print(prompts[f'{indices[index].item()}'])"
      ],
      "metadata": {
        "id": "XNHz0hfhHRUu"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}