Spaces:
Running
Running
Delete data_loader.py
Browse files- data_loader.py +0 -205
data_loader.py
DELETED
|
@@ -1,205 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
AIFinder Data Loader
|
| 3 |
-
Downloads and parses HuggingFace datasets, extracts assistant responses,
|
| 4 |
-
and labels them with is_ai, provider, and model.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import re
|
| 8 |
-
import time
|
| 9 |
-
from datasets import load_dataset
|
| 10 |
-
from tqdm import tqdm
|
| 11 |
-
|
| 12 |
-
from config import (
|
| 13 |
-
DATASET_REGISTRY,
|
| 14 |
-
DEEPSEEK_AM_DATASETS,
|
| 15 |
-
)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def _parse_msg(msg):
|
| 19 |
-
"""Parse a message that may be a dict or a JSON string."""
|
| 20 |
-
if isinstance(msg, dict):
|
| 21 |
-
return msg
|
| 22 |
-
if isinstance(msg, str):
|
| 23 |
-
try:
|
| 24 |
-
import json
|
| 25 |
-
|
| 26 |
-
parsed = json.loads(msg)
|
| 27 |
-
if isinstance(parsed, dict):
|
| 28 |
-
return parsed
|
| 29 |
-
except (json.JSONDecodeError, ValueError):
|
| 30 |
-
pass
|
| 31 |
-
return {}
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _extract_assistant_texts_from_conversations(rows):
|
| 35 |
-
"""Extract assistant message content from conversation datasets.
|
| 36 |
-
These have a 'conversations' or 'messages' column with list of
|
| 37 |
-
{role, content} dicts (or JSON strings encoding such dicts).
|
| 38 |
-
"""
|
| 39 |
-
texts = []
|
| 40 |
-
for row in rows:
|
| 41 |
-
convos = row.get("conversations")
|
| 42 |
-
if convos is None or (hasattr(convos, "__len__") and len(convos) == 0):
|
| 43 |
-
convos = row.get("messages")
|
| 44 |
-
if convos is None or (hasattr(convos, "__len__") and len(convos) == 0):
|
| 45 |
-
convos = []
|
| 46 |
-
parts = []
|
| 47 |
-
for msg in convos:
|
| 48 |
-
msg = _parse_msg(msg)
|
| 49 |
-
role = msg.get("role", "")
|
| 50 |
-
content = msg.get("content", "")
|
| 51 |
-
if role in ("assistant", "gpt", "model") and content:
|
| 52 |
-
parts.append(content)
|
| 53 |
-
if parts:
|
| 54 |
-
texts.append("\n\n".join(parts))
|
| 55 |
-
return texts
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def _extract_from_am_dataset(row):
|
| 59 |
-
"""Extract assistant text from a-m-team format (messages list with role/content)."""
|
| 60 |
-
messages = row.get("messages") or row.get("conversations") or []
|
| 61 |
-
parts = []
|
| 62 |
-
for msg in messages:
|
| 63 |
-
role = msg.get("role", "") if isinstance(msg, dict) else ""
|
| 64 |
-
content = msg.get("content", "") if isinstance(msg, dict) else ""
|
| 65 |
-
if role == "assistant" and content:
|
| 66 |
-
parts.append(content)
|
| 67 |
-
return "\n\n".join(parts) if parts else ""
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def load_teichai_dataset(dataset_id, provider, model_name, kwargs):
|
| 71 |
-
"""Load a single conversation-format dataset and return (texts, providers, models)."""
|
| 72 |
-
max_samples = kwargs.get("max_samples")
|
| 73 |
-
load_kwargs = {}
|
| 74 |
-
if "name" in kwargs:
|
| 75 |
-
load_kwargs["name"] = kwargs["name"]
|
| 76 |
-
|
| 77 |
-
try:
|
| 78 |
-
ds = load_dataset(dataset_id, split="train", **load_kwargs)
|
| 79 |
-
rows = list(ds)
|
| 80 |
-
except Exception as e:
|
| 81 |
-
# Fallback: load from auto-converted parquet via HF API
|
| 82 |
-
try:
|
| 83 |
-
import pandas as pd
|
| 84 |
-
|
| 85 |
-
url = f"https://huggingface.co/api/datasets/{dataset_id}/parquet/default/train/0.parquet"
|
| 86 |
-
df = pd.read_parquet(url)
|
| 87 |
-
rows = df.to_dict(orient="records")
|
| 88 |
-
except Exception as e2:
|
| 89 |
-
print(f" [SKIP] {dataset_id}: {e} / parquet fallback: {e2}")
|
| 90 |
-
return [], [], []
|
| 91 |
-
|
| 92 |
-
if max_samples and len(rows) > max_samples:
|
| 93 |
-
import random
|
| 94 |
-
|
| 95 |
-
random.seed(42)
|
| 96 |
-
rows = random.sample(rows, max_samples)
|
| 97 |
-
|
| 98 |
-
texts = _extract_assistant_texts_from_conversations(rows)
|
| 99 |
-
|
| 100 |
-
# Filter out empty/too-short texts
|
| 101 |
-
filtered = [(t, provider, model_name) for t in texts if len(t) > 50]
|
| 102 |
-
if not filtered:
|
| 103 |
-
print(f" [SKIP] {dataset_id}: no valid texts extracted")
|
| 104 |
-
return [], [], []
|
| 105 |
-
|
| 106 |
-
t, p, m = zip(*filtered)
|
| 107 |
-
return list(t), list(p), list(m)
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def load_am_deepseek_dataset(dataset_id, provider, model_name, kwargs):
|
| 111 |
-
"""Load a-m-team DeepSeek dataset."""
|
| 112 |
-
max_samples = kwargs.get("max_samples")
|
| 113 |
-
load_kwargs = {}
|
| 114 |
-
if "name" in kwargs:
|
| 115 |
-
load_kwargs["name"] = kwargs["name"]
|
| 116 |
-
|
| 117 |
-
try:
|
| 118 |
-
ds = load_dataset(dataset_id, split="train", **load_kwargs)
|
| 119 |
-
except Exception as e1:
|
| 120 |
-
# Try without name kwarg as fallback
|
| 121 |
-
try:
|
| 122 |
-
ds = load_dataset(dataset_id, split="train", streaming=True)
|
| 123 |
-
rows = []
|
| 124 |
-
for row in ds:
|
| 125 |
-
rows.append(row)
|
| 126 |
-
if max_samples and len(rows) >= max_samples:
|
| 127 |
-
break
|
| 128 |
-
except Exception as e2:
|
| 129 |
-
print(f" [SKIP] {dataset_id}: {e2}")
|
| 130 |
-
return [], [], []
|
| 131 |
-
else:
|
| 132 |
-
rows = list(ds)
|
| 133 |
-
if max_samples and len(rows) > max_samples:
|
| 134 |
-
rows = rows[:max_samples]
|
| 135 |
-
|
| 136 |
-
texts = []
|
| 137 |
-
for row in rows:
|
| 138 |
-
text = _extract_from_am_dataset(row)
|
| 139 |
-
if len(text) > 50:
|
| 140 |
-
texts.append(text)
|
| 141 |
-
|
| 142 |
-
providers = [provider] * len(texts)
|
| 143 |
-
models = [model_name] * len(texts)
|
| 144 |
-
return texts, providers, models
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
def load_all_data():
|
| 148 |
-
"""Load all datasets and return combined lists.
|
| 149 |
-
|
| 150 |
-
Returns:
|
| 151 |
-
texts: list of str
|
| 152 |
-
providers: list of str
|
| 153 |
-
models: list of str
|
| 154 |
-
is_ai: list of int (1=AI, 0=Human)
|
| 155 |
-
"""
|
| 156 |
-
all_texts = []
|
| 157 |
-
all_providers = []
|
| 158 |
-
all_models = []
|
| 159 |
-
|
| 160 |
-
# TeichAI datasets
|
| 161 |
-
print("Loading TeichAI datasets...")
|
| 162 |
-
for dataset_id, provider, model_name, kwargs in tqdm(
|
| 163 |
-
DATASET_REGISTRY, desc="TeichAI"
|
| 164 |
-
):
|
| 165 |
-
t0 = time.time()
|
| 166 |
-
texts, providers, models = load_teichai_dataset(
|
| 167 |
-
dataset_id, provider, model_name, kwargs
|
| 168 |
-
)
|
| 169 |
-
elapsed = time.time() - t0
|
| 170 |
-
all_texts.extend(texts)
|
| 171 |
-
all_providers.extend(providers)
|
| 172 |
-
all_models.extend(models)
|
| 173 |
-
print(f" {dataset_id}: {len(texts)} samples ({elapsed:.1f}s)")
|
| 174 |
-
|
| 175 |
-
# DeepSeek a-m-team datasets
|
| 176 |
-
print("\nLoading DeepSeek (a-m-team) datasets...")
|
| 177 |
-
for dataset_id, provider, model_name, kwargs in tqdm(
|
| 178 |
-
DEEPSEEK_AM_DATASETS, desc="DeepSeek-AM"
|
| 179 |
-
):
|
| 180 |
-
t0 = time.time()
|
| 181 |
-
texts, providers, models = load_am_deepseek_dataset(
|
| 182 |
-
dataset_id, provider, model_name, kwargs
|
| 183 |
-
)
|
| 184 |
-
elapsed = time.time() - t0
|
| 185 |
-
all_texts.extend(texts)
|
| 186 |
-
all_providers.extend(providers)
|
| 187 |
-
all_models.extend(models)
|
| 188 |
-
print(f" {dataset_id}: {len(texts)} samples ({elapsed:.1f}s)")
|
| 189 |
-
|
| 190 |
-
# Build is_ai labels (all AI)
|
| 191 |
-
is_ai = [1] * len(all_texts)
|
| 192 |
-
|
| 193 |
-
print(f"\n=== Total: {len(all_texts)} samples ===")
|
| 194 |
-
# Print per-provider counts
|
| 195 |
-
from collections import Counter
|
| 196 |
-
|
| 197 |
-
prov_counts = Counter(all_providers)
|
| 198 |
-
for p, c in sorted(prov_counts.items(), key=lambda x: -x[1]):
|
| 199 |
-
print(f" {p}: {c}")
|
| 200 |
-
|
| 201 |
-
return all_texts, all_providers, all_models, is_ai
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
if __name__ == "__main__":
|
| 205 |
-
texts, providers, models, is_ai = load_all_data()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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