{ "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", "source": [ "\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", "# 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/workspace\n", " loaded = True\n", "#--------#" ], "metadata": { "id": "xow5kaB2SgPs", "outputId": "e11edb8a-98a3-4de8-b5b7-139d5db959a5", "colab": { "base_uri": "https://localhost:8080/" } }, "execution_count": 1, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "/content\n", "/content\n", "Cloning into 'workspace'...\n", "remote: Enumerating objects: 19, done.\u001b[K\n", "remote: Counting objects: 100% (16/16), done.\u001b[K\n", "remote: Compressing objects: 100% (10/10), done.\u001b[K\n", "remote: Total 19 (delta 0), reused 0 (delta 0), pack-reused 3 (from 1)\u001b[K\n", "Unpacking objects: 100% (19/19), 4.84 KiB | 412.00 KiB/s, done.\n" ] } ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "cskYkw0zXHEm", "outputId": "b60e3914-84c4-4660-ba85-f8522ba18558", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "/content\n", "/content/workspace/civit9/raw\n", "/content/output/civit9/raw\n", "Saving segment civit9.json to /content/output/civit9/raw/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n", "900\n", "/content/output/civit9/text\n", "Saving segment civit9-1.json to /content/output/civit9/text/...\n", "/content/output/civit9/text_encodings\n", "Saving segment civit9-1.safetensors to /content/output/civit9/text_encodings/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n", "900\n", "/content/output/civit9/text\n", "Saving segment civit9-2.json to /content/output/civit9/text/...\n", "/content/output/civit9/text_encodings\n", "Saving segment civit9-2.safetensors to /content/output/civit9/text_encodings/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n", "900\n", "/content/output/civit9/text\n", "Saving segment civit9-3.json to /content/output/civit9/text/...\n", "/content/output/civit9/text_encodings\n", "Saving segment civit9-3.safetensors to /content/output/civit9/text_encodings/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n", "900\n", "/content/output/civit9/text\n", "Saving segment civit9-4.json to /content/output/civit9/text/...\n", "/content/output/civit9/text_encodings\n", "Saving segment civit9-4.safetensors to /content/output/civit9/text_encodings/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n", "900\n", "/content/output/civit9/text\n", "Saving segment civit9-5.json to /content/output/civit9/text/...\n", "/content/output/civit9/text_encodings\n", "Saving segment civit9-5.safetensors to /content/output/civit9/text_encodings/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n", "900\n", "/content/output/civit9/text\n", "Saving segment civit9-6.json to /content/output/civit9/text/...\n", "/content/output/civit9/text_encodings\n", "Saving segment civit9-6.safetensors to /content/output/civit9/text_encodings/...\n", "0\n", "100\n", "200\n", "300\n", "400\n", "500\n", "600\n", "700\n", "800\n" ] } ], "source": [ "\n", "\n", "# @title Make your own text_encodings .safetensor file for later use (using GPU is recommended to speed things up)\n", "# User input\n", "target = home_directory + 'workspace/civit9/'\n", "output_folder = home_directory + 'output/civit9/'\n", "root_filename = 'civit9'\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", "output_folder_raw = output_folder + 'raw/'\n", "target_raw = target + 'raw/'\n", "\n", "%cd {home_directory}\n", "my_mkdirs(output_folder)\n", "my_mkdirs(output_folder_text)\n", "my_mkdirs(output_folder_text_encodings)\n", "my_mkdirs(output_folder_raw)\n", "#-------#\n", "\n", "%cd {target_raw}\n", "with open(root_filename + '.json', 'r') as f:\n", " data = json.load(f)\n", "_df = pd.DataFrame({'count': data})['count']\n", "_prompts = {\n", " key : value for key, value in _df.items()\n", "}\n", "\n", "index = 0\n", "for key in _prompts:\n", " index = index + 1\n", "#-----#\n", "NUM_ITEMS = index-1\n", "\n", "prompts = {}\n", "import random\n", "for key in _prompts:\n", " prompts[key] = _prompts[key] + ' ' + _prompts[f'{random.randint(0,NUM_ITEMS)}']\n", "#------#\n", "\n", "%cd {output_folder_raw}\n", "print(f'Saving segment {root_filename}.json to {output_folder_raw}...')\n", "with open(f'{root_filename}.json', 'w') as f:\n", " json.dump(prompts, f)\n", "#-------#\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", "#---------#\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", " 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, truncation = 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, truncation = 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, truncation = 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, truncation = 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, truncation = 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", "# UP TO FILE INDEX 250 FOR fanfic tags out of a total 1622\n", "import os\n", "%cd {home_directory}\n", "output_folder = '/content/output'\n", "#os.remove(f'{home_directory}results.zip')\n", "zip_dest = f'{home_directory}results.zip'\n", "!zip -r {zip_dest} '/content/output'" ], "metadata": { "id": "cR-ed0CGhekk" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# @title Download the text_encodings to google drive as .zip\n", "from google.colab import drive\n", "\n", "output_folder = '/content/output'\n", "#-----#\n", "try: mounted\n", "except:\n", " mounted = True\n", " drive.mount('/content/drive')\n", "#------#\n" ], "metadata": { "id": "zTRmgabymGI1", "outputId": "0071e88d-c55b-43d8-bf51-9055ef59ce7f", "colab": { "base_uri": "https://localhost:8080/" } }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Mounted at /content/drive\n" ] } ] }, { "cell_type": "code", "source": [ "\n", "zip_dest = '/content/drive/MyDrive/fanfic1.zip'\n", "!zip -r {zip_dest} {output_folder}" ], "metadata": { "id": "wk3KETWdZv1h" }, "execution_count": null, "outputs": [] } ] }