File size: 25,846 Bytes
3d64a03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "# NOTE : although they have 1x768 dimension , these are not text_encodings , but token vectors\n",
        "import json\n",
        "import pandas as pd\n",
        "import os\n",
        "import shelve\n",
        "import torch\n",
        "from safetensors.torch import save_file , load_file\n",
        "import json\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",
        "def getPrompts(_path, separator):\n",
        "  path = _path + '/text'\n",
        "  path_vec = _path + '/token_vectors'\n",
        "  _file_name = 'vocab'\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",
        "    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",
        "    #-------#\n",
        "    %cd {path_vec}\n",
        "    _text_encodings = load_file(f'{_file_name}.safetensors')\n",
        "\n",
        "    for key in _prompts:\n",
        "      _index = int(key)\n",
        "      value = _prompts[key]\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",
        "#-------#"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "V-1DrszLqEVj",
        "outputId": "9b894182-a7e0-436e-9bf1-5a7d3d920ac7"
      },
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Fetch the json + .safetensor pair\n",
        "\n",
        "#------#\n",
        "vocab = {}\n",
        "tokens = {}\n",
        "nA = 0\n",
        "#--------#\n",
        "\n",
        "if True:\n",
        "  url = '/content/text-to-image-prompts/vocab'\n",
        "  vocab , tokens, nA = append_from_url(vocab , tokens, nA , url , '')\n",
        "#-------#\n",
        "NUM_TOKENS = nA # NUM_TOKENS = 49407\n",
        "#--------#\n",
        "\n",
        "print(NUM_TOKENS)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "EDCd1IGEqj3-",
        "outputId": "bbaab5ab-4bd3-4766-ad44-f139a0ec7a02"
      },
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "reading vocab.json....\n",
            "/content/text-to-image-prompts/vocab/text\n",
            "/content/text-to-image-prompts/vocab/token_vectors\n",
            "49407\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "vocab[f'{8922}']"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "o9AfUKkvwUdG",
        "outputId": "029e1148-056b-4040-da23-7ed6caaca878"
      },
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'benedict</w>'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Compare similiarity between tokens\n",
        "\n",
        "import torch\n",
        "from transformers import AutoTokenizer\n",
        "tokenizer = AutoTokenizer.from_pretrained(\"openai/clip-vit-large-patch14\", clean_up_tokenization_spaces = False)\n",
        "\n",
        "# @markdown Write name of token to match against\n",
        "token_name = \"banana\" # @param {type:'string',\"placeholder\":\"leave empty for random value token\"}\n",
        "\n",
        "prompt = token_name\n",
        "# @markdown (optional) Mix the token with something else\n",
        "mix_with = \"\" # @param {\"type\":\"string\",\"placeholder\":\"leave empty for random value token\"}\n",
        "mix_method = \"None\" # @param [\"None\" , \"Average\", \"Subtract\"] {allow-input: true}\n",
        "w = 0.5 # @param {type:\"slider\", min:0, max:1, step:0.01}\n",
        "# @markdown Limit char size of included token\n",
        "\n",
        "min_char_size = 0 # param {type:\"slider\", min:0, max: 50, step:1}\n",
        "char_range = 50 # param {type:\"slider\", min:0, max: 50, step:1}\n",
        "\n",
        "tokenizer_output = tokenizer(text = prompt)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "id_A = input_ids[1]\n",
        "A = torch.tensor(tokens[f'{id_A}'])\n",
        "A = A/A.norm(p=2, dim=-1, keepdim=True)\n",
        "#-----#\n",
        "tokenizer_output = tokenizer(text = mix_with)\n",
        "input_ids = tokenizer_output['input_ids']\n",
        "id_C = input_ids[1]\n",
        "C = torch.tensor(tokens[f'{id_C}'])\n",
        "C = C/C.norm(p=2, dim=-1, keepdim=True)\n",
        "#-----#\n",
        "sim_AC = torch.dot(A,C)\n",
        "#-----#\n",
        "print(input_ids)\n",
        "#-----#\n",
        "\n",
        "#if no imput exists we just randomize the entire thing\n",
        "if (prompt == \"\"):\n",
        "  id_A = -1\n",
        "  print(\"Tokenized prompt tensor A is a random valued tensor with no ID\")\n",
        "  R = torch.rand(A.shape)\n",
        "  R = R/R.norm(p=2, dim=-1, keepdim=True)\n",
        "  A = R\n",
        "  name_A = 'random_A'\n",
        "\n",
        "#if no imput exists we just randomize the entire thing\n",
        "if (mix_with == \"\"):\n",
        "  id_C = -1\n",
        "  print(\"Tokenized prompt  'mix_with' tensor C is a random valued tensor with no ID\")\n",
        "  R = torch.rand(A.shape)\n",
        "  R = R/R.norm(p=2, dim=-1, keepdim=True)\n",
        "  C = R\n",
        "  name_C = 'random_C'\n",
        "\n",
        "name_A = \"A of random type\"\n",
        "if (id_A>-1):\n",
        "  name_A = vocab[f'{id_A}']\n",
        "\n",
        "name_C = \"token C of random type\"\n",
        "if (id_C>-1):\n",
        "  name_C = vocab[f'{id_C}']\n",
        "\n",
        "print(f\"The similarity between A '{name_A}' and C '{name_C}' is {round(sim_AC.item()*100,2)} %\")\n",
        "\n",
        "if (mix_method ==  \"None\"):\n",
        "  print(\"No operation\")\n",
        "\n",
        "if (mix_method ==  \"Average\"):\n",
        "  A = w*A + (1-w)*C\n",
        "  _A = A.norm(p=2, dim=-1, keepdim=True)\n",
        "  print(f\"Tokenized prompt tensor A '{name_A}' token has been recalculated as A = w*A + (1-w)*C , where C is '{name_C}' token , for w = {w}  \")\n",
        "\n",
        "if (mix_method ==  \"Subtract\"):\n",
        "  tmp =  w*A - (1-w)*C\n",
        "  tmp = tmp/tmp.norm(p=2, dim=-1, keepdim=True)\n",
        "  A = tmp\n",
        "  #//---//\n",
        "  print(f\"Tokenized prompt tensor A '{name_A}' token has been recalculated as A = _A*norm(w*A  - (1-w)*C) , where C is '{name_C}' token , for w = {w} \")\n",
        "\n",
        "#OPTIONAL : Add/subtract + normalize above result with another token. Leave field empty to get a random value tensor\n",
        "\n",
        "dots = torch.zeros(NUM_TOKENS)\n",
        "for index in range(NUM_TOKENS):\n",
        "  id_B = index\n",
        "  B = torch.tensor(tokens[f'{id_B}'])\n",
        "  B = B/B.norm(p=2, dim=-1, keepdim=True)\n",
        "  sim_AB = torch.dot(A,B)\n",
        "  dots[index] = sim_AB\n",
        "\n",
        "\n",
        "sorted, indices = torch.sort(dots,dim=0 , descending=True)\n",
        "#----#\n",
        "if (mix_method ==  \"Average\"):\n",
        "  print(f'Calculated all cosine-similarities between the average of token {name_A} and {name_C} with Id_A = {id_A} and mixed Id_C = {id_C} as a 1x{sorted.shape[0]} tensor')\n",
        "if (mix_method ==  \"Subtract\"):\n",
        "  print(f'Calculated all cosine-similarities between the subtract of token {name_A} and {name_C} with Id_A = {id_A} and mixed Id_C = {id_C} as a 1x{sorted.shape[0]} tensor')\n",
        "if (mix_method ==  \"None\"):\n",
        "  print(f'Calculated all cosine-similarities between the token {name_A} with Id_A = {id_A} with the the rest of the {NUM_TOKENS} tokens as a 1x{sorted.shape[0]} tensor')\n",
        "\n",
        "#Produce a list id IDs that are most similiar to the prompt ID at positiion 1 based on above result\n",
        "\n",
        "# @markdown Set print options\n",
        "list_size = 100 # @param {type:'number'}\n",
        "print_ID = False # @param {type:\"boolean\"}\n",
        "print_Similarity = True # @param {type:\"boolean\"}\n",
        "print_Name = True # @param {type:\"boolean\"}\n",
        "print_Divider = True # @param {type:\"boolean\"}\n",
        "\n",
        "\n",
        "if (print_Divider):\n",
        "  print('//---//')\n",
        "\n",
        "print('')\n",
        "print('Here is the result : ')\n",
        "print('')\n",
        "\n",
        "for index in range(list_size):\n",
        "  id = indices[index].item()\n",
        "  if (print_Name):\n",
        "    print(vocab[f'{id}']) # vocab item\n",
        "  if (print_ID):\n",
        "    print(f'ID = {id}') # IDs\n",
        "  if (print_Similarity):\n",
        "    print(f'similiarity = {round(sorted[index].item()*100,2)} %')\n",
        "  if (print_Divider):\n",
        "    print('--------')\n",
        "\n",
        "#Print the sorted list from above result\n",
        "\n",
        "#The prompt will be enclosed with the <|start-of-text|> and <|end-of-text|> tokens, which is why output will be [49406, ... , 49407].\n",
        "\n",
        "#You can leave the 'prompt' field empty to get a random value tensor. Since the tensor is random value, it will not correspond to any tensor in the vocab.json list , and this it will have no ID.\n",
        "\n",
        "# Save results as .db file\n",
        "import shelve\n",
        "VOCAB_FILENAME = 'tokens_most_similiar_to_' + name_A.replace('</w>','').strip()\n",
        "d = shelve.open(VOCAB_FILENAME)\n",
        "#NUM TOKENS == 49407\n",
        "for index in range(NUM_TOKENS):\n",
        "  #print(d[f'{index}']) #<-----Use this to read values from the .db file\n",
        "  d[f'{index}']= vocab[f'{indices[index].item()}'] #<---- write values to .db file\n",
        "#----#\n",
        "d.close() #close the file\n",
        "# See this link for additional stuff to do with shelve: https://docs.python.org/3/library/shelve.html"
      ],
      "metadata": {
        "id": "ZwGqg9R5s1QS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Below is code used to create the .safetensor + json files for the notebook"
      ],
      "metadata": {
        "id": "dGb1KgP_p4_w"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 599
        },
        "id": "AyhYBlP2pYyI",
        "outputId": "0168beb3-428c-4886-f159-adc479b9da4b"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n",
            "/content\n",
            "Cloning into 'text-to-image-prompts'...\n",
            "remote: Enumerating objects: 1552, done.\u001b[K\n",
            "remote: Counting objects: 100% (1549/1549), done.\u001b[K\n",
            "remote: Compressing objects: 100% (1506/1506), done.\u001b[K\n",
            "remote: Total 1552 (delta 190), reused 0 (delta 0), pack-reused 3 (from 1)\u001b[K\n",
            "Receiving objects: 100% (1552/1552), 9.09 MiB | 6.30 MiB/s, done.\n",
            "Resolving deltas: 100% (190/190), done.\n",
            "Updating files: 100% (906/906), done.\n",
            "Filtering content: 100% (438/438), 1.49 GiB | 56.42 MiB/s, done.\n",
            "/content\n",
            "/content/text-to-image-prompts/vocab/raw\n",
            "/content/text-to-image-prompts/vocab/raw\n"
          ]
        },
        {
          "output_type": "error",
          "ename": "JSONDecodeError",
          "evalue": "Expecting ':' delimiter: line 28 column 7 (char 569)",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mJSONDecodeError\u001b[0m                           Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-1-542fe0f58fcc>\u001b[0m in \u001b[0;36m<cell line: 56>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     55\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'cd'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'{target_raw}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     56\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'{root_filename}.json'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 57\u001b[0;31m     \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mjson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mload\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     58\u001b[0m \u001b[0m_df\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpd\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mDataFrame\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m{\u001b[0m\u001b[0;34m'count'\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'count'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     59\u001b[0m \u001b[0;31m#reverse key and value in the dict\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/lib/python3.10/json/__init__.py\u001b[0m in \u001b[0;36mload\u001b[0;34m(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[1;32m    291\u001b[0m     \u001b[0mkwarg\u001b[0m\u001b[0;34m;\u001b[0m \u001b[0motherwise\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0mJSONDecoder\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mused\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    292\u001b[0m     \"\"\"\n\u001b[0;32m--> 293\u001b[0;31m     return loads(fp.read(),\n\u001b[0m\u001b[1;32m    294\u001b[0m         \u001b[0mcls\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcls\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mobject_hook\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mobject_hook\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    295\u001b[0m         \u001b[0mparse_float\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mparse_float\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mparse_int\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mparse_int\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/lib/python3.10/json/__init__.py\u001b[0m in \u001b[0;36mloads\u001b[0;34m(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[1;32m    344\u001b[0m             \u001b[0mparse_int\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0mparse_float\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m \u001b[0;32mand\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    345\u001b[0m             parse_constant is None and object_pairs_hook is None and not kw):\n\u001b[0;32m--> 346\u001b[0;31m         \u001b[0;32mreturn\u001b[0m \u001b[0m_default_decoder\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdecode\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    347\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mcls\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    348\u001b[0m         \u001b[0mcls\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mJSONDecoder\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/lib/python3.10/json/decoder.py\u001b[0m in \u001b[0;36mdecode\u001b[0;34m(self, s, _w)\u001b[0m\n\u001b[1;32m    335\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    336\u001b[0m         \"\"\"\n\u001b[0;32m--> 337\u001b[0;31m         \u001b[0mobj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mend\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mraw_decode\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0midx\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0m_w\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    338\u001b[0m         \u001b[0mend\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_w\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mend\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    339\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mend\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/lib/python3.10/json/decoder.py\u001b[0m in \u001b[0;36mraw_decode\u001b[0;34m(self, s, idx)\u001b[0m\n\u001b[1;32m    351\u001b[0m         \"\"\"\n\u001b[1;32m    352\u001b[0m         \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 353\u001b[0;31m             \u001b[0mobj\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mend\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscan_once\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0midx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    354\u001b[0m         \u001b[0;32mexcept\u001b[0m \u001b[0mStopIteration\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0merr\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    355\u001b[0m             \u001b[0;32mraise\u001b[0m \u001b[0mJSONDecodeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Expecting value\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0ms\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0merr\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mJSONDecodeError\u001b[0m: Expecting ':' delimiter: line 28 column 7 (char 569)"
          ]
        }
      ],
      "source": [
        "# @title Process the raw vocab into json + .safetensor pair\n",
        "\n",
        "# NOTE : although they have 1x768 dimension , these are not text_encodings , but token vectors\n",
        "import json\n",
        "import pandas as pd\n",
        "import os\n",
        "import shelve\n",
        "import torch\n",
        "from safetensors.torch import save_file , load_file\n",
        "import json\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",
        "# User input\n",
        "target = home_directory + 'text-to-image-prompts/vocab/'\n",
        "root_output_folder = home_directory + 'output/'\n",
        "output_folder = root_output_folder  + 'vocab/'\n",
        "root_filename = 'vocab'\n",
        "NUM_FILES = 1\n",
        "#--------#\n",
        "\n",
        "# Setup environment\n",
        "def my_mkdirs(folder):\n",
        "    if os.path.exists(folder)==False:\n",
        "        os.makedirs(folder)\n",
        "#--------#\n",
        "output_folder_text = output_folder + 'text/'\n",
        "output_folder_text = output_folder + 'text/'\n",
        "output_folder_token_vectors = output_folder + 'token_vectors/'\n",
        "target_raw = target + 'raw/'\n",
        "%cd {home_directory}\n",
        "my_mkdirs(output_folder)\n",
        "my_mkdirs(output_folder_text)\n",
        "my_mkdirs(output_folder_token_vectors)\n",
        "#-------#\n",
        "\n",
        "%cd {target_raw}\n",
        "model = torch.load(f'{root_filename}.pt' , weights_only=True)\n",
        "tokens = model.clone().detach()\n",
        "\n",
        "\n",
        "%cd {target_raw}\n",
        "with open(f'{root_filename}.json', 'r') as f:\n",
        "    data = json.load(f)\n",
        "_df = pd.DataFrame({'count': data})['count']\n",
        "#reverse key and value in the dict\n",
        "vocab = {\n",
        "    value : key for key, value in _df.items()\n",
        "}\n",
        "#------#\n",
        "\n",
        "\n",
        "tensors = {}\n",
        "for key in vocab:\n",
        "  name = vocab[key]\n",
        "  token = tokens[int(key)]\n",
        "  tensors[key] = token\n",
        "#-----#\n",
        "\n",
        "%cd {output_folder_token_vectors}\n",
        "save_file(tensors, \"vocab.safetensors\")\n",
        "\n",
        "%cd {output_folder_text}\n",
        "with open('vocab.json', 'w') as f:\n",
        "    json.dump(vocab, f)\n"
      ]
    },
    {
      "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 vocab 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} '/content/text-to-image-prompts/tokens'"
      ],
      "metadata": {
        "id": "9uIDf9IUpzh2"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}