Spaces:
Running
Running
Download utils_data.py from cq111sto/h1-diving-tuning: direct link, hf CLI and curl.
- Browser
- Download file 4.52 kB
-
https://huggingface.co/spaces/cq111sto/h1-diving-tuning/resolve/main/utils_data.py
- Command line
-
hf download hf://spaces/cq111sto/h1-diving-tuning/utils_data.py
-
curl -L -o utils_data.py https://huggingface.co/spaces/cq111sto/h1-diving-tuning/resolve/main/utils_data.py
4.52 kB
| """Download pinned source data, remove ambiguous/duplicate texts, split, tokenize.""" | |
| import hashlib | |
| import json | |
| import re | |
| from pathlib import Path | |
| import pandas as pd | |
| import requests | |
| import torch | |
| from sklearn.model_selection import train_test_split | |
| DATA_REPO = "VuduVations/disaster_tweets" | |
| DATA_REVISION = "4e6d821b0157aa382d287b15fb1681415ea3a512" | |
| def download_file(url, path): | |
| if path.exists(): | |
| return | |
| response = requests.get(url, timeout=120) | |
| response.raise_for_status() | |
| path.write_bytes(response.content) | |
| def text_key(text): | |
| return re.sub(r"\s+", " ", str(text)).strip().casefold() | |
| def prepare_data(data_dir="data", seed=42): | |
| root = Path(data_dir) | |
| root.mkdir(parents=True, exist_ok=True) | |
| sources, labeled, unlabeled = [], [], [] | |
| for split in ("train", "validation", "test"): | |
| path = root / f"source_{split}.csv" | |
| url = f"https://huggingface.co/datasets/{DATA_REPO}/resolve/{DATA_REVISION}/data/{split}.csv" | |
| download_file(url, path) | |
| frame = pd.read_csv(path) | |
| if "text" not in frame: | |
| raise ValueError(f"Missing text column in {path}") | |
| sources.append( | |
| { | |
| "url": url, | |
| "rows": len(frame), | |
| "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), | |
| } | |
| ) | |
| frame["source_split"] = split | |
| if "target" in frame and frame.target.notna().all(): | |
| labeled.append(frame) | |
| else: | |
| unlabeled.append(frame) | |
| frame = pd.concat(labeled, ignore_index=True) | |
| original_rows = len(frame) | |
| frame = frame.dropna(subset=["text", "target"]).copy() | |
| frame = frame[frame.text.str.strip().ne("")] | |
| frame["target"] = frame.target.astype(int) | |
| if set(frame.target.unique()) != {0, 1}: | |
| raise ValueError("Expected binary targets 0 and 1") | |
| frame["text_key"] = frame.text.map(text_key) | |
| counts = frame.groupby("text_key").target.nunique() | |
| conflicting = set(counts[counts > 1].index) | |
| conflict_rows = int(frame.text_key.isin(conflicting).sum()) | |
| frame = frame[~frame.text_key.isin(conflicting)] | |
| before_dedup = len(frame) | |
| frame = frame.drop_duplicates("text_key").reset_index(drop=True) | |
| train, holdout = train_test_split( | |
| frame, test_size=0.2, stratify=frame.target, random_state=seed | |
| ) | |
| val, test = train_test_split( | |
| holdout, test_size=0.5, stratify=holdout.target, random_state=seed | |
| ) | |
| splits = {"train": train, "val": val, "test": test} | |
| key_sets = [set(part.text_key) for part in splits.values()] | |
| assert not ( | |
| key_sets[0] & key_sets[1] | |
| or key_sets[0] & key_sets[2] | |
| or key_sets[1] & key_sets[2] | |
| ) | |
| for name, part in splits.items(): | |
| part.drop(columns="text_key").to_csv(root / f"{name}.csv", index=False) | |
| manifest = { | |
| "dataset": DATA_REPO, | |
| "revision": DATA_REVISION, | |
| "sources": sources, | |
| "original_labeled_rows": original_rows, | |
| "conflicting_text_groups": len(conflicting), | |
| "removed_conflicting_rows": conflict_rows, | |
| "removed_duplicate_rows": before_dedup - len(frame), | |
| "clean_rows": len(frame), | |
| "seed": seed, | |
| "split_policy": "stratified 80/10/10, after global text deduplication", | |
| "splits": { | |
| k: { | |
| "rows": len(v), | |
| "class_counts": v.target.value_counts().sort_index().to_dict(), | |
| } | |
| for k, v in splits.items() | |
| }, | |
| "split_text_overlap": 0, | |
| } | |
| (root / "manifest.json").write_text( | |
| json.dumps(manifest, indent=2), encoding="utf-8" | |
| ) | |
| return ( | |
| splits, | |
| pd.concat(unlabeled, ignore_index=True) if unlabeled else None, | |
| manifest, | |
| ) | |
| class TweetDataset(torch.utils.data.Dataset): | |
| def __init__(self, frame, tokenizer, max_length=128): | |
| self.encoding = tokenizer( | |
| frame.text.tolist(), | |
| truncation=True, | |
| padding="max_length", | |
| max_length=max_length, | |
| return_tensors="pt", | |
| ) | |
| self.labels = ( | |
| torch.tensor(frame.target.to_numpy(), dtype=torch.long) | |
| if "target" in frame | |
| else None | |
| ) | |
| def __len__(self): | |
| return len(self.encoding["input_ids"]) | |
| def __getitem__(self, index): | |
| item = {k: v[index] for k, v in self.encoding.items()} | |
| if self.labels is not None: | |
| item["labels"] = self.labels[index] | |
| return item | |