File size: 11,094 Bytes
f04b033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251c856
 
 
 
 
 
 
 
 
f04b033
 
 
 
251c856
 
 
 
 
f04b033
251c856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f04b033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251c856
 
 
 
f04b033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251c856
f04b033
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "This notebook processes a JSON file of N items into chunks of 1000 items. The items are stored as a JSON + Safetensor pair. The name of the safestensor file is written within the JSON file at index 1"
      ],
      "metadata": {
        "id": "T7pqzVAFcPoK"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cskYkw0zXHEm",
        "outputId": "40cd8c83-6619-4acf-f720-c4126b9d99e5",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n",
            "/content\n",
            "/content/text-to-image-prompts/suffix_pairs/raw\n",
            "0\n",
            "100\n",
            "200\n",
            "300\n",
            "400\n",
            "500\n",
            "600\n",
            "700\n",
            "800\n",
            "900\n",
            "/content/output/suffix_pairs/text\n",
            "Saving segment suffix_pairs-1.json to /content/output/suffix_pairs/text/...\n",
            "/content/output/suffix_pairs/text_encodings\n",
            "Saving segment suffix_pairs-1.safetensors to /content/output/suffix_pairs/text_encodings/...\n",
            "0\n",
            "100\n",
            "200\n",
            "300\n",
            "400\n"
          ]
        }
      ],
      "source": [
        "# @title Make your own text_encodings .safetensor file for later use (using GPU is recommended to speed things up)\n",
        "\n",
        "import json\n",
        "import pandas as pd\n",
        "import os\n",
        "import shelve\n",
        "import torch\n",
        "from safetensors.torch import save_file\n",
        "import json\n",
        "\n",
        "# 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",
        "# User input\n",
        "target = home_directory + 'text-to-image-prompts/suffix_pairs/'\n",
        "output_folder = home_directory + 'output/suffix_pairs/'\n",
        "root_filename = 'suffix_pairs'\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_text_encodings = output_folder + 'text_encodings/'\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_text_encodings)\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",
        "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\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\").to(device)\n",
        "#---------#\n",
        "for  file_index in range(NUM_FILES + 1):\n",
        "    if (file_index < 1): continue\n",
        "    filename = f'{root_filename}-{file_index}'\n",
        "    if (NUM_FILES == 1) : filename = f'{root_filename}'\n",
        "\n",
        "    # Read {filename}.json\n",
        "    %cd {target_raw}\n",
        "    with open(filename + '.json', 'r') as f:\n",
        "        data = json.load(f)\n",
        "    _df = pd.DataFrame({'count': data})['count']\n",
        "    prompts = {\n",
        "        key : value.replace(\"</w>\",\" \") for key, value in _df.items()\n",
        "    }\n",
        "    index = 0\n",
        "    for key in prompts:\n",
        "        index = index + 1\n",
        "    #----------#\n",
        "    NUM_ITEMS = index\n",
        "    #------#\n",
        "\n",
        "  # Calculate text_encoding for .json file contents and results as .db file\n",
        "    names_dict = {}\n",
        "    text_encoding_dict = {}\n",
        "    segments = {}\n",
        "    index = 0;\n",
        "    subby = 1;\n",
        "    NUM_HEADERS = 2\n",
        "    CHUNKS_SIZE = 1000\n",
        "    _filename = ''\n",
        "    for _index in range(NUM_ITEMS):\n",
        "        if (index % 100 == 0) : print(index)\n",
        "        if (index == 0 and _index>0) : index = index + 2 #make space for headers\n",
        "        if (_index % (CHUNKS_SIZE-NUM_HEADERS) == 0 and _index > 0) :\n",
        "\n",
        "            # Write headers in the .json\n",
        "            names_dict[f'{0}'] = f'{_index}'\n",
        "            names_dict[f'{1}'] = f'{filename}-{subby}'\n",
        "\n",
        "            # Encode the headers into text_encoding\n",
        "            inputs = tokenizer(text = '' + names_dict[f'{0}'], padding=True, return_tensors=\"pt\").to(device)\n",
        "            text_features = model.get_text_features(**inputs).to(device)\n",
        "            text_features =  text_features/text_features.norm(p=2, dim=-1, keepdim=True)\n",
        "            text_encoding_dict[f'{0}'] = text_features.to(torch.device('cpu'))\n",
        "            inputs = tokenizer(text = '' + names_dict[f'{1}'], padding=True, return_tensors=\"pt\").to(device)\n",
        "            text_features = model.get_text_features(**inputs).to(device)\n",
        "            text_features =  text_features/text_features.norm(p=2, dim=-1, keepdim=True)\n",
        "            text_encoding_dict[f'{1}'] = text_features.to(torch.device('cpu'))\n",
        "            #-------#\n",
        "\n",
        "            # Write .json\n",
        "            _filename = f'{filename}-{subby}.json'\n",
        "            %cd {output_folder_text}\n",
        "            print(f'Saving segment {_filename} to {output_folder_text}...')\n",
        "            with open(_filename, 'w') as f:\n",
        "                json.dump(names_dict, f)\n",
        "            #-------#\n",
        "\n",
        "            # Write .safetensors\n",
        "            _filename = f'{filename}-{subby}.safetensors'\n",
        "            %cd {output_folder_text_encodings}\n",
        "            print(f'Saving segment {_filename} to {output_folder_text_encodings}...')\n",
        "            save_file(text_encoding_dict, _filename)\n",
        "            #--------#\n",
        "\n",
        "            #Iterate\n",
        "            subby = subby + 1\n",
        "            segments[f'{subby}'] = _filename\n",
        "            text_encoding_dict = {}\n",
        "            names_dict = {}\n",
        "            index = 0\n",
        "            #------#\n",
        "            #------#\n",
        "        else: index = index + 1\n",
        "        #--------#\n",
        "        inputs = tokenizer(text = '' + prompts[f'{_index}'], padding=True, return_tensors=\"pt\").to(device)\n",
        "        text_features = model.get_text_features(**inputs).to(device)\n",
        "        text_features =  text_features/text_features.norm(p=2, dim=-1, keepdim=True)\n",
        "        text_encoding_dict[f'{index}'] = text_features.to(torch.device('cpu'))\n",
        "        names_dict[f'{index}'] = prompts[f'{_index}']\n",
        "        continue\n",
        "    #-----#\n",
        "    #-----#\n",
        "    # Write headers in the .json\n",
        "    names_dict[f'{0}'] = f'{_index}'\n",
        "    names_dict[f'{1}'] = f'{filename}-{subby}'\n",
        "\n",
        "    # Encode the headers into text_encoding\n",
        "    inputs = tokenizer(text = '' + names_dict[f'{0}'], padding=True, return_tensors=\"pt\").to(device)\n",
        "    text_features = model.get_text_features(**inputs).to(device)\n",
        "    text_features =  text_features/text_features.norm(p=2, dim=-1, keepdim=True)\n",
        "    text_encoding_dict[f'{0}'] = text_features.to(torch.device('cpu'))\n",
        "    inputs = tokenizer(text = '' + names_dict[f'{1}'], padding=True, return_tensors=\"pt\").to(device)\n",
        "    text_features = model.get_text_features(**inputs).to(device)\n",
        "    text_features =  text_features/text_features.norm(p=2, dim=-1, keepdim=True)\n",
        "    text_encoding_dict[f'{1}'] = text_features.to(torch.device('cpu'))\n",
        "    #-------#\n",
        "\n",
        "    # Write .json\n",
        "    _filename = f'{filename}-{subby}.json'\n",
        "    %cd {output_folder_text}\n",
        "    print(f'Saving segment {_filename} to {output_folder_text}...')\n",
        "    with open(_filename, 'w') as f:\n",
        "        json.dump(names_dict, f)\n",
        "    #-------#\n",
        "\n",
        "    # Write .safetensors\n",
        "    _filename = f'{filename}-{subby}.safetensors'\n",
        "    %cd {output_folder_text_encodings}\n",
        "    print(f'Saving segment {_filename} to {output_folder_text_encodings}...')\n",
        "    save_file(text_encoding_dict, _filename)\n",
        "    #--------#\n",
        "\n",
        "    #Iterate\n",
        "    subby = subby + 1\n",
        "    segments[f'{subby}'] = _filename\n",
        "    text_encoding_dict = {}\n",
        "    names_dict = {}\n",
        "    index = 0\n",
        "    #------#\n",
        "  #----#"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Download the text_encodings as .zip\n",
        "import os\n",
        "%cd {home_directory}\n",
        "#os.remove(f'{home_directory}results.zip')\n",
        "zip_dest = f'{home_directory}results.zip'\n",
        "!zip -r {zip_dest} {output_folder}"
      ],
      "metadata": {
        "id": "cR-ed0CGhekk"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}