Spaces:
Running

File size: 4,519 Bytes
e11cd36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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