anindya64 commited on
Commit
fcbea81
·
verified ·
1 Parent(s): bce037c

Add files using upload-large-folder tool

Browse files
Files changed (48) hide show
  1. .gitignore +5 -0
  2. README.md +201 -0
  3. data/processing_summary.json +114 -0
  4. data/protein_links/test-275387.parquet +3 -0
  5. data/protein_links/test-275388.parquet +3 -0
  6. data/protein_links/test-275391.parquet +3 -0
  7. data/protein_links/test-275393.parquet +3 -0
  8. data/protein_links/test-275394.parquet +3 -0
  9. data/protein_links/test-275395.parquet +3 -0
  10. data/protein_links/test-275397.parquet +3 -0
  11. data/protein_links/test-275398.parquet +3 -0
  12. data/protein_links/test-275399.parquet +3 -0
  13. data/protein_links/test-275402.parquet +3 -0
  14. data/protein_links/test-275405.parquet +3 -0
  15. data/protein_links/test-275408.parquet +3 -0
  16. data/protein_links/test-275410.parquet +3 -0
  17. data/protein_links/test-275411.parquet +3 -0
  18. data/protein_links/test-275413.parquet +3 -0
  19. data/protein_links/train-275395.parquet +3 -0
  20. data/protein_links/train-275400.parquet +3 -0
  21. data/protein_links/train-275402.parquet +3 -0
  22. data/protein_links/train-275403.parquet +3 -0
  23. data/protein_links/train-275409.parquet +3 -0
  24. data/protein_links/train-275411.parquet +3 -0
  25. data/protein_links/train-275412.parquet +3 -0
  26. data/protein_links/validation-275376.parquet +3 -0
  27. data/protein_links/validation-275384.parquet +3 -0
  28. data/protein_links/validation-275387.parquet +3 -0
  29. data/protein_links/validation-275389.parquet +3 -0
  30. data/protein_links/validation-275390.parquet +3 -0
  31. data/protein_links/validation-275391.parquet +3 -0
  32. data/protein_links/validation-275393.parquet +3 -0
  33. data/protein_links/validation-275395.parquet +3 -0
  34. data/protein_links/validation-275396.parquet +3 -0
  35. data/protein_links/validation-275399.parquet +3 -0
  36. data/protein_links/validation-275400.parquet +3 -0
  37. data/protein_links/validation-275401.parquet +3 -0
  38. data/protein_links/validation-275404.parquet +3 -0
  39. data/protein_links/validation-275405.parquet +3 -0
  40. data/protein_links/validation-275406.parquet +3 -0
  41. data/protein_links/validation-275407.parquet +3 -0
  42. data/protein_links/validation-275408.parquet +3 -0
  43. data/protein_links/validation-275409.parquet +3 -0
  44. data/protein_links/validation-275412.parquet +3 -0
  45. data_preview/processing_summary.json +114 -0
  46. requirements.txt +3 -0
  47. scripts/prepare_hf_dataset.py +763 -0
  48. scripts/validate_hf_dataset.py +89 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .cache/
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
5
+ data_preview/
README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ pretty_name: STRING v12.0
4
+ tags:
5
+ - biology
6
+ - proteomics
7
+ - protein-protein-interaction
8
+ - graph
9
+ - string-db
10
+ configs:
11
+ - config_name: protein_links
12
+ data_files:
13
+ - split: train
14
+ path: "data/protein_links/train-*.parquet"
15
+ - split: validation
16
+ path: "data/protein_links/validation-*.parquet"
17
+ - split: test
18
+ path: "data/protein_links/test-*.parquet"
19
+ - config_name: protein_info
20
+ data_files:
21
+ - split: train
22
+ path: "data/protein_info/train-*.parquet"
23
+ - split: validation
24
+ path: "data/protein_info/validation-*.parquet"
25
+ - split: test
26
+ path: "data/protein_info/test-*.parquet"
27
+ - config_name: protein_aliases
28
+ data_files:
29
+ - split: train
30
+ path: "data/protein_aliases/train-*.parquet"
31
+ - split: validation
32
+ path: "data/protein_aliases/validation-*.parquet"
33
+ - split: test
34
+ path: "data/protein_aliases/test-*.parquet"
35
+ - config_name: protein_sequences
36
+ data_files:
37
+ - split: train
38
+ path: "data/protein_sequences/train-*.parquet"
39
+ - split: validation
40
+ path: "data/protein_sequences/validation-*.parquet"
41
+ - split: test
42
+ path: "data/protein_sequences/test-*.parquet"
43
+ - config_name: species
44
+ data_files:
45
+ - split: train
46
+ path: "data/species/train-*.parquet"
47
+ - split: validation
48
+ path: "data/species/validation-*.parquet"
49
+ - split: test
50
+ path: "data/species/test-*.parquet"
51
+ ---
52
+
53
+ # STRING v12.0
54
+
55
+ This repository contains a Hugging Face-friendly packaging of the STRING v12.0 bulk download. STRING is a database of known and predicted protein associations. The raw files are kept under `v12.0/`; the scripts in `scripts/` convert them into sharded Parquet files under `data/` so the Hugging Face Data Viewer can show tables and `datasets.load_dataset` can stream or download the data.
56
+
57
+ STRING v12.0 reports 59,309,604 proteins from 12,535 organisms and 27,541,372,833 interactions. The upstream data and download files are distributed under Creative Commons BY 4.0; credit STRING and describe any modifications when using this processed version.
58
+
59
+ ## Configs
60
+
61
+ | Config | Raw source | Description |
62
+ | --- | --- | --- |
63
+ | `protein_links` | `protein.links.full.v12.0.txt.gz` | Protein-protein association edges with all STRING evidence channels and `combined_score`. |
64
+ | `protein_info` | `protein.info.v12.0.txt.gz` | Protein identifiers, preferred names, sizes, and annotations. |
65
+ | `protein_aliases` | `protein.aliases.v12.0.txt.gz` | External aliases and identifier sources for STRING proteins. |
66
+ | `protein_sequences` | `protein.sequences.v12.0.fa.gz` | Protein amino-acid sequences parsed from FASTA. |
67
+ | `species` | `species.v12.0.txt` | Organism metadata: taxonomy id, STRING type, compact name, official NCBI name, and domain. |
68
+
69
+ ## Splits
70
+
71
+ The post-processing script assigns rows to `train`, `validation`, and `test` with a deterministic CRC32 hash. The default ratios are 98/1/1. Re-running with the same `--split-seed` gives the same split assignment.
72
+
73
+ Split keys:
74
+
75
+ | Config | Split key |
76
+ | --- | --- |
77
+ | `protein_links` | `protein1 + protein2` |
78
+ | `protein_info` | `string_protein_id` |
79
+ | `protein_aliases` | `string_protein_id + alias + source` |
80
+ | `protein_sequences` | `string_protein_id` |
81
+ | `species` | `taxon_id` |
82
+
83
+ ## Usage
84
+
85
+ Install the client library:
86
+
87
+ ```bash
88
+ python -m pip install datasets
89
+ ```
90
+
91
+ Load the interaction table in streaming mode:
92
+
93
+ ```python
94
+ from datasets import load_dataset
95
+
96
+ links = load_dataset("LiteFold/STRING", "protein_links", split="train", streaming=True)
97
+ first_row = next(iter(links))
98
+ print(first_row)
99
+ ```
100
+
101
+ Load a smaller metadata table normally:
102
+
103
+ ```python
104
+ from datasets import load_dataset
105
+
106
+ proteins = load_dataset("LiteFold/STRING", "protein_info", split="train")
107
+ print(proteins[0])
108
+ ```
109
+
110
+ Load local Parquet files generated before upload:
111
+
112
+ ```python
113
+ from datasets import load_dataset
114
+
115
+ data_files = {
116
+ "train": "data/protein_links/train-*.parquet",
117
+ "validation": "data/protein_links/validation-*.parquet",
118
+ "test": "data/protein_links/test-*.parquet",
119
+ }
120
+ links = load_dataset("parquet", data_files=data_files, split="train", streaming=True)
121
+ ```
122
+
123
+ ## Post-processing
124
+
125
+ Install conversion dependencies:
126
+
127
+ ```bash
128
+ python -m pip install -r requirements.txt
129
+ ```
130
+
131
+ Create the full Parquet dataset using 32 worker processes:
132
+
133
+ ```bash
134
+ python scripts/prepare_hf_dataset.py \
135
+ --raw-dir v12.0 \
136
+ --output-dir data \
137
+ --num-proc 32 \
138
+ --overwrite
139
+ ```
140
+
141
+ Create a quick preview dataset before running the full conversion:
142
+
143
+ ```bash
144
+ python scripts/prepare_hf_dataset.py \
145
+ --raw-dir v12.0 \
146
+ --output-dir data_preview \
147
+ --tables species,protein_info,protein_links \
148
+ --max-rows-per-table 10000 \
149
+ --num-proc 32 \
150
+ --overwrite
151
+ ```
152
+
153
+ Useful options:
154
+
155
+ | Option | Purpose |
156
+ | --- | --- |
157
+ | `--num-proc 32` | Uses 32 parser workers. |
158
+ | `--rows-per-chunk 100000` | Controls rows parsed per worker task. Lower this if memory is tight. |
159
+ | `--max-in-flight 32` | Bounds queued chunks to avoid unbounded RAM growth. Defaults to `--num-proc`. |
160
+ | `--link-min-combined-score 700` | Optionally keep only higher-confidence links. |
161
+ | `--compression zstd` | Writes compressed Parquet shards. |
162
+
163
+ Validate generated local files:
164
+
165
+ ```bash
166
+ python scripts/validate_hf_dataset.py --data-dir data --config protein_links --split train --streaming
167
+ ```
168
+
169
+ Validate after upload:
170
+
171
+ ```bash
172
+ python scripts/validate_hf_dataset.py --repo-id LiteFold/STRING --config protein_links --split train --streaming
173
+ ```
174
+
175
+ ## Upload
176
+
177
+ After generating `data/`, upload the processed files and this dataset card:
178
+
179
+ ```bash
180
+ huggingface-cli upload LiteFold/STRING README.md README.md --repo-type dataset
181
+ huggingface-cli upload LiteFold/STRING data data --repo-type dataset
182
+ ```
183
+
184
+ The repository already tracks `*.parquet` with Git LFS through `.gitattributes`.
185
+
186
+ ## Citation
187
+
188
+ Please cite the upstream STRING database:
189
+
190
+ ```bibtex
191
+ @article{szklarczyk2023string,
192
+ title = {The STRING database in 2023: protein-protein association networks and functional enrichment analyses for any sequenced genome of interest},
193
+ author = {Szklarczyk, Damian and Kirsch, Rebecca and Koutrouli, Mikaela and Nastou, Katerina and Mehryary, Farrokh and Hachilif, Radja and Gable, Annika L. and Fang, Tao and Doncheva, Nadezhda T. and Pyysalo, Sampo and Bork, Peer and Jensen, Lars J. and von Mering, Christian},
194
+ journal = {Nucleic Acids Research},
195
+ volume = {51},
196
+ number = {D1},
197
+ pages = {D638--D646},
198
+ year = {2023},
199
+ doi = {10.1093/nar/gkac1000}
200
+ }
201
+ ```
data/processing_summary.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compression": "zstd",
3
+ "link_min_combined_score": null,
4
+ "max_rows_per_table": null,
5
+ "num_proc": 32,
6
+ "output_dir": "data",
7
+ "raw_dir": "v12.0",
8
+ "rows_per_chunk": 100000,
9
+ "split_ratios": {
10
+ "test": 0.01,
11
+ "train": 0.98,
12
+ "validation": 0.01
13
+ },
14
+ "split_seed": "string-v12.0",
15
+ "stats": {
16
+ "protein_aliases": {
17
+ "parser": {
18
+ "bad_rows": 0,
19
+ "chunks": 6281,
20
+ "filtered_rows": 0,
21
+ "parsed_rows": 628096921
22
+ },
23
+ "rows": {
24
+ "test": 6279523,
25
+ "train": 615533987,
26
+ "validation": 6283411
27
+ },
28
+ "shards": {
29
+ "test": 6281,
30
+ "train": 6281,
31
+ "validation": 6281
32
+ }
33
+ },
34
+ "protein_info": {
35
+ "parser": {
36
+ "bad_rows": 0,
37
+ "chunks": 594,
38
+ "filtered_rows": 0,
39
+ "parsed_rows": 59309604
40
+ },
41
+ "rows": {
42
+ "test": 593633,
43
+ "train": 58123200,
44
+ "validation": 592771
45
+ },
46
+ "shards": {
47
+ "test": 594,
48
+ "train": 594,
49
+ "validation": 594
50
+ }
51
+ },
52
+ "protein_links": {
53
+ "parser": {
54
+ "bad_rows": 0,
55
+ "chunks": 275414,
56
+ "filtered_rows": 0,
57
+ "parsed_rows": 27541372832
58
+ },
59
+ "rows": {
60
+ "test": 275437468,
61
+ "train": 26990522006,
62
+ "validation": 275413358
63
+ },
64
+ "shards": {
65
+ "test": 275414,
66
+ "train": 275414,
67
+ "validation": 275414
68
+ }
69
+ },
70
+ "protein_sequences": {
71
+ "parser": {
72
+ "bad_rows": 0,
73
+ "chunks": 594,
74
+ "filtered_rows": 0,
75
+ "parsed_rows": 59309604
76
+ },
77
+ "rows": {
78
+ "test": 593633,
79
+ "train": 58123200,
80
+ "validation": 592771
81
+ },
82
+ "shards": {
83
+ "test": 594,
84
+ "train": 594,
85
+ "validation": 594
86
+ }
87
+ },
88
+ "species": {
89
+ "parser": {
90
+ "bad_rows": 0,
91
+ "chunks": 1,
92
+ "filtered_rows": 0,
93
+ "parsed_rows": 12535
94
+ },
95
+ "rows": {
96
+ "test": 157,
97
+ "train": 12261,
98
+ "validation": 117
99
+ },
100
+ "shards": {
101
+ "test": 1,
102
+ "train": 1,
103
+ "validation": 1
104
+ }
105
+ }
106
+ },
107
+ "tables": [
108
+ "species",
109
+ "protein_info",
110
+ "protein_aliases",
111
+ "protein_sequences",
112
+ "protein_links"
113
+ ]
114
+ }
data/protein_links/test-275387.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d24dbf640ffffbd3da221ecd768d60f4912d631ae8c77428dcdc72d4de739bbb
3
+ size 15409
data/protein_links/test-275388.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b00698dc15d4ebaa71908e288782d0305288ebdd7cc42c0991c20a0b2ef79fc
3
+ size 16073
data/protein_links/test-275391.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dcc03485431c5b096769712a986884b582c0f22433b54f7906d89b80eb17ae0d
3
+ size 15737
data/protein_links/test-275393.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d473567dd9cf582112c6a2b6e0220e28ffcc5b16376617d3f199b0e5652d296b
3
+ size 15051
data/protein_links/test-275394.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b418afb6fd1de1fdffe23b646689e16af7ddd6b526956e1653995babc410e853
3
+ size 15450
data/protein_links/test-275395.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05f30519ca3496d4a2ebaddbec113d2ba83570195322494bfd1714e16adbc3d4
3
+ size 15124
data/protein_links/test-275397.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a26ed587086f9a7187dbd6c680d662670ca9cd663b049f7587853c39d9334ce
3
+ size 15804
data/protein_links/test-275398.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b3fb18530adf1213d9fa8b99a6aba773333d4dd64694c5ea5428efde97c4c37
3
+ size 15322
data/protein_links/test-275399.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78098c134977f6ed9ae879c0db5d980a543edf11f2960ec60abd43219a256599
3
+ size 15625
data/protein_links/test-275402.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2940bd1517a114792629586bf13b27153ca0882fb5ea9e8a7e5844bb6d74d0c0
3
+ size 16046
data/protein_links/test-275405.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3ea3444142353c5a036c5f61057ea96fe74782fa3212dcdc5319b779e5ef409
3
+ size 16014
data/protein_links/test-275408.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20b0af36f0a95e3127c9d275a7640c1557930825e9d7e59dea498ee464409d5d
3
+ size 14992
data/protein_links/test-275410.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49a5a127fc9783ed7beb6ec29aa752f84c407c1accaedf03310b097686372488
3
+ size 12498
data/protein_links/test-275411.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b104198ddfd843c724a1222fffea95929a98f63502e48efcfa56d9d5ddc17784
3
+ size 15148
data/protein_links/test-275413.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05544dd32d133506fbd65c9b47a30a7db19c653f5196171db99114145a19c735
3
+ size 15585
data/protein_links/train-275395.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c12ab42380939d5e45f3bb9bf9c58deb6b8fa1e75fb1ffbeb28bdc72fa3a4111
3
+ size 572914
data/protein_links/train-275400.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaf6225c40e77c4a6e8901812572364ed848d89f1199fde1201161385ca0cff8
3
+ size 592384
data/protein_links/train-275402.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60b5a15b7400e194a587dcade8da6cbc0a04c3c1def65a177aebe0687dfc833e
3
+ size 595059
data/protein_links/train-275403.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44dc5b9e977bcd7cc20fe30357b94b14214765fb0a5bdccf08c65d9475d8ebf7
3
+ size 595468
data/protein_links/train-275409.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfbf370408cf1e7b47f8646d37fabd9da539b961a2b5f2868f1d497a7714fb8f
3
+ size 576578
data/protein_links/train-275411.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63504d6439a4cff61aeaa507d34a26afa2a62f0b935ac3fad9d3e17973869310
3
+ size 596608
data/protein_links/train-275412.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:830a76dda467ca502ebee219948375342290438165aba7d4ee946cbf233f2220
3
+ size 585915
data/protein_links/validation-275376.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff272a0211795e58b5ecda0f55601251c6a4236ee144689e25a2c9ff314d09dc
3
+ size 14557
data/protein_links/validation-275384.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d4c0092634bfde1674a634e91d10e43082eb7e3fcf5196e783a67b183128dab
3
+ size 15244
data/protein_links/validation-275387.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf11ca7fb7c6598ca2f9579cf659607ba25471e927bcaa93f9331fddbd2613bc
3
+ size 15683
data/protein_links/validation-275389.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc5d74d47eee44f0f3773d70ea89aade6b96580557be7b817fcd5435cbb89a79
3
+ size 15616
data/protein_links/validation-275390.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f85ba37a940c3b6426db221a112d2ef5e29fb2ab6cb0091a7c88f199a9d32891
3
+ size 15457
data/protein_links/validation-275391.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6cc3d758af1bae53f379b4de838f935245661b73640a4a5aed08a4abc84a3c71
3
+ size 15406
data/protein_links/validation-275393.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc4f13a48a54c94945b339b8d2c4f8bbc448743badfe7349eda5fcb8e2bacfa0
3
+ size 15632
data/protein_links/validation-275395.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b9b0d18cf72e537cb7a7b39ae67dd2285e547353aaaa1294ea9e07a5ee9bb3d
3
+ size 15136
data/protein_links/validation-275396.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7831a1cc949c25782654e24e433f7b4bafa2ce871b8ebacb5729f0d8bc464c3a
3
+ size 15976
data/protein_links/validation-275399.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2997d5ac8275186c5b3c29455f1a47ab1d4f0cc78f46bc14b262d6dc5afc5009
3
+ size 15477
data/protein_links/validation-275400.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1664e11505f94b99ff3a696cad19d4f29e45ff60d1a98c932530281cf0daf49
3
+ size 15732
data/protein_links/validation-275401.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98858d1f07fab09523a46788cd0e6ab43d94ebf7e0e086bf9b0f546030be9600
3
+ size 15654
data/protein_links/validation-275404.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a09bd288cd74380cf29a1035eeef3ecc28dfd190149b3e4534ad521956add7af
3
+ size 15604
data/protein_links/validation-275405.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef0e293d175aefe7b5b64b1be726a78c7cdfe9dc25cd8cb31e79f2876e44fe31
3
+ size 15670
data/protein_links/validation-275406.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:365b8bf84ec58b2414d56e317e174b3b9ecf7c6ee25f435361e19ae8cedeafe6
3
+ size 15652
data/protein_links/validation-275407.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8a534c0b714067c7746e16125bcdee66be237ab36468255b9a282347d0a7305
3
+ size 15187
data/protein_links/validation-275408.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7858860a759ed94111083b569532e459d8db2da383b0a8e6861c5c7a2db1361
3
+ size 15042
data/protein_links/validation-275409.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68b7caabe29bf7c10e3fcbc2ddb6eaf65b2dfade7792ae528b7326d2a92dd977
3
+ size 15077
data/protein_links/validation-275412.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2db3dd759f6ef60115d265dcb00ee3dfec500b91998e6811541cd7575e8736e5
3
+ size 15460
data_preview/processing_summary.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compression": "zstd",
3
+ "link_min_combined_score": null,
4
+ "max_rows_per_table": 1000,
5
+ "num_proc": 4,
6
+ "output_dir": "data_preview",
7
+ "raw_dir": "v12.0",
8
+ "rows_per_chunk": 250,
9
+ "split_ratios": {
10
+ "test": 0.01,
11
+ "train": 0.98,
12
+ "validation": 0.01
13
+ },
14
+ "split_seed": "string-v12.0",
15
+ "stats": {
16
+ "protein_aliases": {
17
+ "parser": {
18
+ "bad_rows": 0,
19
+ "chunks": 4,
20
+ "filtered_rows": 0,
21
+ "parsed_rows": 1000
22
+ },
23
+ "rows": {
24
+ "test": 10,
25
+ "train": 984,
26
+ "validation": 6
27
+ },
28
+ "shards": {
29
+ "test": 4,
30
+ "train": 4,
31
+ "validation": 3
32
+ }
33
+ },
34
+ "protein_info": {
35
+ "parser": {
36
+ "bad_rows": 0,
37
+ "chunks": 4,
38
+ "filtered_rows": 0,
39
+ "parsed_rows": 1000
40
+ },
41
+ "rows": {
42
+ "test": 10,
43
+ "train": 982,
44
+ "validation": 8
45
+ },
46
+ "shards": {
47
+ "test": 4,
48
+ "train": 4,
49
+ "validation": 3
50
+ }
51
+ },
52
+ "protein_links": {
53
+ "parser": {
54
+ "bad_rows": 0,
55
+ "chunks": 4,
56
+ "filtered_rows": 0,
57
+ "parsed_rows": 1000
58
+ },
59
+ "rows": {
60
+ "test": 9,
61
+ "train": 978,
62
+ "validation": 13
63
+ },
64
+ "shards": {
65
+ "test": 4,
66
+ "train": 4,
67
+ "validation": 3
68
+ }
69
+ },
70
+ "protein_sequences": {
71
+ "parser": {
72
+ "bad_rows": 0,
73
+ "chunks": 4,
74
+ "filtered_rows": 0,
75
+ "parsed_rows": 1000
76
+ },
77
+ "rows": {
78
+ "test": 10,
79
+ "train": 982,
80
+ "validation": 8
81
+ },
82
+ "shards": {
83
+ "test": 4,
84
+ "train": 4,
85
+ "validation": 3
86
+ }
87
+ },
88
+ "species": {
89
+ "parser": {
90
+ "bad_rows": 0,
91
+ "chunks": 4,
92
+ "filtered_rows": 0,
93
+ "parsed_rows": 1000
94
+ },
95
+ "rows": {
96
+ "test": 15,
97
+ "train": 978,
98
+ "validation": 7
99
+ },
100
+ "shards": {
101
+ "test": 3,
102
+ "train": 4,
103
+ "validation": 4
104
+ }
105
+ }
106
+ },
107
+ "tables": [
108
+ "species",
109
+ "protein_info",
110
+ "protein_aliases",
111
+ "protein_sequences",
112
+ "protein_links"
113
+ ]
114
+ }
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pyarrow>=14.0.0
2
+ datasets>=2.19.0
3
+ huggingface_hub>=0.23.0
scripts/prepare_hf_dataset.py ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert raw STRING downloads into Hugging Face Data Viewer-friendly Parquet.
3
+
4
+ The converter streams the raw files, assigns rows to deterministic
5
+ train/validation/test splits, and writes sharded Parquet files under:
6
+
7
+ data/<config>/<split>-00000.parquet
8
+
9
+ It is designed for very large STRING files: chunks are parsed in a bounded
10
+ process pool and written incrementally, so the complete dataset is never loaded
11
+ into memory.
12
+ """
13
+
14
+ import argparse
15
+ import gzip
16
+ import io
17
+ import json
18
+ import logging
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import time
23
+ import zlib
24
+ from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
25
+ from contextlib import contextmanager
26
+ from pathlib import Path
27
+ from typing import Dict, Iterator, List, Mapping, Optional, Sequence, Set, Tuple
28
+
29
+
30
+ TABLE_ORDER = (
31
+ "species",
32
+ "protein_info",
33
+ "protein_aliases",
34
+ "protein_sequences",
35
+ "protein_links",
36
+ )
37
+
38
+ RAW_FILES = {
39
+ "species": "species.v12.0.txt",
40
+ "protein_info": "protein.info.v12.0.txt.gz",
41
+ "protein_aliases": "protein.aliases.v12.0.txt.gz",
42
+ "protein_sequences": "protein.sequences.v12.0.fa.gz",
43
+ "protein_links": "protein.links.full.v12.0.txt.gz",
44
+ }
45
+
46
+ COLUMNS = {
47
+ "species": (
48
+ "taxon_id",
49
+ "string_type",
50
+ "string_name_compact",
51
+ "official_name_ncbi",
52
+ "domain",
53
+ ),
54
+ "protein_info": (
55
+ "string_protein_id",
56
+ "taxon_id",
57
+ "preferred_name",
58
+ "protein_size",
59
+ "annotation",
60
+ ),
61
+ "protein_aliases": (
62
+ "string_protein_id",
63
+ "taxon_id",
64
+ "alias",
65
+ "source",
66
+ ),
67
+ "protein_sequences": (
68
+ "string_protein_id",
69
+ "taxon_id",
70
+ "sequence",
71
+ "sequence_length",
72
+ ),
73
+ "protein_links": (
74
+ "protein1",
75
+ "protein2",
76
+ "taxon_id",
77
+ "neighborhood",
78
+ "neighborhood_transferred",
79
+ "fusion",
80
+ "cooccurence",
81
+ "homology",
82
+ "coexpression",
83
+ "coexpression_transferred",
84
+ "experiments",
85
+ "experiments_transferred",
86
+ "database",
87
+ "database_transferred",
88
+ "textmining",
89
+ "textmining_transferred",
90
+ "combined_score",
91
+ ),
92
+ }
93
+
94
+ TYPE_NAMES = {
95
+ "species": (
96
+ "int32",
97
+ "string",
98
+ "string",
99
+ "string",
100
+ "string",
101
+ ),
102
+ "protein_info": (
103
+ "string",
104
+ "int32",
105
+ "string",
106
+ "int32",
107
+ "string",
108
+ ),
109
+ "protein_aliases": (
110
+ "string",
111
+ "int32",
112
+ "string",
113
+ "string",
114
+ ),
115
+ "protein_sequences": (
116
+ "string",
117
+ "int32",
118
+ "string",
119
+ "int32",
120
+ ),
121
+ "protein_links": (
122
+ "string",
123
+ "string",
124
+ "int32",
125
+ "int16",
126
+ "int16",
127
+ "int16",
128
+ "int16",
129
+ "int16",
130
+ "int16",
131
+ "int16",
132
+ "int16",
133
+ "int16",
134
+ "int16",
135
+ "int16",
136
+ "int16",
137
+ "int16",
138
+ "int16",
139
+ ),
140
+ }
141
+
142
+
143
+ def parse_args() -> argparse.Namespace:
144
+ parser = argparse.ArgumentParser(
145
+ description="Post-process STRING v12.0 raw files into sharded Parquet configs."
146
+ )
147
+ parser.add_argument("--raw-dir", type=Path, default=Path("v12.0"))
148
+ parser.add_argument("--output-dir", type=Path, default=Path("data"))
149
+ parser.add_argument(
150
+ "--tables",
151
+ default="all",
152
+ help="Comma-separated table list, or 'all'. Valid tables: %s" % ", ".join(TABLE_ORDER),
153
+ )
154
+ parser.add_argument("--num-proc", type=int, default=32)
155
+ parser.add_argument(
156
+ "--max-in-flight",
157
+ type=int,
158
+ default=None,
159
+ help="Maximum parser chunks queued at once. Defaults to --num-proc.",
160
+ )
161
+ parser.add_argument(
162
+ "--rows-per-chunk",
163
+ type=int,
164
+ default=100_000,
165
+ help="Rows sent to one worker at a time. Lower this if RAM is tight.",
166
+ )
167
+ parser.add_argument("--train-ratio", type=float, default=0.98)
168
+ parser.add_argument("--validation-ratio", type=float, default=0.01)
169
+ parser.add_argument("--test-ratio", type=float, default=0.01)
170
+ parser.add_argument(
171
+ "--split-seed",
172
+ default="string-v12.0",
173
+ help="Stable salt used by the row hash split assignment.",
174
+ )
175
+ parser.add_argument(
176
+ "--link-min-combined-score",
177
+ type=int,
178
+ default=None,
179
+ help="Optional filter for protein_links. Keeps rows with combined_score >= this value.",
180
+ )
181
+ parser.add_argument(
182
+ "--max-rows-per-table",
183
+ type=int,
184
+ default=None,
185
+ help="Optional raw-row cap per table, useful for creating a small preview dataset.",
186
+ )
187
+ parser.add_argument(
188
+ "--compression",
189
+ default="zstd",
190
+ choices=("zstd", "snappy", "gzip", "brotli", "none"),
191
+ help="Parquet compression codec.",
192
+ )
193
+ parser.add_argument(
194
+ "--decompressor",
195
+ default="auto",
196
+ choices=("auto", "python", "gzip", "pigz"),
197
+ help="How to stream .gz files. auto uses pigz when installed, otherwise Python gzip.",
198
+ )
199
+ parser.add_argument(
200
+ "--decompressor-proc",
201
+ type=int,
202
+ default=4,
203
+ help="Threads passed to pigz when --decompressor is pigz/auto and pigz is available.",
204
+ )
205
+ parser.add_argument(
206
+ "--overwrite",
207
+ action="store_true",
208
+ help="Delete existing output subdirectories for selected tables before writing.",
209
+ )
210
+ parser.add_argument("--log-every", type=int, default=25)
211
+ return parser.parse_args()
212
+
213
+
214
+ def resolve_tables(value: str) -> List[str]:
215
+ if value == "all":
216
+ return list(TABLE_ORDER)
217
+ selected = [item.strip() for item in value.split(",") if item.strip()]
218
+ unknown = sorted(set(selected) - set(TABLE_ORDER))
219
+ if unknown:
220
+ raise ValueError("Unknown table(s): %s" % ", ".join(unknown))
221
+ return selected
222
+
223
+
224
+ def split_cutoffs(train_ratio: float, validation_ratio: float, test_ratio: float) -> Tuple[int, int]:
225
+ total = train_ratio + validation_ratio + test_ratio
226
+ if abs(total - 1.0) > 1e-9:
227
+ raise ValueError("Split ratios must sum to 1.0, got %.8f" % total)
228
+ train_cutoff = int(train_ratio * (2**32))
229
+ validation_cutoff = int((train_ratio + validation_ratio) * (2**32))
230
+ return train_cutoff, validation_cutoff
231
+
232
+
233
+ def seed_crc(seed: str) -> int:
234
+ return zlib.crc32(seed.encode("utf-8")) & 0xFFFFFFFF
235
+
236
+
237
+ def assign_split(key: str, seed_value: int, cutoffs: Tuple[int, int]) -> str:
238
+ value = zlib.crc32(key.encode("utf-8"), seed_value) & 0xFFFFFFFF
239
+ if value < cutoffs[0]:
240
+ return "train"
241
+ if value < cutoffs[1]:
242
+ return "validation"
243
+ return "test"
244
+
245
+
246
+ def taxon_from_protein_id(protein_id: str) -> int:
247
+ return int(protein_id.split(".", 1)[0])
248
+
249
+
250
+ @contextmanager
251
+ def open_text(path: Path, decompressor: str, decompressor_proc: int) -> Iterator[io.TextIOBase]:
252
+ if path.suffix != ".gz":
253
+ with path.open("rt", encoding="utf-8", newline="") as handle:
254
+ yield handle
255
+ return
256
+
257
+ if decompressor == "pigz" and not shutil.which("pigz"):
258
+ raise RuntimeError("Requested --decompressor pigz, but pigz is not installed")
259
+
260
+ use_pigz = decompressor == "pigz" or (decompressor == "auto" and shutil.which("pigz"))
261
+ use_gzip_cmd = decompressor == "gzip"
262
+
263
+ if use_pigz:
264
+ cmd = ["pigz", "-dc", "-p", str(max(1, decompressor_proc)), str(path)]
265
+ elif use_gzip_cmd:
266
+ cmd = ["gzip", "-cd", str(path)]
267
+ else:
268
+ with gzip.open(path, "rt", encoding="utf-8", newline="") as handle:
269
+ yield handle
270
+ return
271
+
272
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
273
+ assert proc.stdout is not None
274
+ handle = io.TextIOWrapper(proc.stdout, encoding="utf-8", newline="")
275
+ try:
276
+ yield handle
277
+ finally:
278
+ handle.close()
279
+ return_code = proc.wait()
280
+ if return_code != 0:
281
+ raise RuntimeError("Decompressor failed with exit code %s: %s" % (return_code, " ".join(cmd)))
282
+
283
+
284
+ def iter_text_chunks(
285
+ path: Path,
286
+ rows_per_chunk: int,
287
+ max_rows: Optional[int],
288
+ decompressor: str,
289
+ decompressor_proc: int,
290
+ ) -> Iterator[Tuple[int, List[str]]]:
291
+ with open_text(path, decompressor, decompressor_proc) as handle:
292
+ header = next(handle, None)
293
+ if header is None:
294
+ return
295
+
296
+ chunk: List[str] = []
297
+ chunk_id = 0
298
+ seen = 0
299
+ for line in handle:
300
+ if max_rows is not None and seen >= max_rows:
301
+ break
302
+ chunk.append(line)
303
+ seen += 1
304
+ if len(chunk) >= rows_per_chunk:
305
+ yield chunk_id, chunk
306
+ chunk_id += 1
307
+ chunk = []
308
+
309
+ if chunk:
310
+ yield chunk_id, chunk
311
+
312
+
313
+ def iter_fasta_records(
314
+ path: Path,
315
+ max_rows: Optional[int],
316
+ decompressor: str,
317
+ decompressor_proc: int,
318
+ ) -> Iterator[Tuple[str, str]]:
319
+ yielded = 0
320
+ protein_id: Optional[str] = None
321
+ parts: List[str] = []
322
+
323
+ with open_text(path, decompressor, decompressor_proc) as handle:
324
+ for raw_line in handle:
325
+ line = raw_line.strip()
326
+ if not line:
327
+ continue
328
+ if line.startswith(">"):
329
+ if protein_id is not None:
330
+ yield protein_id, "".join(parts)
331
+ yielded += 1
332
+ if max_rows is not None and yielded >= max_rows:
333
+ return
334
+ protein_id = line[1:].split(None, 1)[0]
335
+ parts = []
336
+ else:
337
+ parts.append(line)
338
+
339
+ if protein_id is not None and (max_rows is None or yielded < max_rows):
340
+ yield protein_id, "".join(parts)
341
+
342
+
343
+ def iter_sequence_chunks(
344
+ path: Path,
345
+ rows_per_chunk: int,
346
+ max_rows: Optional[int],
347
+ decompressor: str,
348
+ decompressor_proc: int,
349
+ ) -> Iterator[Tuple[int, List[Tuple[str, str]]]]:
350
+ chunk: List[Tuple[str, str]] = []
351
+ chunk_id = 0
352
+ for record in iter_fasta_records(path, max_rows, decompressor, decompressor_proc):
353
+ chunk.append(record)
354
+ if len(chunk) >= rows_per_chunk:
355
+ yield chunk_id, chunk
356
+ chunk_id += 1
357
+ chunk = []
358
+ if chunk:
359
+ yield chunk_id, chunk
360
+
361
+
362
+ def empty_buckets(table: str) -> Dict[str, List[List[object]]]:
363
+ width = len(COLUMNS[table])
364
+ return {
365
+ "train": [[] for _ in range(width)],
366
+ "validation": [[] for _ in range(width)],
367
+ "test": [[] for _ in range(width)],
368
+ }
369
+
370
+
371
+ def append_row(bucket: List[List[object]], values: Sequence[object]) -> None:
372
+ for index, value in enumerate(values):
373
+ bucket[index].append(value)
374
+
375
+
376
+ def parse_species_line(line: str) -> Tuple[str, Tuple[object, ...]]:
377
+ fields = line.rstrip("\n").split("\t")
378
+ if len(fields) != 5:
379
+ raise ValueError("expected 5 fields")
380
+ taxon_id = int(fields[0])
381
+ return str(taxon_id), (taxon_id, fields[1], fields[2], fields[3], fields[4])
382
+
383
+
384
+ def parse_protein_info_line(line: str) -> Tuple[str, Tuple[object, ...]]:
385
+ fields = line.rstrip("\n").split("\t", 3)
386
+ if len(fields) != 4:
387
+ raise ValueError("expected 4 fields")
388
+ protein_id = fields[0]
389
+ taxon_id = taxon_from_protein_id(protein_id)
390
+ return protein_id, (protein_id, taxon_id, fields[1], int(fields[2]), fields[3])
391
+
392
+
393
+ def parse_alias_line(line: str) -> Tuple[str, Tuple[object, ...]]:
394
+ fields = line.rstrip("\n").split("\t", 2)
395
+ if len(fields) != 3:
396
+ raise ValueError("expected 3 fields")
397
+ protein_id = fields[0]
398
+ taxon_id = taxon_from_protein_id(protein_id)
399
+ key = "%s\t%s\t%s" % (protein_id, fields[1], fields[2])
400
+ return key, (protein_id, taxon_id, fields[1], fields[2])
401
+
402
+
403
+ def parse_link_line(line: str, min_combined_score: Optional[int]) -> Optional[Tuple[str, Tuple[object, ...]]]:
404
+ fields = line.rstrip("\n").split()
405
+ if len(fields) != 16:
406
+ raise ValueError("expected 16 fields")
407
+ combined_score = int(fields[15])
408
+ if min_combined_score is not None and combined_score < min_combined_score:
409
+ return None
410
+ protein1 = fields[0]
411
+ protein2 = fields[1]
412
+ taxon_id = taxon_from_protein_id(protein1)
413
+ scores = tuple(int(value) for value in fields[2:15])
414
+ key = "%s\t%s" % (protein1, protein2)
415
+ return key, (protein1, protein2, taxon_id) + scores + (combined_score,)
416
+
417
+
418
+ def process_text_chunk(
419
+ table: str,
420
+ chunk_id: int,
421
+ lines: Sequence[str],
422
+ seed_value: int,
423
+ cutoffs: Tuple[int, int],
424
+ min_combined_score: Optional[int],
425
+ ) -> Dict[str, object]:
426
+ buckets = empty_buckets(table)
427
+ bad_rows = 0
428
+ filtered_rows = 0
429
+ parsed_rows = 0
430
+
431
+ for line in lines:
432
+ if not line.strip():
433
+ continue
434
+ try:
435
+ if table == "species":
436
+ parsed = parse_species_line(line)
437
+ elif table == "protein_info":
438
+ parsed = parse_protein_info_line(line)
439
+ elif table == "protein_aliases":
440
+ parsed = parse_alias_line(line)
441
+ elif table == "protein_links":
442
+ parsed = parse_link_line(line, min_combined_score)
443
+ else:
444
+ raise ValueError("unsupported text table %s" % table)
445
+ except Exception:
446
+ bad_rows += 1
447
+ continue
448
+
449
+ if parsed is None:
450
+ filtered_rows += 1
451
+ continue
452
+
453
+ key, values = parsed
454
+ split = assign_split(key, seed_value, cutoffs)
455
+ append_row(buckets[split], values)
456
+ parsed_rows += 1
457
+
458
+ return {
459
+ "table": table,
460
+ "chunk_id": chunk_id,
461
+ "buckets": buckets,
462
+ "parsed_rows": parsed_rows,
463
+ "bad_rows": bad_rows,
464
+ "filtered_rows": filtered_rows,
465
+ }
466
+
467
+
468
+ def process_sequence_chunk(
469
+ chunk_id: int,
470
+ records: Sequence[Tuple[str, str]],
471
+ seed_value: int,
472
+ cutoffs: Tuple[int, int],
473
+ ) -> Dict[str, object]:
474
+ table = "protein_sequences"
475
+ buckets = empty_buckets(table)
476
+ bad_rows = 0
477
+ parsed_rows = 0
478
+
479
+ for protein_id, sequence in records:
480
+ try:
481
+ taxon_id = taxon_from_protein_id(protein_id)
482
+ except Exception:
483
+ bad_rows += 1
484
+ continue
485
+ values = (protein_id, taxon_id, sequence, len(sequence))
486
+ split = assign_split(protein_id, seed_value, cutoffs)
487
+ append_row(buckets[split], values)
488
+ parsed_rows += 1
489
+
490
+ return {
491
+ "table": table,
492
+ "chunk_id": chunk_id,
493
+ "buckets": buckets,
494
+ "parsed_rows": parsed_rows,
495
+ "bad_rows": bad_rows,
496
+ "filtered_rows": 0,
497
+ }
498
+
499
+
500
+ def import_arrow():
501
+ try:
502
+ import pyarrow as pa
503
+ import pyarrow.parquet as pq
504
+ except ImportError as exc:
505
+ raise SystemExit(
506
+ "pyarrow is required. Install dependencies with: python -m pip install -r requirements.txt"
507
+ ) from exc
508
+ return pa, pq
509
+
510
+
511
+ def arrow_type(pa, type_name: str):
512
+ if type_name == "string":
513
+ return pa.string()
514
+ if type_name == "int16":
515
+ return pa.int16()
516
+ if type_name == "int32":
517
+ return pa.int32()
518
+ raise ValueError("unsupported type %s" % type_name)
519
+
520
+
521
+ def arrow_schema(pa, table: str):
522
+ return pa.schema(
523
+ [pa.field(name, arrow_type(pa, type_name)) for name, type_name in zip(COLUMNS[table], TYPE_NAMES[table])]
524
+ )
525
+
526
+
527
+ class ParquetSink:
528
+ def __init__(self, output_dir: Path, compression: str):
529
+ self.output_dir = output_dir
530
+ self.compression = None if compression == "none" else compression
531
+ self.pa, self.pq = import_arrow()
532
+ self.schemas = {table: arrow_schema(self.pa, table) for table in TABLE_ORDER}
533
+ self.shard_counts: Dict[str, Dict[str, int]] = {
534
+ table: {"train": 0, "validation": 0, "test": 0} for table in TABLE_ORDER
535
+ }
536
+ self.row_counts: Dict[str, Dict[str, int]] = {
537
+ table: {"train": 0, "validation": 0, "test": 0} for table in TABLE_ORDER
538
+ }
539
+
540
+ def write_buckets(self, table: str, buckets: Mapping[str, Sequence[Sequence[object]]]) -> None:
541
+ table_dir = self.output_dir / table
542
+ table_dir.mkdir(parents=True, exist_ok=True)
543
+
544
+ for split in ("train", "validation", "test"):
545
+ column_lists = buckets[split]
546
+ row_count = len(column_lists[0]) if column_lists else 0
547
+ if row_count == 0:
548
+ continue
549
+
550
+ data = {name: column_lists[index] for index, name in enumerate(COLUMNS[table])}
551
+ arrow_table = self.pa.Table.from_pydict(data, schema=self.schemas[table])
552
+ shard_id = self.shard_counts[table][split]
553
+ output_path = table_dir / ("%s-%05d.parquet" % (split, shard_id))
554
+ self.pq.write_table(
555
+ arrow_table,
556
+ output_path,
557
+ compression=self.compression,
558
+ use_dictionary=True,
559
+ write_statistics=True,
560
+ )
561
+ self.shard_counts[table][split] += 1
562
+ self.row_counts[table][split] += row_count
563
+
564
+
565
+ def prepare_output_dirs(output_dir: Path, tables: Sequence[str], overwrite: bool) -> None:
566
+ output_dir.mkdir(parents=True, exist_ok=True)
567
+ for table in tables:
568
+ table_dir = output_dir / table
569
+ if not table_dir.exists():
570
+ continue
571
+ if not overwrite:
572
+ raise SystemExit(
573
+ "Output directory already exists: %s. Re-run with --overwrite or choose another --output-dir."
574
+ % table_dir
575
+ )
576
+ shutil.rmtree(table_dir)
577
+
578
+
579
+ def handle_result(result: Mapping[str, object], sink: ParquetSink, stats: Dict[str, Dict[str, int]]) -> None:
580
+ table = str(result["table"])
581
+ sink.write_buckets(table, result["buckets"]) # type: ignore[arg-type]
582
+ stats[table]["parsed_rows"] += int(result["parsed_rows"])
583
+ stats[table]["bad_rows"] += int(result["bad_rows"])
584
+ stats[table]["filtered_rows"] += int(result["filtered_rows"])
585
+ stats[table]["chunks"] += 1
586
+
587
+
588
+ def drain_one(
589
+ pending: Set[object],
590
+ sink: ParquetSink,
591
+ stats: Dict[str, Dict[str, int]],
592
+ ) -> Set[object]:
593
+ done, still_pending = wait(pending, return_when=FIRST_COMPLETED)
594
+ for future in done:
595
+ handle_result(future.result(), sink, stats)
596
+ return set(still_pending)
597
+
598
+
599
+ def drain_all(
600
+ pending: Set[object],
601
+ sink: ParquetSink,
602
+ stats: Dict[str, Dict[str, int]],
603
+ ) -> None:
604
+ while pending:
605
+ pending = drain_one(pending, sink, stats)
606
+
607
+
608
+ def chunk_iterator(
609
+ table: str,
610
+ path: Path,
611
+ rows_per_chunk: int,
612
+ max_rows: Optional[int],
613
+ decompressor: str,
614
+ decompressor_proc: int,
615
+ ) -> Iterator[Tuple[int, object]]:
616
+ if max_rows is not None and decompressor == "auto":
617
+ decompressor = "python"
618
+ if table == "protein_sequences":
619
+ yield from iter_sequence_chunks(path, rows_per_chunk, max_rows, decompressor, decompressor_proc)
620
+ else:
621
+ yield from iter_text_chunks(path, rows_per_chunk, max_rows, decompressor, decompressor_proc)
622
+
623
+
624
+ def process_table(
625
+ executor: ProcessPoolExecutor,
626
+ sink: ParquetSink,
627
+ table: str,
628
+ raw_path: Path,
629
+ args: argparse.Namespace,
630
+ seed_value: int,
631
+ cutoffs: Tuple[int, int],
632
+ stats: Dict[str, Dict[str, int]],
633
+ ) -> None:
634
+ logging.info("Processing %s from %s", table, raw_path)
635
+ started = time.time()
636
+ pending: Set[object] = set()
637
+ max_in_flight = args.max_in_flight or args.num_proc
638
+
639
+ for chunk_id, chunk in chunk_iterator(
640
+ table,
641
+ raw_path,
642
+ args.rows_per_chunk,
643
+ args.max_rows_per_table,
644
+ args.decompressor,
645
+ args.decompressor_proc,
646
+ ):
647
+ if table == "protein_sequences":
648
+ future = executor.submit(process_sequence_chunk, chunk_id, chunk, seed_value, cutoffs)
649
+ else:
650
+ future = executor.submit(
651
+ process_text_chunk,
652
+ table,
653
+ chunk_id,
654
+ chunk,
655
+ seed_value,
656
+ cutoffs,
657
+ args.link_min_combined_score,
658
+ )
659
+ pending.add(future)
660
+
661
+ if len(pending) >= max_in_flight:
662
+ pending = drain_one(pending, sink, stats)
663
+
664
+ submitted = chunk_id + 1
665
+ if args.log_every and submitted % args.log_every == 0:
666
+ logging.info("%s: submitted %d chunks", table, submitted)
667
+
668
+ drain_all(pending, sink, stats)
669
+ elapsed = time.time() - started
670
+ logging.info(
671
+ "Finished %s in %.1fs: %s rows, %s bad rows, %s filtered rows",
672
+ table,
673
+ elapsed,
674
+ stats[table]["parsed_rows"],
675
+ stats[table]["bad_rows"],
676
+ stats[table]["filtered_rows"],
677
+ )
678
+
679
+
680
+ def write_summary(
681
+ output_dir: Path,
682
+ tables: Sequence[str],
683
+ args: argparse.Namespace,
684
+ sink: ParquetSink,
685
+ stats: Mapping[str, Mapping[str, int]],
686
+ ) -> None:
687
+ summary = {
688
+ "raw_dir": str(args.raw_dir),
689
+ "output_dir": str(args.output_dir),
690
+ "tables": list(tables),
691
+ "num_proc": args.num_proc,
692
+ "rows_per_chunk": args.rows_per_chunk,
693
+ "split_ratios": {
694
+ "train": args.train_ratio,
695
+ "validation": args.validation_ratio,
696
+ "test": args.test_ratio,
697
+ },
698
+ "split_seed": args.split_seed,
699
+ "link_min_combined_score": args.link_min_combined_score,
700
+ "max_rows_per_table": args.max_rows_per_table,
701
+ "compression": args.compression,
702
+ "stats": {
703
+ table: {
704
+ "parser": dict(stats[table]),
705
+ "rows": dict(sink.row_counts[table]),
706
+ "shards": dict(sink.shard_counts[table]),
707
+ }
708
+ for table in tables
709
+ },
710
+ }
711
+ path = output_dir / "processing_summary.json"
712
+ path.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8")
713
+ logging.info("Wrote %s", path)
714
+
715
+
716
+ def main() -> int:
717
+ logging.basicConfig(
718
+ level=logging.INFO,
719
+ format="%(asctime)s %(levelname)s %(message)s",
720
+ datefmt="%H:%M:%S",
721
+ )
722
+ args = parse_args()
723
+ tables = resolve_tables(args.tables)
724
+
725
+ if args.num_proc < 1:
726
+ raise SystemExit("--num-proc must be >= 1")
727
+ if args.rows_per_chunk < 1:
728
+ raise SystemExit("--rows-per-chunk must be >= 1")
729
+ if args.max_in_flight is not None and args.max_in_flight < 1:
730
+ raise SystemExit("--max-in-flight must be >= 1")
731
+
732
+ cutoffs = split_cutoffs(args.train_ratio, args.validation_ratio, args.test_ratio)
733
+ seed_value = seed_crc(args.split_seed)
734
+
735
+ for table in tables:
736
+ raw_path = args.raw_dir / RAW_FILES[table]
737
+ if not raw_path.exists():
738
+ raise SystemExit("Missing raw file for %s: %s" % (table, raw_path))
739
+
740
+ prepare_output_dirs(args.output_dir, tables, args.overwrite)
741
+ sink = ParquetSink(args.output_dir, args.compression)
742
+
743
+ try:
744
+ sink.pa.set_cpu_count(args.num_proc)
745
+ except AttributeError:
746
+ pass
747
+
748
+ stats: Dict[str, Dict[str, int]] = {
749
+ table: {"chunks": 0, "parsed_rows": 0, "bad_rows": 0, "filtered_rows": 0} for table in TABLE_ORDER
750
+ }
751
+
752
+ logging.info("Using %d worker processes", args.num_proc)
753
+ with ProcessPoolExecutor(max_workers=args.num_proc) as executor:
754
+ for table in tables:
755
+ raw_path = args.raw_dir / RAW_FILES[table]
756
+ process_table(executor, sink, table, raw_path, args, seed_value, cutoffs, stats)
757
+
758
+ write_summary(args.output_dir, tables, args, sink, stats)
759
+ return 0
760
+
761
+
762
+ if __name__ == "__main__":
763
+ sys.exit(main())
scripts/validate_hf_dataset.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Smoke-test generated STRING Parquet configs with the Hugging Face datasets API."""
3
+
4
+ import argparse
5
+ import glob
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Dict, List
9
+
10
+
11
+ CONFIGS = (
12
+ "species",
13
+ "protein_info",
14
+ "protein_aliases",
15
+ "protein_sequences",
16
+ "protein_links",
17
+ )
18
+
19
+ SPLITS = ("train", "validation", "test")
20
+
21
+
22
+ def parse_args() -> argparse.Namespace:
23
+ parser = argparse.ArgumentParser(description="Validate local or uploaded STRING HF dataset configs.")
24
+ parser.add_argument(
25
+ "--repo-id",
26
+ default=None,
27
+ help="Optional HF dataset repo id, for example LiteFold/STRING. If omitted, validates local Parquet.",
28
+ )
29
+ parser.add_argument("--data-dir", type=Path, default=Path("data"))
30
+ parser.add_argument("--config", choices=CONFIGS, default="protein_links")
31
+ parser.add_argument("--split", default="train")
32
+ parser.add_argument("--streaming", action="store_true")
33
+ parser.add_argument("--preview-rows", type=int, default=3)
34
+ return parser.parse_args()
35
+
36
+
37
+ def local_data_files(data_dir: Path, config: str) -> Dict[str, List[str]]:
38
+ files: Dict[str, List[str]] = {}
39
+ for split in SPLITS:
40
+ pattern = str(data_dir / config / ("%s-*.parquet" % split))
41
+ matches = sorted(glob.glob(pattern))
42
+ if matches:
43
+ files[split] = matches
44
+ if not files:
45
+ raise SystemExit("No local Parquet files found for config %s under %s" % (config, data_dir))
46
+ return files
47
+
48
+
49
+ def main() -> int:
50
+ args = parse_args()
51
+ try:
52
+ from datasets import load_dataset
53
+ except ImportError as exc:
54
+ raise SystemExit(
55
+ "datasets is required. Install dependencies with: python -m pip install -r requirements.txt"
56
+ ) from exc
57
+
58
+ if args.repo_id:
59
+ dataset = load_dataset(args.repo_id, args.config, split=args.split, streaming=args.streaming)
60
+ else:
61
+ files = local_data_files(args.data_dir, args.config)
62
+ if args.split not in files:
63
+ raise SystemExit(
64
+ "Split %s is not present locally for config %s. Available splits: %s"
65
+ % (args.split, args.config, ", ".join(sorted(files)))
66
+ )
67
+ dataset = load_dataset("parquet", data_files=files, split=args.split, streaming=args.streaming)
68
+
69
+ print("config:", args.config)
70
+ print("split:", args.split)
71
+ print("features:", dataset.features)
72
+
73
+ if args.streaming:
74
+ iterator = iter(dataset)
75
+ for index in range(args.preview_rows):
76
+ try:
77
+ print("row[%d]:" % index, next(iterator))
78
+ except StopIteration:
79
+ break
80
+ else:
81
+ print("num_rows:", len(dataset))
82
+ for index in range(min(args.preview_rows, len(dataset))):
83
+ print("row[%d]:" % index, dataset[index])
84
+
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ sys.exit(main())