nonarjb commited on
Commit
7955a8e
·
verified ·
1 Parent(s): 3e1fe94

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +326 -6
README.md CHANGED
@@ -1,9 +1,329 @@
1
- This repo contains WebDataset shards split by top-level subfolders (e.g., `images`, `preprocessed_eeg`).
2
- Each shard preserves the internal hierarchy in WebDataset `__key__`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- ## Load example (streaming)
5
  ```python
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  import webdataset as wds
7
- base = "https://huggingface.co/datasets/nonarjb/things_eeg_2/resolve/main"
8
- urls = f"{base}/things_eeg_2-images-{{000000..000099}}.tar"
9
- ds = wds.WebDataset(urls).to_tuple("__key__", "jpg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # README Loading `things_eeg_2` from `nonarjb/alignvis`
2
+
3
+ This repo hosts WebDataset shard sets under `things_eeg_2/`:
4
+
5
+ * `things_eeg_2-images-*.tar` — images
6
+ * `things_eeg_2-image_embeddings-*.tar` — vector embeddings (`.npy/.npz`)
7
+ * `things_eeg_2-preprocessed_eeg-*.tar` — EEG arrays (`.npy/.npz`)
8
+
9
+ Inside each shard, the WebDataset `__key__` is the file’s **relative path under the top folder (without extension)**.
10
+ To reconstruct the original relative path, use:
11
+
12
+ ```
13
+ rel_path = "<top>/" + __key__ + "." + <ext>
14
+ ```
15
+
16
+ (e.g., `images/training_images/01133_raincoat/raincoat_01s.jpg`)
17
+
18
+ > To use the **other dataset** (`things_meg`), just replace `dataset_dir="things_eeg_2"` with `dataset_dir="things_meg"` in the examples below.
19
+
20
+ ---
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install webdataset huggingface_hub pillow torch tqdm
26
+ # Optional: faster transfers for big files
27
+ pip install -U hf_transfer && export HF_HUB_ENABLE_HF_TRANSFER=1
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Helper: list shard URLs from the Hub
33
+
34
+ Create `utils_hf_wds.py`:
35
 
 
36
  ```python
