{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "0W3w2zmgi6cp" }, "outputs": [], "source": [ "# ============================================================\n", "# Sample Encrypted Arrow Multimodal Dataset (gemma4_arrow_encrypted_v1)\n", "# Google Colab\n", "#\n", "# Loads codeShare/kromoss-lora-exports/gemma4_arrow_encrypted_v1\n", "# Decrypts image_enc + conversation_enc with the same scheme as the builder:\n", "# AES-256-GCM, scrypt KDF, AAD = b\"gemma4-v1:{sample_id}:{field_name}\"\n", "# ============================================================\n", "\n", "!pip -q install -U datasets pyarrow cryptography pillow huggingface_hub tqdm\n", "\n", "import os\n", "import io\n", "import json\n", "import base64\n", "import random\n", "from pathlib import Path\n", "\n", "from google.colab import userdata\n", "from PIL import Image\n", "from IPython.display import display\n", "from datasets import load_from_disk\n", "from huggingface_hub import snapshot_download, HfApi\n", "from cryptography.hazmat.primitives.ciphers.aead import AESGCM\n", "from cryptography.hazmat.primitives.kdf.scrypt import Scrypt\n", "from tqdm.auto import tqdm\n", "\n", "# ============================================================\n", "# CONFIGURATION\n", "# ============================================================\n", "\n", "REPO_ID = \"codeShare/kromoss-lora-exports\"\n", "REPO_TYPE = \"model\"\n", "SUBFOLDER = \"gemma4_arrow_encrypted_v1\"\n", "\n", "# Must match the password used when the encrypted dataset was built.\n", "PASSWORD = userdata.get(\"ENC_PWD\")\n", "if not PASSWORD:\n", " raise ValueError(\"ENC_PWD is missing from Colab Secrets.\")\n", "\n", "# How many examples to show\n", "NUM_EXAMPLES = 20\n", "\n", "# Sampling\n", "RANDOM_SEED = 42\n", "# True -> random sample of NUM_EXAMPLES\n", "# False -> first NUM_EXAMPLES rows (idx order after shuffle is still shuffled)\n", "RANDOM_SAMPLE = True\n", "\n", "# Local cache\n", "LOCAL_DIR = Path(\"/content/encrypted_dataset_sample\")\n", "LOCAL_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "# ============================================================\n", "# AUTH\n", "# ============================================================\n", "\n", "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n", "if not HF_TOKEN:\n", " raise ValueError(\"HF_TOKEN is missing from Colab Secrets.\")\n", "\n", "api = HfApi(token=HF_TOKEN)\n", "print(\"Authenticated as:\", api.whoami()[\"name\"])\n", "\n", "# ============================================================\n", "# DOWNLOAD DATASET FOLDER\n", "# ============================================================\n", "\n", "print(f\"\\nDownloading {REPO_ID}/{SUBFOLDER} ...\")\n", "snapshot_download(\n", " repo_id=REPO_ID,\n", " repo_type=REPO_TYPE,\n", " token=HF_TOKEN,\n", " local_dir=str(LOCAL_DIR),\n", " allow_patterns=[f\"{SUBFOLDER}/**\"],\n", ")\n", "\n", "dataset_dir = LOCAL_DIR / SUBFOLDER\n", "manifest_path = dataset_dir / \"encryption_manifest.json\"\n", "\n", "if not manifest_path.is_file():\n", " raise FileNotFoundError(\n", " f\"encryption_manifest.json not found under {dataset_dir}. \"\n", " \"Check SUBFOLDER / repo path.\"\n", " )\n", "\n", "with open(manifest_path, \"r\", encoding=\"utf-8\") as f:\n", " manifest = json.load(f)\n", "\n", "print(\"Manifest sample_count:\", manifest.get(\"sample_count\"))\n", "print(\"Cipher:\", manifest.get(\"encryption\", {}).get(\"cipher\"))\n", "print(\"KDF:\", manifest.get(\"encryption\", {}).get(\"kdf\"))\n", "\n", "# ============================================================\n", "# DERIVE DECRYPTION KEY FROM MANIFEST\n", "# ============================================================\n", "\n", "enc = manifest[\"encryption\"]\n", "if enc.get(\"cipher\") != \"AES-256-GCM\":\n", " raise RuntimeError(f\"Unexpected cipher: {enc.get('cipher')}\")\n", "if enc.get(\"kdf\") != \"scrypt\":\n", " raise RuntimeError(f\"Unexpected KDF: {enc.get('kdf')}\")\n", "\n", "salt = base64.b64decode(enc[\"kdf_salt_base64\"])\n", "n = int(enc[\"scrypt_n\"])\n", "r = int(enc[\"scrypt_r\"])\n", "p = int(enc[\"scrypt_p\"])\n", "key_len = int(enc.get(\"key_length_bytes\", 32))\n", "\n", "KEY = Scrypt(\n", " salt=salt,\n", " length=key_len,\n", " n=n,\n", " r=r,\n", " p=p,\n", ").derive(PASSWORD.encode(\"utf-8\"))\n", "\n", "print(\"Decryption key derived (scrypt).\")\n", "\n", "# ============================================================\n", "# LOAD ARROW DATASET\n", "# ============================================================\n", "\n", "ds = load_from_disk(str(dataset_dir))\n", "print(\"Loaded rows:\", f\"{len(ds):,}\")\n", "print(\"Columns:\", ds.column_names)\n", "\n", "# ============================================================\n", "# DECRYPT HELPERS\n", "# ============================================================\n", "\n", "def decrypt_payload(encrypted_payload, sample_id, field_name, key=KEY):\n", " \"\"\"\n", " Layout: nonce[12] || ciphertext\n", " AAD: gemma4-v1:{sample_id}:{field_name}\n", " \"\"\"\n", " if not isinstance(encrypted_payload, (bytes, bytearray, memoryview)):\n", " encrypted_payload = bytes(encrypted_payload)\n", "\n", " if len(encrypted_payload) <= 12:\n", " raise ValueError(\"Encrypted payload too short.\")\n", "\n", " nonce = encrypted_payload[:12]\n", " ciphertext = encrypted_payload[12:]\n", " aad = f\"gemma4-v1:{sample_id}:{field_name}\".encode(\"utf-8\")\n", " return AESGCM(key).decrypt(nonce, ciphertext, aad)\n", "\n", "\n", "def parse_conversation(conversation_bytes):\n", " data = json.loads(conversation_bytes.decode(\"utf-8\"))\n", " messages = data[\"messages\"]\n", " if len(messages) != 2:\n", " raise ValueError(f\"Expected 2 messages, got {len(messages)}\")\n", "\n", " user_msg, asst_msg = messages[0], messages[1]\n", " if user_msg[\"role\"] != \"user\" or asst_msg[\"role\"] != \"assistant\":\n", " raise ValueError(\"Unexpected roles in conversation.\")\n", "\n", " # User: text + image placeholder\n", " user_text = None\n", " for part in user_msg[\"content\"]:\n", " if part.get(\"type\") == \"text\":\n", " user_text = part.get(\"text\", \"\")\n", " break\n", "\n", " asst_text = None\n", " for part in asst_msg[\"content\"]:\n", " if part.get(\"type\") == \"text\":\n", " asst_text = part.get(\"text\", \"\")\n", " break\n", "\n", " if user_text is None or asst_text is None:\n", " raise ValueError(\"Missing text in conversation content.\")\n", "\n", " return user_text, asst_text\n", "\n", "\n", "def decrypt_row(row):\n", " sample_id = row[\"sample_id\"]\n", " image_bytes = decrypt_payload(row[\"image_enc\"], sample_id, \"image\")\n", " conv_bytes = decrypt_payload(row[\"conversation_enc\"], sample_id, \"conversation\")\n", " user_text, asst_text = parse_conversation(conv_bytes)\n", " return {\n", " \"sample_id\": sample_id,\n", " \"idx\": row.get(\"idx\"),\n", " \"width\": row[\"width\"],\n", " \"height\": row[\"height\"],\n", " \"image_format\": row[\"image_format\"],\n", " \"input\": user_text,\n", " \"output\": asst_text,\n", " \"image_bytes\": image_bytes,\n", " }\n", "\n", "\n", "# ============================================================\n", "# PASSWORD SANITY CHECK (first row)\n", "# ============================================================\n", "\n", "print(\"\\nVerifying password against row 0...\")\n", "try:\n", " _ = decrypt_row(ds[0])\n", " print(\"Password verification: PASS\")\n", "except Exception as e:\n", " raise RuntimeError(\n", " \"Failed to decrypt row 0. Wrong PASSWORD or incompatible dataset. \"\n", " f\"Error: {e!r}\"\n", " ) from e\n", "\n", "# ============================================================\n", "# SELECT ROWS TO DISPLAY\n", "# ============================================================\n", "\n", "n = len(ds)\n", "k = min(NUM_EXAMPLES, n)\n", "\n", "if RANDOM_SAMPLE:\n", " rng = random.Random(RANDOM_SEED)\n", " indices = rng.sample(range(n), k=k)\n", "else:\n", " indices = list(range(k))\n", "\n", "print(f\"\\nDisplaying {k} example(s) \"\n", " f\"({'random seed=' + str(RANDOM_SEED) if RANDOM_SAMPLE else 'first rows'})\")\n", "\n", "# ============================================================\n", "# DISPLAY\n", "# ============================================================\n", "\n", "# Resize for notebook display (longest side)\n", "DISPLAY_MAX_SIDE = 350\n", "\n", "for i, row_i in enumerate(indices, start=1):\n", " row = ds[int(row_i)]\n", " item = decrypt_row(row)\n", "\n", " print(\"\\n\" + \"=\" * 90)\n", " print(f\"DATASET EXAMPLE {i}/{k} | dataset_index={row_i} | idx={item['idx']}\")\n", " print(f\"sample_id={item['sample_id']}\")\n", " print(f\"image={item['width']}x{item['height']} {item['image_format']}\")\n", " print(\"=\" * 90)\n", "\n", " print(\"\\nINPUT:\")\n", " print(item[\"input\"])\n", "\n", " print(\"\\nOUTPUT:\")\n", " print(item[\"output\"])\n", "\n", " print(\"\\nIMAGE:\")\n", " with Image.open(io.BytesIO(item[\"image_bytes\"])) as im:\n", " im = im.convert(\"RGB\")\n", " w, h = im.size\n", " scale = DISPLAY_MAX_SIDE / max(w, h)\n", " if scale < 1.0:\n", " im = im.resize(\n", " (max(1, round(w * scale)), max(1, round(h * scale))),\n", " Image.Resampling.LANCZOS,\n", " )\n", " display(im)\n", "\n", "print(f\"\\nSuccessfully displayed {k} example(s).\")" ] } ] }