edbeeching HF Staff commited on
Commit
095ecf8
·
verified ·
1 Parent(s): 03cc138

Upload create_dataset.py

Browse files
Files changed (1) hide show
  1. create_dataset.py +560 -0
create_dataset.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert Random Promoter DREAM 2022 files to Hugging Face datasets.
3
+
4
+ The script keeps raw downloads under scratch/ by default and publishes several
5
+ configs into one dataset repo:
6
+
7
+ - supervised: train/validation/test sequence-to-activity regression splits
8
+ - challenge_test_sequences: unlabeled challenge test sequences
9
+ - test_subset_membership: IDs from test_subset_ids.tar.gz
10
+ - public_leaderboard_ids: IDs from public_leaderboard_ids.tar.gz
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import hashlib
17
+ import io
18
+ import logging
19
+ import shutil
20
+ import tarfile
21
+ import urllib.request
22
+ from collections.abc import Iterator
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from datasets import Dataset
28
+ from datasets import DatasetDict
29
+ from datasets import Features
30
+ from datasets import Value
31
+ from datasets import load_dataset
32
+ from huggingface_hub import HfApi
33
+
34
+ ZENODO_RECORD = "10633252"
35
+ DEFAULT_HUB_REPO_ID = "HuggingFaceBio/random-promoter-dream-2022"
36
+ DEFAULT_RAW_DIR = Path("scratch/promoter_activity_dream/raw")
37
+ DEFAULT_OUTPUT_DIR = Path("scratch/promoter_activity_dream/hf_dataset")
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class SourceFile:
44
+ filename: str
45
+ md5: str
46
+ url: str
47
+
48
+
49
+ SOURCE_FILES = {
50
+ "train": SourceFile(
51
+ filename="train.txt",
52
+ md5="b387d6e053f797d80abc8b972d16c355",
53
+ url=f"https://zenodo.org/records/{ZENODO_RECORD}/files/train.txt?download=1",
54
+ ),
55
+ "validation": SourceFile(
56
+ filename="val.txt",
57
+ md5="c0f8d2fc873f194e540586ad51cb5ae6",
58
+ url=f"https://zenodo.org/records/{ZENODO_RECORD}/files/val.txt?download=1",
59
+ ),
60
+ "test": SourceFile(
61
+ filename="filtered_test_data_with_MAUDE_expression.txt",
62
+ md5="d0880059150ddebc900450a9d2a6418d",
63
+ url=(
64
+ f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
65
+ "filtered_test_data_with_MAUDE_expression.txt?download=1"
66
+ ),
67
+ ),
68
+ "challenge_test_sequences": SourceFile(
69
+ filename="test_sequences.txt",
70
+ md5="0173024c6f468cc1409e80a1b339609c",
71
+ url=(
72
+ f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
73
+ "test_sequences.txt?download=1"
74
+ ),
75
+ ),
76
+ "test_subset_ids": SourceFile(
77
+ filename="test_subset_ids.tar.gz",
78
+ md5="40b56d200273990560b5b1c2def2185a",
79
+ url=(
80
+ f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
81
+ "test_subset_ids.tar.gz?download=1"
82
+ ),
83
+ ),
84
+ "public_leaderboard_ids": SourceFile(
85
+ filename="public_leaderboard_ids.tar.gz",
86
+ md5="49ce1bc5118665e6c4382c6b9c470efa",
87
+ url=(
88
+ f"https://zenodo.org/records/{ZENODO_RECORD}/files/"
89
+ "public_leaderboard_ids.tar.gz?download=1"
90
+ ),
91
+ ),
92
+ }
93
+
94
+ SUPERVISED_FEATURES = Features(
95
+ {
96
+ "sequence": Value("string"),
97
+ "activity": Value("float32"),
98
+ "sequence_length": Value("int32"),
99
+ "source_file": Value("string"),
100
+ "row_id": Value("int64"),
101
+ }
102
+ )
103
+
104
+ SEQUENCE_FEATURES = Features(
105
+ {
106
+ "sequence": Value("string"),
107
+ "sequence_length": Value("int32"),
108
+ "source_file": Value("string"),
109
+ "row_id": Value("int64"),
110
+ }
111
+ )
112
+
113
+ ID_FEATURES = Features(
114
+ {
115
+ "subset": Value("string"),
116
+ "item_id": Value("string"),
117
+ "row_id": Value("int64"),
118
+ "source_member": Value("string"),
119
+ "line_number": Value("int64"),
120
+ "raw_line": Value("string"),
121
+ }
122
+ )
123
+
124
+
125
+ def parse_args() -> argparse.Namespace:
126
+ parser = argparse.ArgumentParser(
127
+ description="Convert Random Promoter DREAM 2022 data to HF datasets."
128
+ )
129
+ parser.add_argument("--hub-repo-id", default=DEFAULT_HUB_REPO_ID)
130
+ parser.add_argument(
131
+ "--private", action=argparse.BooleanOptionalAction, default=True
132
+ )
133
+ parser.add_argument("--push-to-hub", action="store_true")
134
+ parser.add_argument("--raw-dir", type=Path, default=DEFAULT_RAW_DIR)
135
+ parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
136
+ parser.add_argument(
137
+ "--dataset-cache-dir",
138
+ type=Path,
139
+ default=None,
140
+ help="Optional datasets cache directory. Defaults to the HF cache.",
141
+ )
142
+ parser.add_argument("--num-proc", type=int, default=8)
143
+ parser.add_argument("--max-rows-per-split", type=int, default=None)
144
+ parser.add_argument(
145
+ "--no-download",
146
+ action="store_true",
147
+ help="Use existing files in --raw-dir and fail if any are missing.",
148
+ )
149
+ parser.add_argument("--train-file", type=Path, default=None)
150
+ parser.add_argument("--validation-file", type=Path, default=None)
151
+ parser.add_argument("--test-file", type=Path, default=None)
152
+ parser.add_argument("--test-sequences-file", type=Path, default=None)
153
+ parser.add_argument("--test-subset-ids-tar", type=Path, default=None)
154
+ parser.add_argument("--public-leaderboard-ids-tar", type=Path, default=None)
155
+ return parser.parse_args()
156
+
157
+
158
+ def file_md5(path: Path, chunk_size: int = 1024 * 1024) -> str:
159
+ digest = hashlib.md5()
160
+ with path.open("rb") as handle:
161
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
162
+ digest.update(chunk)
163
+ return digest.hexdigest()
164
+
165
+
166
+ def download_file(source: SourceFile, raw_dir: Path, no_download: bool) -> Path:
167
+ raw_dir.mkdir(parents=True, exist_ok=True)
168
+ path = raw_dir / source.filename
169
+ if path.exists():
170
+ actual_md5 = file_md5(path)
171
+ if actual_md5 != source.md5:
172
+ raise ValueError(
173
+ f"{path} exists but md5 is {actual_md5}; expected {source.md5}"
174
+ )
175
+ logger.info("Using cached %s", path)
176
+ return path
177
+ if no_download:
178
+ raise FileNotFoundError(f"Missing {path}; rerun without --no-download")
179
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
180
+ logger.info("Downloading %s", source.url)
181
+ with urllib.request.urlopen(source.url) as response, tmp_path.open("wb") as out:
182
+ shutil.copyfileobj(response, out)
183
+ actual_md5 = file_md5(tmp_path)
184
+ if actual_md5 != source.md5:
185
+ tmp_path.unlink(missing_ok=True)
186
+ raise ValueError(
187
+ f"Downloaded {source.filename} md5 {actual_md5}; expected {source.md5}"
188
+ )
189
+ tmp_path.replace(path)
190
+ return path
191
+
192
+
193
+ def resolve_paths(args: argparse.Namespace) -> dict[str, Path]:
194
+ explicit = {
195
+ "train": args.train_file,
196
+ "validation": args.validation_file,
197
+ "test": args.test_file,
198
+ "challenge_test_sequences": args.test_sequences_file,
199
+ "test_subset_ids": args.test_subset_ids_tar,
200
+ "public_leaderboard_ids": args.public_leaderboard_ids_tar,
201
+ }
202
+ if any(path is not None for path in explicit.values()):
203
+ missing = [
204
+ name for name in ("train", "validation", "test") if explicit[name] is None
205
+ ]
206
+ if missing:
207
+ raise ValueError(
208
+ "When using explicit local files, provide train, validation, "
209
+ f"and test files. Missing: {missing}"
210
+ )
211
+ return {name: path for name, path in explicit.items() if path is not None}
212
+ return {
213
+ name: download_file(source, args.raw_dir, args.no_download)
214
+ for name, source in SOURCE_FILES.items()
215
+ }
216
+
217
+
218
+ def add_supervised_metadata(
219
+ batch: dict[str, list[Any]],
220
+ indices: list[int],
221
+ source_file: str,
222
+ ) -> dict[str, list[Any]]:
223
+ sequences = [str(sequence).strip().upper() for sequence in batch["sequence"]]
224
+ return {
225
+ "sequence": sequences,
226
+ "activity": [float(value) for value in batch["activity"]],
227
+ "sequence_length": [len(sequence) for sequence in sequences],
228
+ "source_file": [source_file] * len(sequences),
229
+ "row_id": list(indices),
230
+ }
231
+
232
+
233
+ def limit_dataset(dataset: Dataset, max_rows: int | None) -> Dataset:
234
+ if max_rows is None or max_rows >= len(dataset):
235
+ return dataset
236
+ return dataset.select(range(max_rows))
237
+
238
+
239
+ def build_supervised_dataset(
240
+ paths: dict[str, Path],
241
+ *,
242
+ max_rows_per_split: int | None,
243
+ num_proc: int,
244
+ cache_dir: Path | None = None,
245
+ ) -> DatasetDict:
246
+ raw = load_dataset(
247
+ "csv",
248
+ data_files={
249
+ "train": str(paths["train"]),
250
+ "validation": str(paths["validation"]),
251
+ "test": str(paths["test"]),
252
+ },
253
+ delimiter="\t",
254
+ column_names=["sequence", "activity"],
255
+ features=Features({"sequence": Value("string"), "activity": Value("float32")}),
256
+ cache_dir=str(cache_dir) if cache_dir is not None else None,
257
+ )
258
+ processed = {}
259
+ for split, dataset in raw.items():
260
+ dataset = limit_dataset(dataset, max_rows_per_split)
261
+ map_kwargs: dict[str, Any] = {
262
+ "with_indices": True,
263
+ "fn_kwargs": {"source_file": paths[split].name},
264
+ "features": SUPERVISED_FEATURES,
265
+ "desc": f"Adding DREAM metadata to {split}",
266
+ }
267
+ if num_proc and num_proc > 1:
268
+ map_kwargs["num_proc"] = num_proc
269
+ processed[split] = dataset.map(
270
+ add_supervised_metadata, batched=True, **map_kwargs
271
+ )
272
+ return DatasetDict(processed)
273
+
274
+
275
+ def iter_sequence_file(
276
+ path: Path, max_rows: int | None = None
277
+ ) -> Iterator[dict[str, Any]]:
278
+ with path.open("r", encoding="utf-8") as handle:
279
+ for row_id, line in enumerate(handle):
280
+ if max_rows is not None and row_id >= max_rows:
281
+ break
282
+ line = line.strip()
283
+ if not line:
284
+ continue
285
+ sequence = line.split("\t", 1)[0].strip().upper()
286
+ yield {
287
+ "sequence": sequence,
288
+ "sequence_length": len(sequence),
289
+ "source_file": path.name,
290
+ "row_id": row_id,
291
+ }
292
+
293
+
294
+ def build_sequence_dataset(
295
+ path: Path, max_rows: int | None, cache_dir: Path | None = None
296
+ ) -> Dataset:
297
+ return Dataset.from_generator(
298
+ iter_sequence_file,
299
+ gen_kwargs={"path": path, "max_rows": max_rows},
300
+ features=SEQUENCE_FEATURES,
301
+ cache_dir=str(cache_dir) if cache_dir is not None else None,
302
+ )
303
+
304
+
305
+ def subset_name_from_member(member_name: str) -> str:
306
+ path = Path(member_name)
307
+ name = path.name
308
+ for suffix in (".txt", ".tsv", ".csv", ".ids"):
309
+ if name.endswith(suffix):
310
+ name = name[: -len(suffix)]
311
+ return name.replace(" ", "_")
312
+
313
+
314
+ def parse_id_line(line: str) -> tuple[str, int]:
315
+ item_id = line.split("\t", 1)[0].split(",", 1)[0].strip()
316
+ row_id = int(item_id) if item_id.isdigit() else -1
317
+ return item_id, row_id
318
+
319
+
320
+ def iter_tar_ids(path: Path, max_rows: int | None = None) -> Iterator[dict[str, Any]]:
321
+ emitted = 0
322
+ with tarfile.open(path, "r:gz") as tar:
323
+ for member in tar:
324
+ if not member.isfile():
325
+ continue
326
+ extracted = tar.extractfile(member)
327
+ if extracted is None:
328
+ continue
329
+ subset = subset_name_from_member(member.name)
330
+ with io.TextIOWrapper(extracted, encoding="utf-8") as handle:
331
+ for line_number, line in enumerate(handle):
332
+ raw_line = line.strip()
333
+ if not raw_line:
334
+ continue
335
+ if max_rows is not None and emitted >= max_rows:
336
+ return
337
+ item_id, row_id = parse_id_line(raw_line)
338
+ yield {
339
+ "subset": subset,
340
+ "item_id": item_id,
341
+ "row_id": row_id,
342
+ "source_member": member.name,
343
+ "line_number": line_number,
344
+ "raw_line": raw_line,
345
+ }
346
+ emitted += 1
347
+
348
+
349
+ def build_id_dataset(
350
+ path: Path, max_rows: int | None, cache_dir: Path | None = None
351
+ ) -> Dataset:
352
+ return Dataset.from_generator(
353
+ iter_tar_ids,
354
+ gen_kwargs={"path": path, "max_rows": max_rows},
355
+ features=ID_FEATURES,
356
+ cache_dir=str(cache_dir) if cache_dir is not None else None,
357
+ )
358
+
359
+
360
+ def render_dataset_card(hub_repo_id: str) -> str:
361
+ return f"""---
362
+ license: cc-by-4.0
363
+ task_categories:
364
+ - text-regression
365
+ language:
366
+ - en
367
+ tags:
368
+ - biology
369
+ - dna
370
+ - genomics
371
+ - promoter
372
+ - gene-expression
373
+ - carbon
374
+ ---
375
+
376
+ # Random Promoter DREAM Challenge 2022
377
+
378
+ This dataset repackages the processed Random Promoter DREAM Challenge 2022
379
+ files from Zenodo record `{ZENODO_RECORD}` for use with `datasets`.
380
+
381
+ The task is sequence-to-expression regression on synthetic yeast promoter
382
+ sequences. The canonical supervised config contains random promoter training
383
+ examples, validation examples, and labeled designed test promoters.
384
+
385
+ ## Configs
386
+
387
+ - `supervised`: `train`, `validation`, and `test` splits with promoter
388
+ sequences and measured activity.
389
+ - `challenge_test_sequences`: unlabeled test sequences for submission-style
390
+ prediction workflows.
391
+ - `test_subset_membership`: normalized IDs from `test_subset_ids.tar.gz`.
392
+ - `public_leaderboard_ids`: normalized IDs from `public_leaderboard_ids.tar.gz`.
393
+
394
+ ## Schema
395
+
396
+ `supervised`:
397
+
398
+ - `sequence`: DNA sequence.
399
+ - `activity`: measured promoter activity.
400
+ - `sequence_length`: sequence length in base pairs.
401
+ - `source_file`: source filename.
402
+ - `row_id`: zero-based row index within the source split.
403
+
404
+ ID metadata configs:
405
+
406
+ - `subset`: subset name inferred from the archive member.
407
+ - `item_id`: raw ID token from the source line.
408
+ - `row_id`: integer row ID when `item_id` is numeric; otherwise `-1`.
409
+ - `source_member`: archive member path.
410
+ - `line_number`: line number within the member.
411
+ - `raw_line`: unmodified stripped source line.
412
+
413
+ ## Usage
414
+
415
+ ```py
416
+ from datasets import load_dataset
417
+
418
+ ds = load_dataset("{hub_repo_id}", "supervised")
419
+ train = ds["train"]
420
+ validation = ds["validation"]
421
+ test = ds["test"]
422
+
423
+ subsets = load_dataset("{hub_repo_id}", "test_subset_membership", split="train")
424
+ ```
425
+
426
+ ## Source
427
+
428
+ Source: Random Promoter DREAM Challenge 2022, Zenodo DOI
429
+ `10.5281/zenodo.10633252`.
430
+
431
+ The source record is licensed CC BY 4.0. Cite the original DREAM Challenge data
432
+ and paper when using this dataset.
433
+
434
+ ## Reproduction
435
+
436
+ This dataset repo includes `create_dataset.py`, the script used to download,
437
+ convert, and upload the configs.
438
+ """
439
+
440
+
441
+ def save_or_push(
442
+ *,
443
+ dataset: Dataset | DatasetDict,
444
+ config_name: str,
445
+ args: argparse.Namespace,
446
+ api: HfApi | None,
447
+ ) -> None:
448
+ if args.push_to_hub:
449
+ dataset.push_to_hub(
450
+ args.hub_repo_id,
451
+ config_name=config_name,
452
+ commit_message=f"Upload {config_name} config",
453
+ )
454
+ logger.info("Pushed %s to %s", config_name, args.hub_repo_id)
455
+ return
456
+ output_path = args.output_dir / config_name
457
+ dataset.save_to_disk(str(output_path))
458
+ logger.info("Saved %s to %s", config_name, output_path)
459
+
460
+
461
+ def upload_dataset_metadata(args: argparse.Namespace, api: HfApi) -> None:
462
+ readme_bytes = render_dataset_card(args.hub_repo_id).encode("utf-8")
463
+ api.upload_file(
464
+ path_or_fileobj=readme_bytes,
465
+ path_in_repo="README.md",
466
+ repo_id=args.hub_repo_id,
467
+ repo_type="dataset",
468
+ commit_message="Upload dataset card",
469
+ )
470
+ api.upload_file(
471
+ path_or_fileobj=Path(__file__).read_bytes(),
472
+ path_in_repo="create_dataset.py",
473
+ repo_id=args.hub_repo_id,
474
+ repo_type="dataset",
475
+ commit_message="Upload create_dataset.py",
476
+ )
477
+
478
+
479
+ def run(args: argparse.Namespace) -> None:
480
+ paths = resolve_paths(args)
481
+ args.output_dir.mkdir(parents=True, exist_ok=True)
482
+
483
+ api = None
484
+ if args.push_to_hub:
485
+ api = HfApi()
486
+ api.whoami()
487
+ api.create_repo(
488
+ repo_id=args.hub_repo_id,
489
+ repo_type="dataset",
490
+ exist_ok=True,
491
+ private=args.private,
492
+ )
493
+
494
+ supervised = build_supervised_dataset(
495
+ paths,
496
+ max_rows_per_split=args.max_rows_per_split,
497
+ num_proc=args.num_proc,
498
+ cache_dir=args.dataset_cache_dir,
499
+ )
500
+ save_or_push(dataset=supervised, config_name="supervised", args=args, api=api)
501
+
502
+ if "challenge_test_sequences" in paths:
503
+ challenge_test = build_sequence_dataset(
504
+ paths["challenge_test_sequences"],
505
+ args.max_rows_per_split,
506
+ cache_dir=args.dataset_cache_dir,
507
+ )
508
+ save_or_push(
509
+ dataset=challenge_test,
510
+ config_name="challenge_test_sequences",
511
+ args=args,
512
+ api=api,
513
+ )
514
+
515
+ if "test_subset_ids" in paths:
516
+ subset_ids = build_id_dataset(
517
+ paths["test_subset_ids"],
518
+ args.max_rows_per_split,
519
+ cache_dir=args.dataset_cache_dir,
520
+ )
521
+ save_or_push(
522
+ dataset=subset_ids,
523
+ config_name="test_subset_membership",
524
+ args=args,
525
+ api=api,
526
+ )
527
+
528
+ if "public_leaderboard_ids" in paths:
529
+ leaderboard_ids = build_id_dataset(
530
+ paths["public_leaderboard_ids"],
531
+ args.max_rows_per_split,
532
+ cache_dir=args.dataset_cache_dir,
533
+ )
534
+ save_or_push(
535
+ dataset=leaderboard_ids,
536
+ config_name="public_leaderboard_ids",
537
+ args=args,
538
+ api=api,
539
+ )
540
+
541
+ if args.push_to_hub and api is not None:
542
+ upload_dataset_metadata(args, api)
543
+ logger.info("Uploaded dataset card and create_dataset.py")
544
+ else:
545
+ (args.output_dir / "README.md").write_text(
546
+ render_dataset_card(args.hub_repo_id),
547
+ encoding="utf-8",
548
+ )
549
+
550
+
551
+ def main() -> None:
552
+ logging.basicConfig(
553
+ level=logging.INFO,
554
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
555
+ )
556
+ run(parse_args())
557
+
558
+
559
+ if __name__ == "__main__":
560
+ main()