Update MMSearch-Plus dataset with encrypted text fields (images unchanged)
Browse files- README.md +7 -26
- decrypt_after_load.py +269 -0
README.md
CHANGED
|
@@ -73,40 +73,21 @@ Official repository for the paper "[MMSearch-Plus: Benchmarking Provenance-Aware
|
|
| 73 |
|
| 74 |
### Dataset Usage
|
| 75 |
|
| 76 |
-
|
| 77 |
|
| 78 |
```python
|
| 79 |
import os
|
| 80 |
-
from huggingface_hub import hf_hub_download, snapshot_download
|
| 81 |
from datasets import load_dataset
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
#
|
| 87 |
-
snapshot_download(
|
| 88 |
-
repo_id="Cie1/MMSearch-Plus",
|
| 89 |
-
repo_type="dataset",
|
| 90 |
-
revision="main"
|
| 91 |
-
)
|
| 92 |
-
|
| 93 |
-
# Download the custom data loader script
|
| 94 |
-
script_path = hf_hub_download(
|
| 95 |
-
repo_id="Cie1/MMSearch-Plus",
|
| 96 |
-
filename="mmsearch_plus.py",
|
| 97 |
-
repo_type="dataset",
|
| 98 |
-
revision="main"
|
| 99 |
)
|
| 100 |
|
| 101 |
-
# Load dataset with transparent decryption using the custom loader
|
| 102 |
-
dataset = load_dataset(script_path, trust_remote_code=True)
|
| 103 |
-
|
| 104 |
-
# Explore the dataset - everything is already decrypted!
|
| 105 |
-
print(f"Dataset size: {len(dataset['train'])}")
|
| 106 |
-
print(f"Features: {list(dataset['train'].features.keys())}")
|
| 107 |
-
|
| 108 |
# Access a sample
|
| 109 |
-
sample =
|
| 110 |
print(f"Question: {sample['question']}")
|
| 111 |
print(f"Answer: {sample['answer']}")
|
| 112 |
print(f"Category: {sample['category']}")
|
|
|
|
| 73 |
|
| 74 |
### Dataset Usage
|
| 75 |
|
| 76 |
+
For better compatibility with newer versions of the datasets library, we provide explicit decryption functions:
|
| 77 |
|
| 78 |
```python
|
| 79 |
import os
|
|
|
|
| 80 |
from datasets import load_dataset
|
| 81 |
+
from decrypt_after_load import decrypt_mmsearch_plus, decrypt_dataset
|
| 82 |
|
| 83 |
+
encrypted_dataset = load_dataset("Cie1/MMSearch-Plus", split='train')
|
| 84 |
+
decrypted_dataset = decrypt_dataset(
|
| 85 |
+
encrypted_dataset=encrypted_dataset,
|
| 86 |
+
canary='your_canary_string' # Set the canary string (hint: it's the name of this repo without username)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
)
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
# Access a sample
|
| 90 |
+
sample = decrypted_dataset[0]
|
| 91 |
print(f"Question: {sample['question']}")
|
| 92 |
print(f"Answer: {sample['answer']}")
|
| 93 |
print(f"Category: {sample['category']}")
|
decrypt_after_load.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Decrypt MMSearch-Plus dataset after loading from HuggingFace Hub.
|
| 4 |
+
|
| 5 |
+
This module provides two main functions:
|
| 6 |
+
1. decrypt_dataset(): Decrypt an already-loaded Dataset object
|
| 7 |
+
2. decrypt_mmsearch_plus(): Load from path and decrypt in one step
|
| 8 |
+
|
| 9 |
+
Example usage with loaded dataset:
|
| 10 |
+
from datasets import load_dataset
|
| 11 |
+
from decrypt_after_load import decrypt_dataset
|
| 12 |
+
|
| 13 |
+
# Load encrypted dataset
|
| 14 |
+
encrypted_ds = load_dataset("username/mmsearch-plus-encrypted", split='train')
|
| 15 |
+
|
| 16 |
+
# Decrypt it
|
| 17 |
+
decrypted_ds = decrypt_dataset(encrypted_ds, canary="MMSearch-Plus")
|
| 18 |
+
|
| 19 |
+
Example usage with path:
|
| 20 |
+
from decrypt_after_load import decrypt_mmsearch_plus
|
| 21 |
+
|
| 22 |
+
# Load and decrypt in one step
|
| 23 |
+
decrypted_ds = decrypt_mmsearch_plus(
|
| 24 |
+
dataset_path="username/mmsearch-plus-encrypted",
|
| 25 |
+
canary="MMSearch-Plus"
|
| 26 |
+
)
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import base64
|
| 30 |
+
import hashlib
|
| 31 |
+
import argparse
|
| 32 |
+
import io
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from datasets import load_dataset, load_from_disk, Dataset
|
| 35 |
+
from PIL import Image
|
| 36 |
+
from typing import Dict, Any
|
| 37 |
+
import os
|
| 38 |
+
|
| 39 |
+
def derive_key(password: str, length: int) -> bytes:
|
| 40 |
+
"""Derive encryption key from password using SHA-256."""
|
| 41 |
+
hasher = hashlib.sha256()
|
| 42 |
+
hasher.update(password.encode())
|
| 43 |
+
key = hasher.digest()
|
| 44 |
+
return key * (length // len(key)) + key[: length % len(key)]
|
| 45 |
+
|
| 46 |
+
def decrypt_image(ciphertext_b64: str, password: str) -> Image.Image:
|
| 47 |
+
"""Decrypt base64-encoded encrypted image bytes back to PIL Image."""
|
| 48 |
+
if not ciphertext_b64:
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
encrypted = base64.b64decode(ciphertext_b64)
|
| 53 |
+
key = derive_key(password, len(encrypted))
|
| 54 |
+
decrypted = bytes([a ^ b for a, b in zip(encrypted, key)])
|
| 55 |
+
|
| 56 |
+
# Convert bytes back to PIL Image
|
| 57 |
+
img_buffer = io.BytesIO(decrypted)
|
| 58 |
+
image = Image.open(img_buffer)
|
| 59 |
+
return image
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"[Warning] Image decryption failed: {e}")
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
def decrypt_text(ciphertext_b64: str, password: str) -> str:
|
| 65 |
+
"""Decrypt base64-encoded ciphertext using XOR cipher with derived key."""
|
| 66 |
+
if not ciphertext_b64:
|
| 67 |
+
return ciphertext_b64
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
encrypted = base64.b64decode(ciphertext_b64)
|
| 71 |
+
key = derive_key(password, len(encrypted))
|
| 72 |
+
decrypted = bytes([a ^ b for a, b in zip(encrypted, key)])
|
| 73 |
+
return decrypted.decode('utf-8')
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"[Warning] Decryption failed: {e}")
|
| 76 |
+
return ciphertext_b64 # Return original if decryption fails
|
| 77 |
+
|
| 78 |
+
def decrypt_sample(sample: Dict[str, Any], canary: str) -> Dict[str, Any]:
|
| 79 |
+
"""Decrypt text and image fields in a single sample using the provided canary password."""
|
| 80 |
+
decrypted_sample = sample.copy()
|
| 81 |
+
|
| 82 |
+
# Decrypt text fields (must match what was encrypted)
|
| 83 |
+
text_fields = ['question', 'video_url', 'arxiv_id']
|
| 84 |
+
|
| 85 |
+
for field in text_fields:
|
| 86 |
+
if field in sample and sample[field]:
|
| 87 |
+
decrypted_sample[field] = decrypt_text(sample[field], canary)
|
| 88 |
+
|
| 89 |
+
# Handle answer field (list of strings)
|
| 90 |
+
if 'answer' in sample and sample['answer']:
|
| 91 |
+
decrypted_answers = []
|
| 92 |
+
for answer in sample['answer']:
|
| 93 |
+
if answer:
|
| 94 |
+
decrypted_answers.append(decrypt_text(answer, canary))
|
| 95 |
+
else:
|
| 96 |
+
decrypted_answers.append(answer)
|
| 97 |
+
decrypted_sample['answer'] = decrypted_answers
|
| 98 |
+
|
| 99 |
+
# Images are NOT encrypted in the current version, so no image decryption needed
|
| 100 |
+
# If your dataset has encrypted images (base64 strings), uncomment below:
|
| 101 |
+
# image_fields = ['img_1', 'img_2', 'img_3', 'img_4', 'img_5']
|
| 102 |
+
# for field in image_fields:
|
| 103 |
+
# if field in sample and sample[field] is not None and isinstance(sample[field], str):
|
| 104 |
+
# decrypted_sample[field] = decrypt_image(sample[field], canary)
|
| 105 |
+
|
| 106 |
+
return decrypted_sample
|
| 107 |
+
|
| 108 |
+
def decrypt_dataset(encrypted_dataset: Dataset, canary: str, output_path: str = None) -> Dataset:
|
| 109 |
+
"""
|
| 110 |
+
Decrypt an already-loaded dataset object.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
encrypted_dataset: Already loaded Dataset object to decrypt
|
| 114 |
+
canary: Canary string used for encryption
|
| 115 |
+
output_path: Path to save decrypted dataset (optional)
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Decrypted Dataset object
|
| 119 |
+
"""
|
| 120 |
+
if not isinstance(encrypted_dataset, Dataset):
|
| 121 |
+
raise TypeError(f"Expected Dataset object, got {type(encrypted_dataset)}")
|
| 122 |
+
|
| 123 |
+
print(f"📊 Dataset contains {len(encrypted_dataset)} samples")
|
| 124 |
+
print(f"🔧 Features: {list(encrypted_dataset.features.keys())}")
|
| 125 |
+
print(f"🔑 Using canary string: {canary}")
|
| 126 |
+
|
| 127 |
+
# Decrypt the dataset using map function for efficiency
|
| 128 |
+
print(f"🔄 Decrypting dataset...")
|
| 129 |
+
|
| 130 |
+
def decrypt_batch(batch):
|
| 131 |
+
"""Decrypt a batch of samples."""
|
| 132 |
+
# Get the number of samples in the batch
|
| 133 |
+
num_samples = len(batch[list(batch.keys())[0]])
|
| 134 |
+
|
| 135 |
+
# Process each sample in the batch
|
| 136 |
+
decrypted_batch = {key: [] for key in batch.keys()}
|
| 137 |
+
|
| 138 |
+
for i in range(num_samples):
|
| 139 |
+
# Extract single sample from batch
|
| 140 |
+
sample = {key: batch[key][i] for key in batch.keys()}
|
| 141 |
+
|
| 142 |
+
# Decrypt sample
|
| 143 |
+
decrypted_sample = decrypt_sample(sample, canary)
|
| 144 |
+
|
| 145 |
+
# Add to decrypted batch
|
| 146 |
+
for key in decrypted_batch.keys():
|
| 147 |
+
decrypted_batch[key].append(decrypted_sample.get(key))
|
| 148 |
+
|
| 149 |
+
return decrypted_batch
|
| 150 |
+
|
| 151 |
+
# Apply decryption with batching
|
| 152 |
+
decrypted_dataset = encrypted_dataset.map(
|
| 153 |
+
decrypt_batch,
|
| 154 |
+
batched=True,
|
| 155 |
+
batch_size=50,
|
| 156 |
+
desc="Decrypting samples"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
print(f"✅ Decryption completed!")
|
| 160 |
+
print(f"📝 Decrypted {len(decrypted_dataset)} samples")
|
| 161 |
+
print(f"🔓 Text fields decrypted: question, answer, video_url, arxiv_id")
|
| 162 |
+
print(f"🖼️ Images: kept as-is (not encrypted in current version)")
|
| 163 |
+
print(f"📋 Metadata preserved: category, difficulty, subtask, etc.")
|
| 164 |
+
|
| 165 |
+
# Save if output path provided
|
| 166 |
+
if output_path:
|
| 167 |
+
print(f"💾 Saving decrypted dataset to: {output_path}")
|
| 168 |
+
decrypted_dataset.save_to_disk(output_path)
|
| 169 |
+
print(f"✅ Saved successfully!")
|
| 170 |
+
|
| 171 |
+
return decrypted_dataset
|
| 172 |
+
|
| 173 |
+
def decrypt_mmsearch_plus(dataset_path: str, canary: str, output_path: str = None, from_hub: bool = False):
|
| 174 |
+
"""
|
| 175 |
+
Load and decrypt the MMSearch-Plus dataset.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
dataset_path: Path to local dataset or HuggingFace Hub repo ID
|
| 179 |
+
canary: Canary string used for encryption
|
| 180 |
+
output_path: Path to save decrypted dataset (optional)
|
| 181 |
+
from_hub: Whether to load from HuggingFace Hub (default: auto-detect)
|
| 182 |
+
"""
|
| 183 |
+
# Auto-detect if loading from hub (contains "/" and doesn't exist locally)
|
| 184 |
+
if not from_hub:
|
| 185 |
+
from_hub = "/" in dataset_path and not Path(dataset_path).exists()
|
| 186 |
+
|
| 187 |
+
# Load the encrypted dataset
|
| 188 |
+
if from_hub:
|
| 189 |
+
print(f"🔓 Loading encrypted dataset from HuggingFace Hub: {dataset_path}")
|
| 190 |
+
# Load from HuggingFace Hub without trust_remote_code
|
| 191 |
+
encrypted_dataset = load_dataset(dataset_path, split='train')
|
| 192 |
+
else:
|
| 193 |
+
print(f"🔓 Loading encrypted dataset from local path: {dataset_path}")
|
| 194 |
+
# Check if path exists
|
| 195 |
+
if not Path(dataset_path).exists():
|
| 196 |
+
raise ValueError(f"Dataset path does not exist: {dataset_path}")
|
| 197 |
+
encrypted_dataset = load_from_disk(dataset_path)
|
| 198 |
+
|
| 199 |
+
# Use decrypt_dataset to handle the actual decryption
|
| 200 |
+
return decrypt_dataset(encrypted_dataset, canary, output_path)
|
| 201 |
+
|
| 202 |
+
def main():
|
| 203 |
+
parser = argparse.ArgumentParser(
|
| 204 |
+
description="Decrypt MMSearch-Plus dataset after loading from HuggingFace Hub or local path.",
|
| 205 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 206 |
+
epilog="""
|
| 207 |
+
Examples:
|
| 208 |
+
# From HuggingFace Hub
|
| 209 |
+
python decrypt_after_load.py --dataset-path username/mmsearch-plus-encrypted --canary "MMSearch-Plus" --output ./decrypted
|
| 210 |
+
|
| 211 |
+
# From local directory
|
| 212 |
+
python decrypt_after_load.py --dataset-path ./mmsearch_plus_encrypted --canary "MMSearch-Plus" --output ./decrypted
|
| 213 |
+
|
| 214 |
+
# Using environment variable for canary
|
| 215 |
+
export MMSEARCH_PLUS="your-canary-string"
|
| 216 |
+
python decrypt_after_load.py --dataset-path username/mmsearch-plus-encrypted --output ./decrypted
|
| 217 |
+
"""
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--dataset-path",
|
| 221 |
+
required=True,
|
| 222 |
+
help="Path to encrypted dataset (local directory or HuggingFace Hub repo ID)"
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--canary",
|
| 226 |
+
help="Canary string used for encryption (or set MMSEARCH_PLUS environment variable)"
|
| 227 |
+
)
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--output",
|
| 230 |
+
help="Path to save the decrypted dataset (optional, defaults to not saving)"
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--from-hub",
|
| 234 |
+
action="store_true",
|
| 235 |
+
help="Force loading from HuggingFace Hub (auto-detected by default)"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
args = parser.parse_args()
|
| 239 |
+
|
| 240 |
+
# Get canary from args or environment variable
|
| 241 |
+
canary = args.canary or os.environ.get("MMSEARCH_PLUS")
|
| 242 |
+
|
| 243 |
+
if not canary:
|
| 244 |
+
raise ValueError(
|
| 245 |
+
"Canary string is required for decryption. Either provide --canary argument "
|
| 246 |
+
"or set the MMSEARCH_PLUS environment variable.\n"
|
| 247 |
+
"Example: export MMSEARCH_PLUS='your-canary-string'"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# Check if output path exists
|
| 251 |
+
if args.output:
|
| 252 |
+
output_path = Path(args.output)
|
| 253 |
+
if output_path.exists():
|
| 254 |
+
response = input(f"Output path {output_path} already exists. Overwrite? (y/N): ")
|
| 255 |
+
if response.lower() != 'y':
|
| 256 |
+
print("Aborted.")
|
| 257 |
+
return
|
| 258 |
+
|
| 259 |
+
# Decrypt dataset
|
| 260 |
+
decrypt_mmsearch_plus(
|
| 261 |
+
dataset_path=args.dataset_path,
|
| 262 |
+
canary=canary,
|
| 263 |
+
output_path=args.output,
|
| 264 |
+
from_hub=args.from_hub
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
main()
|
| 269 |
+
|