hatespeechmix / scripts /build_dataset.py
villacu's picture
Add full English and Turkish text with three-way labels
7859146 verified
Raw History Blame Contribute Delete
23.2 kB
#!/usr/bin/env python3
"""Build the multilingual HateSpeechMix DatasetDict.
The conversion is intentionally conservative:
* ``label`` uses the shared three-way space: neutral, offensive, and hate.
* ``fine_label`` and ``source_label`` retain the available source semantics.
* Chinese positives map to offensive because its main labels do not
distinguish offensive content from hate.
* Official test splits are preserved. Upstream dev splits are folded into
train. The unsplit English/Turkish data receives a deterministic,
stratified 90/10 split.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import io
import json
import shutil
import urllib.request
import zipfile
from collections import Counter, defaultdict
from pathlib import Path
from typing import Iterable, Iterator
from datasets import ClassLabel, Dataset, DatasetDict, Features, Value
BUILD_VERSION = "2.0.0"
SPLIT_SEED = "hatespeechmix-v1"
REPO_ROOT = Path(__file__).resolve().parents[1]
WORKSPACE_ROOT = REPO_ROOT.parent
SOURCE_SPECS = {
"toraman_en_tr": {
"url": (
"https://raw.githubusercontent.com/metunlp/hate-speech/"
"f27c847b34e68c40ac654219b5824f8750b284d8/"
"dataset_v2/Toraman22_hate_speech_v2.tsv"
),
"sha256": "c6c110de8e9656577b5781c8173d7974268c8e716adf5d804f98a50b2f4c0a95",
"filename": "toraman22_hate_speech_v2.tsv",
"revision": "f27c847b34e68c40ac654219b5824f8750b284d8",
},
"cold_zh": {
"url": (
"https://github.com/thu-coai/COLDataset/archive/"
"a0c55a945497ab58e94aef491180e1cf88ffb864.zip"
),
"sha256": "8d8e4d2807a5eb5350a47ae733aac14fe6a0b24b77ad98da0a7693dbf8beca52",
"filename": "cold_zh.zip",
"revision": "a0c55a945497ab58e94aef491180e1cf88ffb864",
},
"am_train": {
"url": (
"https://huggingface.co/datasets/uhhlt/amharichatespeechranlp/resolve/"
"af6f5d115105a75387e8f67843ee77c807b84c4b/train.tsv"
),
"sha256": "bccb82e9c777f04b3645e1de74c56520959e43ba782123c827805bbd42d3c6a5",
"filename": "am_train.tsv",
"revision": "af6f5d115105a75387e8f67843ee77c807b84c4b",
},
"am_dev": {
"url": (
"https://huggingface.co/datasets/uhhlt/amharichatespeechranlp/resolve/"
"af6f5d115105a75387e8f67843ee77c807b84c4b/dev.tsv"
),
"sha256": "9d5767e0b52a876de1f87cd685e4a77cdf8564b463dbc547d202401680a61edf",
"filename": "am_dev.tsv",
"revision": "af6f5d115105a75387e8f67843ee77c807b84c4b",
},
"am_test": {
"url": (
"https://huggingface.co/datasets/uhhlt/amharichatespeechranlp/resolve/"
"af6f5d115105a75387e8f67843ee77c807b84c4b/test.tsv"
),
"sha256": "245e88a99894e6687acfca686c6661ad87387fe7ca10750e85e42c72025c1fbb",
"filename": "am_test.tsv",
"revision": "af6f5d115105a75387e8f67843ee77c807b84c4b",
},
}
HINDI_SHA256 = "d419780fe825f9946e3a03da4cf3fdf41699b188932d3662ca304693829994ad"
LABEL_NAMES = ["neutral", "offensive", "hate"]
FEATURES = Features(
{
"text": Value("string"),
"label": ClassLabel(names=LABEL_NAMES),
"label_text": Value("string"),
"fine_label": Value("string"),
"language": Value("string"),
"source": Value("string"),
"source_id": Value("string"),
"source_label": Value("string"),
"original_split": Value("string"),
"topic": Value("string"),
"target": Value("string"),
"text_available": Value("bool"),
}
)
RAW_LANGUAGE_COUNTS = {
"am": 15_001,
"en": 68_597,
"hi": 5_983,
"tr": 60_310,
"zh": 37_480,
}
EXPECTED_LANGUAGE_COUNTS = {
"am": 15_000,
"en": 68_597,
"hi": 5_982,
"tr": 60_310,
"zh": 37_426,
}
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def verify_file(path: Path, expected_sha256: str) -> None:
actual = sha256(path)
if actual != expected_sha256:
raise ValueError(
f"SHA-256 mismatch for {path}: expected {expected_sha256}, got {actual}"
)
def download_sources(cache_dir: Path) -> dict[str, Path]:
cache_dir.mkdir(parents=True, exist_ok=True)
paths: dict[str, Path] = {}
for name, spec in SOURCE_SPECS.items():
path = cache_dir / str(spec["filename"])
if path.exists():
try:
verify_file(path, str(spec["sha256"]))
except ValueError:
path.unlink()
if not path.exists():
temporary = path.with_suffix(path.suffix + ".partial")
with urllib.request.urlopen(str(spec["url"])) as response:
with temporary.open("wb") as handle:
shutil.copyfileobj(response, handle)
verify_file(temporary, str(spec["sha256"]))
temporary.replace(path)
paths[name] = path
return paths
def zip_member(archive: zipfile.ZipFile, suffix: str) -> str:
matches = [name for name in archive.namelist() if name.endswith(suffix)]
if len(matches) != 1:
raise ValueError(f"Expected one ZIP member ending in {suffix!r}, got {matches}")
return matches[0]
def dict_rows_from_zip(
archive_path: Path, member_suffix: str, *, delimiter: str = ","
) -> Iterator[dict[str, str]]:
with zipfile.ZipFile(archive_path) as archive:
member = zip_member(archive, member_suffix)
with archive.open(member) as raw:
with io.TextIOWrapper(raw, encoding="utf-8-sig", newline="") as text:
yield from csv.DictReader(text, delimiter=delimiter)
def record(
*,
text: str | None,
label_text: str,
fine_label: str,
language: str,
source: str,
source_id: str,
source_label: str,
original_split: str,
topic: str | None = None,
target: str | None = None,
) -> dict[str, object]:
if label_text not in LABEL_NAMES:
raise ValueError(f"Invalid normalized label: {label_text}")
return {
"text": text,
"label": LABEL_NAMES.index(label_text),
"label_text": label_text,
"fine_label": fine_label,
"language": language,
"source": source,
"source_id": source_id,
"source_label": source_label,
"original_split": original_split,
"topic": topic,
"target": target,
"text_available": text is not None and text != "",
}
def load_hindi(hindi_zip: Path) -> dict[str, list[dict[str, object]]]:
verify_file(hindi_zip, HINDI_SHA256)
fine_labels = {"NONE": "neutral", "OFFN": "offensive", "HATE": "hate", "PRFN": "profane"}
labels = {"NONE": "neutral", "OFFN": "offensive", "HATE": "hate", "PRFN": "offensive"}
targets = {"NONE": None, "TIN": "targeted", "UNT": "untargeted"}
members = {
"train": "hindi_dataset/hindi_dataset.tsv",
"test": "hindi_dataset/hasoc2019_hi_test_gold_2919.tsv",
}
splits: dict[str, list[dict[str, object]]] = {"train": [], "test": []}
for split, member in members.items():
for row in dict_rows_from_zip(hindi_zip, member, delimiter="\t"):
task_1 = row["task_1"]
label_text = labels[row["task_2"]]
splits[split].append(
record(
text=row["text"],
label_text=label_text,
fine_label=fine_labels[row["task_2"]],
language="hi",
source="hasoc2019_hi",
source_id=row["text_id"],
source_label=f"{task_1}|{row['task_2']}|{row['task_3']}",
original_split=split,
target=targets[row["task_3"]],
)
)
return splits
def deterministic_stratified_split(
rows: list[dict[str, object]],
*,
strata: tuple[str, ...],
test_fraction: float = 0.1,
) -> dict[str, list[dict[str, object]]]:
if not 0 < test_fraction < 1:
raise ValueError("test_fraction must be between zero and one")
groups: dict[tuple[object, ...], list[dict[str, object]]] = defaultdict(list)
for row in rows:
groups[tuple(row[field] for field in strata)].append(row)
test_keys: set[tuple[str, str]] = set()
for group_rows in groups.values():
ranked = sorted(
group_rows,
key=lambda row: hashlib.sha256(
f"{SPLIT_SEED}:{row['source']}:{row['source_id']}".encode()
).digest(),
)
test_size = max(1, round(len(ranked) * test_fraction))
test_keys.update(
(str(row["source"]), str(row["source_id"])) for row in ranked[:test_size]
)
splits: dict[str, list[dict[str, object]]] = {"train": [], "test": []}
for row in rows:
key = (str(row["source"]), str(row["source_id"]))
split = "test" if key in test_keys else "train"
row = dict(row)
row["original_split"] = "unsplit"
splits[split].append(row)
return splits
def normalized_tsv_rows(path: Path) -> tuple[list[dict[str, str]], int]:
"""Read the official TSV after repairing bare carriage returns in text."""
with path.open(encoding="utf-8-sig", newline="") as handle:
raw = handle.read()
crlf_count = raw.count("\r\n")
bare_cr_count = raw.count("\r") - crlf_count
normalized = raw.replace("\r\n", "\n").replace("\r", " ")
rows = list(csv.DictReader(io.StringIO(normalized, newline=""), delimiter="\t"))
return rows, bare_cr_count
def load_english_turkish(
tsv_path: Path,
) -> tuple[dict[str, list[dict[str, object]]], dict[str, object]]:
lang = {"0": "tr", "1": "en"}
topics = {"0": "religion", "1": "gender", "2": "race", "3": "politics", "4": "sports"}
labels = {"0": "neutral", "1": "offensive", "2": "hate"}
rows: list[dict[str, object]] = []
dropped_reasons: Counter[str] = Counter()
source_rows, normalized_bare_cr = normalized_tsv_rows(tsv_path)
seen_ids: set[str] = set()
required_columns = {"tweet_id", "topic", "language", "text", "label"}
for row in source_rows:
if not required_columns.issubset(row) or any(
row.get(column) is None for column in required_columns
):
dropped_reasons["malformed_columns"] += 1
continue
if not row["tweet_id"].isdigit():
dropped_reasons["invalid_tweet_id"] += 1
continue
if row["tweet_id"] in seen_ids:
dropped_reasons["duplicate_tweet_id"] += 1
continue
if row["language"] not in lang:
dropped_reasons["invalid_language"] += 1
continue
if row["topic"] not in topics:
dropped_reasons["invalid_topic"] += 1
continue
if row["label"] not in labels:
dropped_reasons["invalid_label"] += 1
continue
if not row["text"].strip():
dropped_reasons["empty_text"] += 1
continue
seen_ids.add(row["tweet_id"])
label_text = labels[row["label"]]
rows.append(
record(
text=row["text"],
label_text=label_text,
fine_label=label_text,
language=lang[row["language"]],
source="toraman2022_en_tr_v2",
source_id=row["tweet_id"],
source_label=row["label"],
original_split="unsplit",
topic=topics[row["topic"]],
)
)
quality_report = {
"source_rows": len(source_rows),
"retained_rows": len(rows),
"dropped_rows": sum(dropped_reasons.values()),
"dropped_reasons": dict(sorted(dropped_reasons.items())),
"normalized_bare_carriage_returns": normalized_bare_cr,
}
splits = deterministic_stratified_split(
rows, strata=("language", "topic", "fine_label"), test_fraction=0.1
)
return splits, quality_report
def load_chinese(archive_path: Path) -> dict[str, list[dict[str, object]]]:
splits: dict[str, list[dict[str, object]]] = {"train": [], "test": []}
fine_test = {"0": "neutral", "1": "offensive", "2": "offensive", "3": "neutral"}
target_test = {"0": None, "1": "individual", "2": "group", "3": None}
for upstream_split in ("train", "dev", "test"):
output_split = "test" if upstream_split == "test" else "train"
for index, row in enumerate(
dict_rows_from_zip(archive_path, f"COLDataset/{upstream_split}.csv")
):
source_binary = row["label"]
source_fine = row.get("fine-grained-label")
if source_fine is None:
fine_label = "neutral" if source_binary == "0" else "offensive"
target = None
source_label = source_binary
else:
fine_label = fine_test[source_fine]
target = target_test[source_fine]
source_label = f"{source_binary}|{source_fine}"
splits[output_split].append(
record(
text=row["TEXT"],
label_text="neutral" if source_binary == "0" else "offensive",
fine_label=fine_label,
language="zh",
source="cold_zh",
# The unnamed CSV column is a non-unique dataframe index,
# so use a stable split/row identifier instead.
source_id=f"{upstream_split}:{index:05d}",
source_label=source_label,
original_split=upstream_split,
topic=row["topic"],
target=target,
)
)
return splits
def load_amharic(paths: dict[str, Path]) -> dict[str, list[dict[str, object]]]:
splits: dict[str, list[dict[str, object]]] = {"train": [], "test": []}
for upstream_split in ("train", "dev", "test"):
output_split = "test" if upstream_split == "test" else "train"
with paths[f"am_{upstream_split}"].open(encoding="utf-8", newline="") as handle:
for index, row in enumerate(csv.reader(handle, delimiter="\t")):
if len(row) != 2:
raise ValueError(
f"Expected two Amharic TSV columns in {upstream_split} row {index}, got {len(row)}"
)
source_fine_label, text = row
label_text = (
"neutral" if source_fine_label == "normal" else source_fine_label
)
splits[output_split].append(
record(
text=text,
label_text=label_text,
fine_label=label_text,
language="am",
source="amharic_ranlp2023",
source_id=f"{upstream_split}:{index:05d}",
source_label=source_fine_label,
original_split=upstream_split,
)
)
return splits
def merge_sources(
sources: Iterable[dict[str, list[dict[str, object]]]],
) -> dict[str, list[dict[str, object]]]:
merged: dict[str, list[dict[str, object]]] = {"train": [], "test": []}
for source in sources:
for split in merged:
merged[split].extend(source[split])
return merged
def remove_cross_split_text_leakage(
splits: dict[str, list[dict[str, object]]],
) -> tuple[dict[str, list[dict[str, object]]], dict[str, object]]:
"""Remove train rows whose exact source/text pair occurs in test.
Test rows are authoritative. The `text_available` guard keeps this routine
safe if a future source introduces metadata-only rows.
"""
raw_language_counts = Counter(
str(row["language"]) for rows in splits.values() for row in rows
)
if dict(sorted(raw_language_counts.items())) != RAW_LANGUAGE_COUNTS:
raise ValueError(
f"Unexpected raw language counts: {dict(sorted(raw_language_counts.items()))}"
)
test_by_key: dict[tuple[str, str], list[dict[str, object]]] = defaultdict(list)
for row in splits["test"]:
if row["text_available"]:
test_by_key[(str(row["source"]), str(row["text"]))].append(row)
kept_train: list[dict[str, object]] = []
removed: list[dict[str, object]] = []
conflicting_labels = 0
for row in splits["train"]:
key = (str(row["source"]), str(row["text"]))
matching_test_rows = test_by_key.get(key, []) if row["text_available"] else []
if matching_test_rows:
removed.append(row)
if any(test_row["label"] != row["label"] for test_row in matching_test_rows):
conflicting_labels += 1
else:
kept_train.append(row)
cleaned = {"train": kept_train, "test": splits["test"]}
report = {
"policy": "remove train rows with exact source/text match in test",
"removed_train_rows": len(removed),
"removed_rows_with_label_conflict": conflicting_labels,
"removed_by_source": dict(
sorted(Counter(str(row["source"]) for row in removed).items())
),
"removed_by_language": dict(
sorted(Counter(str(row["language"]) for row in removed).items())
),
}
return cleaned, report
def validate_records(
splits: dict[str, list[dict[str, object]]],
leakage_report: dict[str, object] | None = None,
) -> dict[str, object]:
if set(splits) != {"train", "test"}:
raise ValueError(f"Expected train/test splits, got {sorted(splits)}")
language_counts: Counter[str] = Counter()
ids_by_split: dict[str, set[tuple[str, str]]] = {}
duplicate_texts: dict[str, int] = {}
for split, rows in splits.items():
ids = [(str(row["source"]), str(row["source_id"])) for row in rows]
if len(ids) != len(set(ids)):
raise ValueError(f"Duplicate source/source_id pairs within {split}")
ids_by_split[split] = set(ids)
texts = [str(row["text"]) for row in rows if row["text_available"]]
duplicate_texts[split] = len(texts) - len(set(texts))
for row in rows:
language_counts[str(row["language"])] += 1
if bool(row["text_available"]) != (
row["text"] is not None and row["text"] != ""
):
raise ValueError("text_available disagrees with text")
expected_label = LABEL_NAMES.index(str(row["label_text"]))
if row["label"] != expected_label:
raise ValueError("label disagrees with label_text")
overlap = ids_by_split["train"] & ids_by_split["test"]
if overlap:
raise ValueError(f"{len(overlap)} source IDs occur in both train and test")
train_texts = {
(str(row["source"]), str(row["text"]))
for row in splits["train"]
if row["text_available"]
}
test_texts = {
(str(row["source"]), str(row["text"]))
for row in splits["test"]
if row["text_available"]
}
text_overlap = train_texts & test_texts
if text_overlap:
raise ValueError(f"{len(text_overlap)} exact texts occur in both train and test")
if dict(sorted(language_counts.items())) != EXPECTED_LANGUAGE_COUNTS:
raise ValueError(
f"Unexpected language counts: {dict(sorted(language_counts.items()))}"
)
all_rows = splits["train"] + splits["test"]
return {
"build_version": BUILD_VERSION,
"split_seed": SPLIT_SEED,
"num_rows": len(all_rows),
"num_text_rows": sum(bool(row["text_available"]) for row in all_rows),
"num_metadata_only_rows": sum(not bool(row["text_available"]) for row in all_rows),
"split_counts": {split: len(rows) for split, rows in splits.items()},
"language_counts": dict(sorted(language_counts.items())),
"split_language_counts": {
split: dict(sorted(Counter(str(row["language"]) for row in rows).items()))
for split, rows in splits.items()
},
"label_counts": dict(
sorted(Counter(str(row["label_text"]) for row in all_rows).items())
),
"source_counts": dict(
sorted(Counter(str(row["source"]) for row in all_rows).items())
),
"cross_split_text_leakage": leakage_report,
"within_split_duplicate_text_counts": duplicate_texts,
}
def to_dataset_dict(splits: dict[str, list[dict[str, object]]]) -> DatasetDict:
return DatasetDict(
{
split: Dataset.from_list(rows, features=FEATURES)
for split, rows in splits.items()
}
)
def write_outputs(
dataset: DatasetDict,
summary: dict[str, object],
output_dir: Path,
) -> None:
data_dir = output_dir / "data"
metadata_dir = output_dir / "metadata"
local_dir = output_dir / "local_dataset"
data_dir.mkdir(parents=True, exist_ok=True)
metadata_dir.mkdir(parents=True, exist_ok=True)
local_dir.mkdir(parents=True, exist_ok=True)
for split, split_dataset in dataset.items():
split_dataset.to_parquet(data_dir / f"{split}-00000-of-00001.parquet")
dataset.save_to_disk(local_dir)
(metadata_dir / "build_summary.json").write_text(
json.dumps(summary, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--hindi-zip",
type=Path,
default=WORKSPACE_ROOT / "hindi_dataset.zip",
help="Path to the registered-access HASOC 2019 Hindi archive.",
)
parser.add_argument(
"--cache-dir",
type=Path,
default=REPO_ROOT / ".cache" / "sources",
help="Download cache for pinned public sources.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=REPO_ROOT,
help="Repository/output directory.",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
source_paths = download_sources(args.cache_dir)
english_turkish, english_turkish_quality = load_english_turkish(
source_paths["toraman_en_tr"]
)
splits = merge_sources(
[
load_hindi(args.hindi_zip),
english_turkish,
load_chinese(source_paths["cold_zh"]),
load_amharic(source_paths),
]
)
splits, leakage_report = remove_cross_split_text_leakage(splits)
summary = validate_records(splits, leakage_report)
summary["source_quality"] = {
"toraman2022_en_tr_v2": english_turkish_quality,
}
dataset = to_dataset_dict(splits)
write_outputs(dataset, summary, args.output_dir)
print(json.dumps(summary, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()