File size: 5,436 Bytes
7f9dfed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import csv
import json
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
from typing import Any


@dataclass(frozen=True)
class DatasetPreview:
    """Small local dataset preview result."""

    source: str
    rows: int
    columns: list[str]
    samples: list[dict[str, Any]]

    def as_table(self) -> list[list[str]]:
        table = [
            ["source", self.source],
            ["rows", str(self.rows)],
            ["columns", ", ".join(self.columns)],
        ]
        for index, sample in enumerate(self.samples, start=1):
            table.append([f"sample_{index}", json.dumps(sample, ensure_ascii=False)])
        return table


@dataclass(frozen=True)
class DatasetStats:
    """Basic dataset statistics for local preview and tools."""

    source: str
    rows: int
    columns: int
    column_names: list[str]
    non_empty_by_column: dict[str, int]

    def as_dict(self) -> dict[str, Any]:
        return {
            "source": self.source,
            "rows": self.rows,
            "columns": self.columns,
            "column_names": self.column_names,
            "non_empty_by_column": self.non_empty_by_column,
        }


@dataclass(frozen=True)
class HuggingFaceDatasetPreview:
    """Small preview result for optional Hugging Face datasets integration."""

    dataset_id: str
    split: str
    rows: int
    columns: list[str]
    samples: list[dict[str, Any]]
    status: str = "loaded"

    def as_table(self) -> list[list[str]]:
        table = [
            ["dataset_id", self.dataset_id],
            ["split", self.split],
            ["rows", str(self.rows)],
            ["columns", ", ".join(self.columns)],
            ["status", self.status],
        ]
        for index, sample in enumerate(self.samples, start=1):
            table.append([f"sample_{index}", json.dumps(sample, ensure_ascii=False)])
        return table


def preview_local_dataset(path: str | Path, limit: int = 5) -> DatasetPreview:
    dataset_path = Path(path)
    if not dataset_path.exists():
        raise FileNotFoundError(f"Dataset path not found: {dataset_path}")
    if dataset_path.suffix.lower() == ".csv":
        return _preview_csv(dataset_path, limit)
    if dataset_path.suffix.lower() in {".jsonl", ".ndjson"}:
        return _preview_jsonl(dataset_path, limit)
    raise ValueError(f"Unsupported dataset format: {dataset_path.suffix}")


def dataset_statistics(path: str | Path) -> DatasetStats:
    preview = preview_local_dataset(path, limit=0)
    non_empty_by_column = {column: 0 for column in preview.columns}

    dataset_path = Path(path)
    if dataset_path.suffix.lower() == ".csv":
        with dataset_path.open(newline="", encoding="utf-8") as f:
            for row in csv.DictReader(f):
                for column in preview.columns:
                    if str(row.get(column, "")).strip():
                        non_empty_by_column[column] += 1
    else:
        with dataset_path.open(encoding="utf-8") as f:
            for line in f:
                if not line.strip():
                    continue
                row = json.loads(line)
                for column in preview.columns:
                    if str(row.get(column, "")).strip():
                        non_empty_by_column[column] += 1

    return DatasetStats(
        source=preview.source,
        rows=preview.rows,
        columns=len(preview.columns),
        column_names=preview.columns,
        non_empty_by_column=non_empty_by_column,
    )


def preview_huggingface_dataset(
    dataset_id: str,
    split: str = "train",
    limit: int = 5,
) -> HuggingFaceDatasetPreview:
    datasets_module = import_module("datasets")
    load_dataset = getattr(datasets_module, "load_dataset", None)
    if load_dataset is None:
        return HuggingFaceDatasetPreview(
            dataset_id=dataset_id,
            split=split,
            rows=0,
            columns=[],
            samples=[],
            status="Hugging Face package 'datasets' is not installed.",
        )

    dataset = load_dataset(dataset_id, split=split)
    rows = len(dataset)
    columns = list(dataset.column_names)
    samples = [dict(dataset[index]) for index in range(min(limit, rows))]
    return HuggingFaceDatasetPreview(dataset_id, split, rows, columns, samples)


def _preview_csv(path: Path, limit: int) -> DatasetPreview:
    samples: list[dict[str, Any]] = []
    rows = 0
    columns: list[str] = []

    with path.open(newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        columns = list(reader.fieldnames or [])
        for row in reader:
            rows += 1
            if len(samples) < limit:
                samples.append(dict(row))

    return DatasetPreview(str(path), rows, columns, samples)


def _preview_jsonl(path: Path, limit: int) -> DatasetPreview:
    samples: list[dict[str, Any]] = []
    rows = 0
    columns: set[str] = set()

    with path.open(encoding="utf-8") as f:
        for line in f:
            if not line.strip():
                continue
            rows += 1
            item = json.loads(line)
            if not isinstance(item, dict):
                raise ValueError("JSONL rows must be objects")
            columns.update(item)
            if len(samples) < limit:
                samples.append(item)

    return DatasetPreview(str(path), rows, sorted(columns), samples)