-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws_download.py
189 lines (160 loc) · 5.45 KB
/
aws_download.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
import concurrent.futures
import logging
import multiprocessing
from pathlib import Path
from urllib.parse import urlparse
import boto3
def parse_s3_uri(s3_uri: str) -> tuple[str, str]:
"""
Parse an S3 URI into bucket name and key
Args:
s3_uri: URI in format s3://bucket-name/path/to/file
Returns:
Tuple of (bucket_name, key)
"""
parsed = urlparse(s3_uri)
bucket = parsed.netloc
key = parsed.path.lstrip("/")
return bucket, key
def read_pmid_locations(filepath: str) -> list[dict[str, str]]:
"""
Read the PMID locations file and return list of file info dicts
Args:
filepath: Path to the file containing PMID,S3_URI pairs
Returns:
List of dicts with s3_key and local_name for each file
"""
file_manifest = []
with open(filepath) as f:
for line in f:
if not line.strip():
continue
try:
pmid, s3_uri = line.strip().split(",")
bucket, key = parse_s3_uri(s3_uri)
# Create subdirectory path based on first 3 digits of PMID
subdir = pmid[:3] if len(pmid) >= 3 else "other"
file_manifest.append(
{
"s3_key": key,
"local_name": f"{subdir}/{pmid}.pdf",
"pmid": pmid,
}
)
except ValueError:
logging.warning(f"Skipping malformed line: {line.strip()}")
return file_manifest
def download_file(
file_info: dict[str, str], bucket_name: str, local_dir: Path
) -> bool:
"""
Download a single file from S3
Args:
file_info: Dict containing 's3_key' and 'local_name' for the file
bucket_name: Name of the S3 bucket
local_dir: Local directory to save files
"""
s3_client = boto3.client("s3")
try:
local_path = local_dir / file_info["local_name"]
local_path.parent.mkdir(parents=True, exist_ok=True)
s3_client.download_file(
Bucket=bucket_name,
Key=file_info["s3_key"],
Filename=str(local_path),
)
logging.info(
f"Successfully downloaded PMID {file_info['pmid']}"
+ f" to {file_info['local_name']}"
)
return True
except Exception:
try:
# add in a / to the prefix
parts = file_info["s3_key"].split("/")
amended_key = "//".join(parts)
s3_client.download_file(
Bucket=bucket_name,
Key=amended_key,
Filename=str(local_path),
)
except Exception as e:
logging.error(
f"Failed to download PMID {file_info['pmid']}"
+ f" ({file_info['s3_key']}): {str(e)}"
)
return False
def parallel_download(
file_manifest: list[dict[str, str]],
bucket_name: str,
local_dir: str,
max_workers: int = 16,
) -> None:
"""
Download multiple files in parallel from S3
Args:
file_manifest: List of dicts containing file information
bucket_name: Name of the S3 bucket
local_dir: Local directory to save files
max_workers: Number of concurrent downloads
"""
local_path = Path(local_dir)
local_path.mkdir(parents=True, exist_ok=True)
success_count = 0
failure_count = 0
with concurrent.futures.ThreadPoolExecutor(
max_workers=max_workers
) as executor:
# Submit all download tasks
future_to_file = {
executor.submit(
download_file, file_info, bucket_name, local_path
): file_info
for file_info in file_manifest
}
# Process completed downloads
for future in concurrent.futures.as_completed(future_to_file):
file_info = future_to_file[future]
try:
if future.result():
success_count += 1
else:
failure_count += 1
except Exception as e:
logging.error(
f"Exception downloading {file_info['s3_key']}: {str(e)}"
)
failure_count += 1
logging.info(
"Download complete. Successes:"
+ f" {success_count}, Failures: {failure_count}"
)
# Add this function to get optimal worker count
def get_optimal_worker_count() -> int:
"""
Calculate optimal number of workers based on CPU count.
Returns a value between 4 and 32.
"""
cpu_count = multiprocessing.cpu_count()
# Use 2x CPU count for I/O bound tasks, but cap between 4 and 32
worker_count = min(max(cpu_count * 2, 4), 32)
return worker_count
if __name__ == "__main__":
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
# Read the PMID locations file
file_manifest = read_pmid_locations("found_pmids.txt")
# Get bucket name from first entry
_, first_uri = next(open("found_pmids.txt")).strip().split(",")
bucket_name, _ = parse_s3_uri(first_uri)
logging.info(f"Found {len(file_manifest)} files to download")
max_workers = get_optimal_worker_count()
logging.info(f"Using {max_workers} workers based on system CPU count")
parallel_download(
file_manifest=file_manifest[:100],
bucket_name=bucket_name,
local_dir="downloaded_pdfs",
max_workers=max_workers,
)