37
+ # utils_hf_wds.py
38
+ from huggingface_hub import HfFileSystem, hf_hub_url
39
+
40
+ def hf_tar_urls(repo_id: str, dataset_dir: str, top: str, revision: str = "main"):
41
+ """
42
+ Return sorted 'resolve/<revision>' URLs for shards matching:
43
+ <dataset_dir>/<dataset_dir>-<top>-*.tar
44
+ Example: things_eeg_2/things_eeg_2-images-000000.tar
45
+ """
46
+ fs = HfFileSystem()
47
+ pattern = f"datasets/{repo_id}/{dataset_dir}/{dataset_dir}-{top}-*.tar"
48
+ hf_paths = sorted(fs.glob(pattern)) # hf://datasets/<repo_id>/...
49
+ rel_paths = [p.split(f"datasets/{repo_id}/", 1)[1] for p in hf_paths]
50
+ return [
51
+ hf_hub_url(repo_id, filename=p, repo_type="dataset", revision=revision)
52
+ for p in rel_paths
53
+ ]
54
+ ```
55
+
56
+ ---
57
+
58
+ ## A) Images (PIL) with original relative paths
59
+
60
+ ```python
61
+ import io
62
+ from PIL import Image
63
+ import torch, webdataset as wds
64
+ from utils_hf_wds import hf_tar_urls
65
+
66
+ REPO = "nonarjb/alignvis"
67
+
68
+ def make_images_loader(dataset_dir="things_eeg_2", batch_size=16, num_workers=4):
69
+ urls = hf_tar_urls(REPO, dataset_dir, top="images")
70
+ if not urls: raise RuntimeError("No image shards found")
71
+
72
+ def pick_image(s):
73
+ for ext in ("jpg","jpeg","png"):
74
+ if ext in s:
75
+ s["img_bytes"] = s[ext]
76
+ s["rel_path"] = f"images/{s['__key__']}.{ext}"
77
+ return s
78
+ return None
79
+
80
+ ds = (wds.WebDataset(urls, shardshuffle=False, handler=wds.handlers.warn_and_continue)
81
+ .map(pick_image).select(lambda s: s is not None)
82
+ .map(lambda s: (s["rel_path"], Image.open(io.BytesIO(s["img_bytes"])).convert("RGB"))))
83
+
84
+ return torch.utils.data.DataLoader(
85
+ ds, batch_size=batch_size, num_workers=num_workers, collate_fn=lambda b: b
86
+ )
87
+
88
+ loader = make_images_loader()
89
+ rel_path, pil_img = next(iter(loader))[0]
90
+ print(rel_path, pil_img.size) # e.g. images/training_images/.../raincoat_01s.jpg (W, H)
91
+ ```
92
+
93
+ ---
94
+
95
+ ## B) Image embeddings (`.npy/.npz`) → `torch.Tensor`
96
+
97
+ ```python
98
+ import io, numpy as np
99
+ import torch, webdataset as wds
100
+ from utils_hf_wds import hf_tar_urls
101
+
102
+ REPO = "nonarjb/alignvis"
103
+
104
+ # Heuristics for dict-like payloads
105
+ CANDIDATE_KEYS = ("embedding", "emb", "vector", "feat", "features", "clip", "image", "text")
106
+
107
+ def _first_numeric_from_npz(npz, prefer_key=None):
108
+ if prefer_key and prefer_key in npz:
109
+ return np.asarray(npz[prefer_key])
110
+ # try direct numeric arrays
111
+ for k in npz.files:
112
+ a = npz[k]
113
+ if isinstance(a, np.ndarray) and np.issubdtype(a.dtype, np.number):
114
+ return a
115
+ # try dict-like entries with known keys
116
+ for k in npz.files:
117
+ a = npz[k]
118
+ if isinstance(a, dict):
119
+ for ck in CANDIDATE_KEYS:
120
+ if ck in a:
121
+ return np.asarray(a[ck])
122
+ return None
123
+
124
+ def _load_numeric_vector(payload: bytes, ext: str, prefer_key: str | None = None):
125
+ """Return 1D float32 vector or None if not numeric."""
126
+ bio = io.BytesIO(payload)
127
+ try:
128
+ arr = np.load(bio, allow_pickle=False)
129
+ except ValueError as e:
130
+ if "Object arrays" in str(e):
131
+ bio.seek(0)
132
+ obj = np.load(bio, allow_pickle=True)
133
+ if isinstance(obj, dict):
134
+ for ck in CANDIDATE_KEYS:
135
+ if ck in obj:
136
+ arr = obj[ck]; break
137
+ else:
138
+ return None
139
+ elif isinstance(obj, (list, tuple)):
140
+ arr = np.asarray(obj)
141
+ else:
142
+ return None
143
+ else:
144
+ raise
145
+ arr = np.asarray(arr)
146
+ if not np.issubdtype(arr.dtype, np.number):
147
+ try:
148
+ arr = arr.astype(np.float32)
149
+ except Exception:
150
+ return None
151
+ return arr.reshape(-1).astype(np.float32)
152
+
153
+ def make_embeddings_loader(
154
+ dataset_dir="things_eeg_2",
155
+ batch_size=64,
156
+ num_workers=4,
157
+ prefer_key: str | None = None, # e.g., "embedding" if you know the field name
158
+ ):
159
+ urls = hf_tar_urls(REPO, dataset_dir, top="image_embeddings")
160
+ if not urls:
161
+ raise RuntimeError("No embedding shards found")
162
+
163
+ def pick_payload(s):
164
+ for ext in ("npy", "npz"):
165
+ if ext in s:
166
+ s["__ext__"] = ext
167
+ s["payload"] = s[ext]
168
+ s["rel_path"] = f"image_embeddings/{s['__key__']}.{ext}"
169
+ return s
170
+ return None
171
+
172
+ def decode_vec(s):
173
+ vec = _load_numeric_vector(s["payload"], s["__ext__"], prefer_key=prefer_key)
174
+ if vec is None:
175
+ # skip non-numeric payloads
176
+ return None
177
+ return (s["rel_path"], torch.from_numpy(vec))
178
+
179
+ ds = (
180
+ wds.WebDataset(urls, shardshuffle=False, handler=wds.handlers.warn_and_continue)
181
+ .map(pick_payload).select(lambda s: s is not None)
182
+ .map(decode_vec).select(lambda x: x is not None)
183
+ )
184
+
185
+ # Collate into a batch tensor; all vectors must have same dim
186
+ def collate(batch):
187
+ paths, vecs = zip(*batch)
188
+ D = vecs[0].numel()
189
+ vecs = [v.view(-1) for v in vecs if v.numel() == D]
190
+ paths = [p for (p, v) in batch if v.numel() == D]
191
+ return list(paths), torch.stack(vecs, dim=0)
192
+
193
+ return torch.utils.data.DataLoader(ds, batch_size=batch_size, num_workers=num_workers, collate_fn=collate)
194
+
195
+ # ---- try it (set num_workers=0 first if you want easier debugging) ----
196
+ if __name__ == "__main__":
197
+ paths, X = next(iter(make_embeddings_loader(num_workers=0, prefer_key=None)))
198
+ print(len(paths), X.shape)
199
+
200
+ ```
201
+
202
+ ---
203
+
204
+ ## C) EEG (`.npy/.npz`) — ragged-friendly (returns list of arrays)
205
+
206
+ ```python
207
+ import io, re
208
  import webdataset as wds
