File size: 8,300 Bytes
a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 e3e057f a090310 |
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 |
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "semhash",
# "datasets",
# "huggingface-hub",
# "hf-transfer",
# ]
# ///
"""
Semantic deduplication for Hugging Face datasets using SemHash.
This script removes duplicate or near-duplicate text samples from datasets based on
semantic similarity, helping to clean training data and prevent train/test leakage.
SemHash is CPU-optimized and uses Model2Vec embeddings that are 500x faster on CPU
than traditional transformers. No GPU required!
Example usage:
# Basic deduplication
uv run semantic-dedupe.py username/dataset text username/dataset-deduped
# With custom threshold and max samples for testing
uv run semantic-dedupe.py username/dataset text username/dataset-deduped \\
--threshold 0.85 --max-samples 1000
# Using HF Jobs (CPU is sufficient)
hf jobs uv run --flavor cpu-4x-xlarge \\
-e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\
https://huggingface.co/datasets/uv-scripts/deduplication/raw/main/semantic-dedupe.py \\
username/dataset text username/dataset-deduped
"""
import argparse
import os
import sys
from datetime import datetime
from typing import Optional
from datasets import Dataset, load_dataset
from huggingface_hub import DatasetCard, login
from semhash import SemHash
# Enable fast transfers
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
def parse_args():
parser = argparse.ArgumentParser(
description="Deduplicate a dataset using semantic similarity",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic usage
uv run semantic-dedupe.py imdb text imdb-deduped
# With options
uv run semantic-dedupe.py squad question squad-deduped --threshold 0.85 --method duplicates
# Test with small sample
uv run semantic-dedupe.py large-dataset text test-dedup --max-samples 100
""",
)
parser.add_argument("dataset", help="Input dataset ID (e.g., 'imdb' or 'username/dataset')")
parser.add_argument("column", help="Text column to deduplicate on")
parser.add_argument("output_repo", help="Output dataset repository name")
parser.add_argument(
"--split",
default="train",
help="Dataset split to process (default: train)",
)
parser.add_argument(
"--method",
choices=["duplicates", "outliers", "representatives"],
default="duplicates",
help="Deduplication method (default: duplicates)",
)
parser.add_argument(
"--threshold",
type=float,
default=0.9,
help="Similarity threshold for duplicates (default: 0.9)",
)
parser.add_argument(
"--batch-size",
type=int,
default=64,
help="Batch size for processing (default: 64)",
)
parser.add_argument(
"--max-samples",
type=int,
help="Maximum number of samples to process (for testing)",
)
parser.add_argument(
"--private",
action="store_true",
help="Create private dataset repository",
)
parser.add_argument(
"--hf-token",
default=os.environ.get("HF_TOKEN"),
help="Hugging Face API token (defaults to HF_TOKEN env var)",
)
return parser.parse_args()
def create_dataset_card(
original_dataset: str,
column: str,
method: str,
threshold: float,
original_size: int,
deduped_size: int,
) -> str:
"""Create a dataset card with deduplication information."""
reduction_pct = ((original_size - deduped_size) / original_size) * 100
return f"""---
viewer: false
tags:
- deduplication
- semhash
- uv-script
---
# Deduplicated {original_dataset}
This dataset is a deduplicated version of [{original_dataset}](https://huggingface.co/datasets/{original_dataset}).
## Deduplication Details
- **Method**: {method}
- **Column**: `{column}`
- **Threshold**: {threshold}
- **Original size**: {original_size:,} samples
- **Deduplicated size**: {deduped_size:,} samples
- **Reduction**: {reduction_pct:.1f}%
- **Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
## Method Description
{get_method_description(method)}
## How to Use
```python
from datasets import load_dataset
# Load the deduplicated dataset
dataset = load_dataset("{os.environ.get('HF_USERNAME', 'username')}/{os.path.basename(original_dataset)}-deduped")
```
## Reproduce
This dataset was created using the [uv-scripts/deduplication](https://huggingface.co/datasets/uv-scripts/deduplication) tool:
```bash
uv run https://huggingface.co/datasets/uv-scripts/deduplication/raw/main/semantic-dedupe.py \\
{original_dataset} {column} {os.path.basename(original_dataset)}-deduped \\
--method {method} --threshold {threshold}
```
Generated with 🤖 UV Scripts
"""
def get_method_description(method: str) -> str:
"""Get description for deduplication method."""
descriptions = {
"duplicates": "Removes semantic duplicates by finding samples with high similarity scores above the threshold.",
"outliers": "Removes outlier samples that have low similarity to other samples in the dataset.",
"representatives": "Keeps only representative samples, removing both duplicates and outliers.",
}
return descriptions.get(method, "Unknown method")
def main():
args = parse_args()
# Authenticate
if args.hf_token:
login(args.hf_token)
else:
print("Warning: No HF token provided. Using cached credentials or anonymous mode.")
# Load dataset
print(f"Loading dataset: {args.dataset}")
dataset = load_dataset(args.dataset, split=args.split)
# Apply max samples if specified
if args.max_samples:
dataset = dataset.select(range(min(args.max_samples, len(dataset))))
print(f"Limited to {len(dataset)} samples for testing")
original_size = len(dataset)
# Check if column exists
if args.column not in dataset.column_names:
print(f"Error: Column '{args.column}' not found in dataset")
print(f"Available columns: {', '.join(dataset.column_names)}")
sys.exit(1)
# Convert dataset to records (preserves all columns)
print("Converting dataset to records...")
records = [dict(row) for row in dataset]
# Initialize SemHash
print("Initializing SemHash (CPU-optimized)...")
semhash = SemHash.from_records(records=records, columns=[args.column])
# Perform deduplication
print(f"Performing {args.method} deduplication on '{args.column}' column...")
if args.method == "duplicates":
result = semhash.self_deduplicate(threshold=args.threshold)
elif args.method == "outliers":
result = semhash.self_filter_outliers()
elif args.method == "representatives":
result = semhash.self_find_representative()
else:
raise ValueError(f"Unknown method: {args.method}")
# Get deduplicated records (all columns preserved)
deduplicated_records = result.selected
# Convert back to HF Dataset
result_dataset = Dataset.from_list(deduplicated_records)
deduped_size = len(result_dataset)
# Print statistics
print(f"\nDeduplication complete!")
print(f"Original size: {original_size:,}")
print(f"Deduplicated size: {deduped_size:,}")
print(f"Removed: {original_size - deduped_size:,} ({((original_size - deduped_size) / original_size) * 100:.1f}%)")
print("\nNote: SemHash processes ~20,000 sentences/second on CPU")
# Create dataset card
card = create_dataset_card(
args.dataset,
args.column,
args.method,
args.threshold,
original_size,
deduped_size,
)
# Push to hub
print(f"\nPushing to hub: {args.output_repo}")
result_dataset.push_to_hub(
args.output_repo,
private=args.private,
commit_message=f"Deduplicated using {args.method} method",
)
# Create and push dataset card
dataset_card = DatasetCard(card)
dataset_card.push_to_hub(args.output_repo)
print(f"✅ Dataset successfully pushed to: https://huggingface.co/datasets/{args.output_repo}")
if __name__ == "__main__":
main() |