-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy path0.download_data.py
225 lines (196 loc) · 6.38 KB
/
0.download_data.py
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import argparse
import boto3
import csv
import datasets
import logging
import os
import pyfastx
import random
import requests
import tempfile
import tqdm
from urllib.parse import urlparse
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
def parse_args():
"""Parse the arguments."""
logging.info("Parsing arguments")
parser = argparse.ArgumentParser()
parser.add_argument(
"--max_records_per_partition",
type=int,
default=500000,
help="Max number of sequence records per csv partition",
)
parser.add_argument(
"--output_dir",
type=str,
default=os.getcwd(),
help="Output dir for processed files",
)
parser.add_argument(
"--save_arrow",
type=bool,
default=False,
help="Save Apache Arrow files to output dir?",
)
parser.add_argument(
"--save_csv",
type=bool,
default=True,
help="Save csv files to output dir?",
)
parser.add_argument(
"--save_fasta",
type=bool,
default=False,
help="Save FASTA file to output dir?",
)
parser.add_argument(
"--save_parquet",
type=bool,
default=False,
help="Save Apache Parquet files to output dir?",
)
parser.add_argument(
"--shuffle",
type=bool,
default=True,
help="Shuffle the records in each csv partition?",
)
parser.add_argument(
"--source",
type=str,
default="https://ftp.uniprot.org/pub/databases/uniprot/uniref/uniref50/uniref50.fasta.gz",
help="Path to input .fasta or .fasta.gz file, e.g. s3://myfasta.fa, http://myfasta.fasta.gz, ~/myfasta.fasta, etc",
)
args, _ = parser.parse_known_args()
return args
def main(args):
"""Transform fasta file into dataset"""
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
tmp_dir = tempfile.TemporaryDirectory(dir=os.getcwd())
logging.info("Downloading FASTA")
fasta_dir = (
os.path.join(args.output_dir, "fasta")
if args.save_fasta
else os.path.join(tmp_dir.name, "fasta")
)
fasta_path = download(args.source, fasta_dir)
logging.info("Generating csv files")
csv_dir = (
os.path.join(args.output_dir, "csv")
if args.save_csv
else os.path.join(tmp_dir.name, "csv")
)
csv_path = fasta_to_csv(
fasta_path, csv_dir, args.max_records_per_partition
)
if args.save_arrow or args.save_parquet:
logging.info("Loading csv files into dataset")
ds = datasets.load_dataset(
"csv",
data_dir=csv_path,
num_proc=os.cpu_count(),
cache_dir=os.path.join(tmp_dir.name, "dataset_cache"),
)
logging.info("Saving dataset in Arrow format")
if args.save_arrow:
ds.save_to_disk(os.path.join(args.output_dir, "arrow"))
logging.info("Saving dataset in Parquet format")
if args.save_parquet:
for split in ds.keys():
ds[split].to_parquet(
f"{os.path.join(args.output_dir, 'parquet')}/data.parquet"
)
tmp_dir.cleanup()
logging.info("Save complete")
return args.output_dir
def download(source: str, filename: str) -> str:
logging.info(f"Downloading {source} to {filename}")
output_dir = os.path.dirname(filename)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if source.startswith("s3"):
s3 = boto3.client("s3")
parsed = urlparse(source, allow_fragments=False)
bucket = parsed.netloc
key = parsed.path[1:]
total = s3.head_object(Bucket=bucket, Key=key)["ContentLength"]
tqdm_params = {
"desc": source,
"total": total,
"miniters": 1,
"unit": "B",
"unit_scale": True,
"unit_divisor": 1024,
}
with tqdm.tqdm(**tqdm_params) as pb:
s3.download_file(
parsed.netloc,
parsed.path[1:],
filename,
Callback=lambda bytes_transferred: pb.update(bytes_transferred),
)
elif source.startswith("http"):
with open(filename, "wb") as f:
with requests.get(source, stream=True) as r:
r.raise_for_status()
total = int(r.headers.get("content-length", 0))
tqdm_params = {
"desc": source,
"total": total,
"miniters": 1,
"unit": "B",
"unit_scale": True,
"unit_divisor": 1024,
}
with tqdm.tqdm(**tqdm_params) as pb:
for chunk in r.iter_content(chunk_size=8192):
pb.update(len(chunk))
f.write(chunk)
elif os.path.isfile(source):
logging.info(f"{source} already exists")
else:
raise ValueError(f"Invalid source: {source}")
return filename
def fasta_to_csv(
fasta: str,
output_dir: str = "csv",
max_records_per_partition=2000000,
shuffle=False,
) -> list:
"""Split a .fasta or .fasta.gz file into multiple .csv files."""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print("Reading FASTA file")
fasta_list = []
fasta_idx = 0
for i, seq in tqdm.tqdm(
enumerate(pyfastx.Fasta(fasta, build_index=False, uppercase=True))
):
fasta_list.append(seq)
if (i + 1) % max_records_per_partition == 0:
if shuffle:
random.shuffle(fasta_list)
fasta_idx = int(i / max_records_per_partition)
_write_seq_record_to_csv(fasta_list, output_dir, fasta_idx)
fasta_list = []
else:
_write_seq_record_to_csv(fasta_list, output_dir, fasta_idx + 1)
return output_dir
def _write_seq_record_to_csv(content_list, output_dir, index):
output_path = os.path.join(output_dir, f"x{str(index).rjust(3, '0')}.csv")
logging.info(f"Writing {len(content_list)} records to {output_path}")
with open(output_path, "w") as f:
writer = csv.writer(f)
writer.writerow(("id", "text"))
writer.writerows(content_list)
return None
if __name__ == "__main__":
args = parse_args()
main(args)