209
+ from huggingface_hub import HfFileSystem, hf_hub_url
210
+ import numpy as np
211
+
212
+ REPO_ID = "nonarjb/alignvis" # your dataset repo on HF
213
+ REVISION = "main"
214
+ DATASET_DIR = "things_eeg_2" # the folder inside the repo
215
+
216
+ def _hf_eeg_urls(repo_id=REPO_ID, dataset_dir=DATASET_DIR, revision=REVISION):
217
+ """Collect EEG shard URLs for both possible top folders."""
218
+ fs = HfFileSystem()
219
+ urls = []
220
+ for top in ("Preprocessed_data_250Hz", "preprocessed_eeg"):
221
+ pattern = f"datasets/{repo_id}/{dataset_dir}/{dataset_dir}-{top}-*.tar"
222
+ hf_paths = sorted(fs.glob(pattern))
223
+ rel = [p.split(f"datasets/{repo_id}/", 1)[1] for p in hf_paths]
224
+ urls += [hf_hub_url(repo_id, filename=p, repo_type="dataset", revision=revision) for p in rel]
225
+ return urls
226
+
227
+ def _load_subject_eeg_from_hf(subject_id: int, split: str):
228
+ """
229
+ Returns (subject_eeg_data, ch_names) for a given subject+split
230
+ by streaming the per-subject .npy/.npz from HF shards.
231
+ """
232
+ urls = _hf_eeg_urls()
233
+ if not urls:
234
+ raise RuntimeError("No EEG shards found in HF repo")
235
+ filebase = "preprocessed_eeg_training" if split == "train" else "preprocessed_eeg_test"
236
+ key_prefix = f"sub-{subject_id:02d}/"
237
+
238
+ ds = wds.WebDataset(urls, shardshuffle=False)
239
+ for s in ds:
240
+ # find the per-subject file
241
+ if ("npy" in s or "npz" in s) and s["__key__"].startswith(key_prefix) and s["__key__"].endswith(filebase):
242
+ ext = "npz" if "npz" in s else "npy"
243
+ payload = s[ext]
244
+ bio = io.BytesIO(payload)
245
+
246
+ # load with safe first, fallback to pickle (original code used allow_pickle=True)
247
+ if ext == "npz":
248
+ try:
249
+ z = np.load(bio, allow_pickle=False)
250
+ except Exception:
251
+ bio.seek(0); z = np.load(bio, allow_pickle=True)
252
+ # prefer exact fields as in your original code
253
+ eeg_data = z["preprocessed_eeg_data"]
254
+ ch_names = z["ch_names"] if "ch_names" in z else None
255
+ else: # npy
256
+ try:
257
+ obj = np.load(bio, allow_pickle=False)
258
+ except ValueError:
259
+ bio.seek(0); obj = np.load(bio, allow_pickle=True)
260
+
261
+ # obj could be dict-like or 0-d object holding a dict
262
+ if isinstance(obj, dict):
263
+ eeg_data = obj["preprocessed_eeg_data"]
264
+ ch_names = obj.get("ch_names")
265
+ elif isinstance(obj, np.ndarray) and obj.dtype == object and obj.shape == ():
266
+ d = obj.item()
267
+ eeg_data = d["preprocessed_eeg_data"]
268
+ ch_names = d.get("ch_names")
269
+ else:
270
+ # if it’s already a numeric array (unlikely for your case)
271
+ eeg_data = obj
272
+ ch_names = None
273
+
274
+ return np.asarray(eeg_data), ch_names
275
+
276
+ raise FileNotFoundError(f"Subject file not found in HF shards: {key_prefix}{filebase}.(npy|npz)")
277
+
278
+
279
+ subject_eeg_data, ch_names = _load_subject_eeg_from_hf(subject_id=1, split="train")
280
+ print(subject_eeg_data.shape)
281
+ print(ch_names)
282
+ ```
283
+
284
+ > If some `.npy` were saved as **object-dtype**, resave as numeric arrays; otherwise you must load with `allow_pickle=True` (only if you trust the data).
285
+
286
+ ---
287
+
288
+ ## D) Download, **untar**, and use locally (byte-identical files)
289
+
290
+ ```python
291
+ # 1) Download the dataset subtree
292
+ from huggingface_hub import snapshot_download
293
+ local_root = snapshot_download(
294
+ "nonarjb/alignvis", repo_type="dataset", allow_patterns=["things_eeg_2/**"]
295
+ )
296
+
297
+ # 2) Untar to a restore directory (keys preserved under each top folder)
298
+ import tarfile, glob, pathlib
299
+
300
+ restore_root = pathlib.Path("./restore/things_eeg_2")
301
+
302
+ for top in ("images", "image_embeddings", "preprocessed_eeg"):
303
+ (restore_root / top).mkdir(parents=True, exist_ok=True)
304
+ for t in glob.glob(f"{local_root}/things_eeg_2/things_eeg_2-{top}-*.tar"):
305
+ with tarfile.open(t) as tf:
306
+ tf.extractall(restore_root / top)
307
+
308
+ print("Restored under:", restore_root)
309
+ ```
310
+
311
+ Now the folder tree mirrors the original:
312
+
313
+ ```python
314
+ # Example local usage
315
+ from PIL import Image
316
+ import numpy as np
317
+
318
+ img = Image.open("./restore/things_eeg_2/images/training_images/01133_raincoat/raincoat_01s.jpg")
319
+ vec = np.load("./restore/things_eeg_2/image_embeddings/some/file.npy")
320
+ eeg = np.load("./restore/things_eeg_2/preprocessed_eeg/s01/run3/segment_0001.npy", allow_pickle=False)
321
+ ```
322
+
323
+ ---
324
+
325
+ ### Notes
326
+
327
+ * WebDataset can also read **local** shards by passing `file://` URLs instead of `https://`.
328
+ * If your shards are named differently, tweak `hf_tar_urls(..., top="...")` and the `rel_path` prefixes (`images/`, `image_embeddings/`, `preprocessed_eeg/`).
329
+ * To batch EEG tensors, implement padding in the `collate` function.