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|
+
import json
|
| 2 |
+
import tarfile
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from urllib.parse import urlparse
|
| 5 |
+
import requests
|
| 6 |
+
from typing import List, Union, Dict, Optional
|
| 7 |
+
import click
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BioAgentDataset:
|
| 11 |
+
"""Download and manage bioinformatics benchmark datasets."""
|
| 12 |
+
|
| 13 |
+
def __init__(self, metadata_path: str = "src/task_metadata.json", base_dir: Union[str, Path] = "tasks"):
|
| 14 |
+
"""Initialize with path to task metadata JSON file."""
|
| 15 |
+
self.metadata_path = Path(metadata_path)
|
| 16 |
+
self.tasks = self._load_metadata()
|
| 17 |
+
self.base_dir = Path(base_dir)
|
| 18 |
+
|
| 19 |
+
def _load_metadata(self) -> List[dict]:
|
| 20 |
+
"""Load task metadata from JSON file."""
|
| 21 |
+
with open(self.metadata_path, 'r') as f:
|
| 22 |
+
return json.load(f)
|
| 23 |
+
|
| 24 |
+
def _get_task(self, task_id: str) -> dict:
|
| 25 |
+
"""Get task metadata by task_id."""
|
| 26 |
+
for task in self.tasks:
|
| 27 |
+
if task["task_id"] == task_id:
|
| 28 |
+
return task
|
| 29 |
+
raise ValueError(f"Task '{task_id}' not found")
|
| 30 |
+
|
| 31 |
+
def _download_file(self, url: str, output_path: Path) -> bool:
|
| 32 |
+
"""Download a single file from URL to output_path."""
|
| 33 |
+
if not url or url.strip() == "":
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
if output_path.exists():
|
| 37 |
+
print(f"File already exists: {output_path}")
|
| 38 |
+
return True
|
| 39 |
+
|
| 40 |
+
print(f"Downloading {url} to {output_path}")
|
| 41 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
response = requests.get(url, stream=True)
|
| 45 |
+
response.raise_for_status()
|
| 46 |
+
|
| 47 |
+
total_size_str = response.headers.get('Content-Length')
|
| 48 |
+
total_size = int(total_size_str) if total_size_str and total_size_str.isdigit() else 0
|
| 49 |
+
|
| 50 |
+
with open(output_path, 'wb') as f:
|
| 51 |
+
if total_size > 0:
|
| 52 |
+
label = f"Downloading {output_path.name}"
|
| 53 |
+
with click.progressbar(length=total_size, label=label, show_eta=True, show_percent=True) as bar:
|
| 54 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 55 |
+
if not chunk:
|
| 56 |
+
continue
|
| 57 |
+
f.write(chunk)
|
| 58 |
+
bar.update(len(chunk))
|
| 59 |
+
else:
|
| 60 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 61 |
+
if not chunk:
|
| 62 |
+
continue
|
| 63 |
+
f.write(chunk)
|
| 64 |
+
|
| 65 |
+
# Auto-extract tar archives if detected (handles .tar.gz, .tgz, .tar)
|
| 66 |
+
if tarfile.is_tarfile(output_path):
|
| 67 |
+
special_prefixes = (
|
| 68 |
+
"kaiju_db_viruses_2024-08-15",
|
| 69 |
+
"k2_standard_16gb_20241228",
|
| 70 |
+
)
|
| 71 |
+
subdir_name = next(
|
| 72 |
+
(
|
| 73 |
+
prefix
|
| 74 |
+
for prefix in special_prefixes
|
| 75 |
+
if output_path.name.startswith(prefix)
|
| 76 |
+
),
|
| 77 |
+
None,
|
| 78 |
+
)
|
| 79 |
+
self._extract_tarfile(output_path, subdir_name=subdir_name)
|
| 80 |
+
|
| 81 |
+
return True
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"Error downloading {url}: {e}")
|
| 85 |
+
if output_path.exists():
|
| 86 |
+
output_path.unlink()
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
def _extract_tarfile(self, tar_path: Path, subdir_name: Optional[str] = None) -> None:
|
| 90 |
+
"""Extract tar archive contents directly and delete the archive."""
|
| 91 |
+
output_dir = tar_path.parent
|
| 92 |
+
if subdir_name:
|
| 93 |
+
output_dir = output_dir / subdir_name
|
| 94 |
+
|
| 95 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 96 |
+
|
| 97 |
+
print(f"Extracting {tar_path} to {output_dir}")
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
with tarfile.open(tar_path, 'r:*') as tar:
|
| 101 |
+
for member in tar.getmembers():
|
| 102 |
+
if member.isfile():
|
| 103 |
+
member.name = Path(member.name).name
|
| 104 |
+
tar.extract(member, path=output_dir)
|
| 105 |
+
|
| 106 |
+
tar_path.unlink()
|
| 107 |
+
print(f"Removed archive: {tar_path}")
|
| 108 |
+
print(f"Successfully extracted {tar_path} to {output_dir}")
|
| 109 |
+
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f"Error extracting {tar_path}: {e}")
|
| 112 |
+
|
| 113 |
+
def _download_urls(self, urls: List[Union[str, Dict[str, str]]], target_dir: Path, category: str) -> bool:
|
| 114 |
+
"""Download multiple URLs to target directory.
|
| 115 |
+
|
| 116 |
+
Supports plain URL strings or objects with keys {"filename", "url"}.
|
| 117 |
+
"""
|
| 118 |
+
if not urls:
|
| 119 |
+
print(f"No {category} URLs to download")
|
| 120 |
+
return True
|
| 121 |
+
|
| 122 |
+
success = True
|
| 123 |
+
for i, entry in enumerate(urls):
|
| 124 |
+
url: str = ""
|
| 125 |
+
filename: str = ""
|
| 126 |
+
|
| 127 |
+
if isinstance(entry, str):
|
| 128 |
+
url = entry.strip()
|
| 129 |
+
if not url:
|
| 130 |
+
continue
|
| 131 |
+
parsed_url = urlparse(url)
|
| 132 |
+
filename = Path(parsed_url.path).name
|
| 133 |
+
elif isinstance(entry, dict):
|
| 134 |
+
url = (entry.get("url") or "").strip()
|
| 135 |
+
filename = (entry.get("filename") or "").strip()
|
| 136 |
+
if not filename and url:
|
| 137 |
+
parsed_url = urlparse(url)
|
| 138 |
+
filename = Path(parsed_url.path).name
|
| 139 |
+
else:
|
| 140 |
+
continue
|
| 141 |
+
|
| 142 |
+
if not filename:
|
| 143 |
+
filename = f"{category}_{i}.tar.gz"
|
| 144 |
+
|
| 145 |
+
if not url:
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
output_path = target_dir / filename
|
| 149 |
+
if not self._download_file(url, output_path):
|
| 150 |
+
success = False
|
| 151 |
+
|
| 152 |
+
return success
|
| 153 |
+
|
| 154 |
+
def download_data(self, task_id: str) -> bool:
|
| 155 |
+
"""Download data files for a specific task."""
|
| 156 |
+
task = self._get_task(task_id)
|
| 157 |
+
data_urls = task["download_urls"]["data"]
|
| 158 |
+
target_dir = self.base_dir / task_id / "data"
|
| 159 |
+
|
| 160 |
+
print(f"Downloading data for task: {task_id}")
|
| 161 |
+
return self._download_urls(data_urls, target_dir, "data")
|
| 162 |
+
|
| 163 |
+
def download_reference_data(self, task_id: str) -> bool:
|
| 164 |
+
"""Download reference data files for a specific task."""
|
| 165 |
+
task = self._get_task(task_id)
|
| 166 |
+
ref_urls = task["download_urls"]["reference_data"]
|
| 167 |
+
target_dir = self.base_dir / task_id / "reference"
|
| 168 |
+
|
| 169 |
+
print(f"Downloading reference data for task: {task_id}")
|
| 170 |
+
return self._download_urls(ref_urls, target_dir, "reference")
|
| 171 |
+
|
| 172 |
+
def download_results(self, task_id: str) -> bool:
|
| 173 |
+
"""Download result files for a specific task (for evaluation)."""
|
| 174 |
+
task = self._get_task(task_id)
|
| 175 |
+
result_urls = task["download_urls"]["results"]
|
| 176 |
+
target_dir = self.base_dir / task_id / "results"
|
| 177 |
+
|
| 178 |
+
print(f"Downloading results for task: {task_id}")
|
| 179 |
+
return self._download_urls(result_urls, target_dir, "results")
|
| 180 |
+
|
| 181 |
+
def download_task(self, task_id: str, include_reference: bool = False) -> bool:
|
| 182 |
+
"""Download all files for a task with optional reference data and results."""
|
| 183 |
+
print(f"Downloading task: {task_id}")
|
| 184 |
+
|
| 185 |
+
success = True
|
| 186 |
+
|
| 187 |
+
if not self.download_data(task_id):
|
| 188 |
+
success = False
|
| 189 |
+
|
| 190 |
+
if include_reference:
|
| 191 |
+
if not self.download_reference_data(task_id):
|
| 192 |
+
success = False
|
| 193 |
+
|
| 194 |
+
return success
|
| 195 |
+
|
| 196 |
+
def download_all_tasks(self, include_reference: bool = False) -> bool:
|
| 197 |
+
"""Download all tasks with optional reference data and results."""
|
| 198 |
+
success = True
|
| 199 |
+
|
| 200 |
+
for task in self.tasks:
|
| 201 |
+
task_id = task["task_id"]
|
| 202 |
+
if not self.download_task(task_id, include_reference):
|
| 203 |
+
success = False
|
| 204 |
+
return success
|
| 205 |
+
|
| 206 |
+
def list_tasks(self) -> List[str]:
|
| 207 |
+
"""List all available task IDs."""
|
| 208 |
+
return [task["task_id"] for task in self.tasks]
|
| 209 |
+
|
| 210 |
+
def download_all_results(self) -> bool:
|
| 211 |
+
"""Download results for all tasks."""
|
| 212 |
+
success = True
|
| 213 |
+
for task in self.tasks:
|
| 214 |
+
task_id = task["task_id"]
|
| 215 |
+
if not self.download_results(task_id):
|
| 216 |
+
success = False
|
| 217 |
+
return success
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# -----------------------------
|
| 221 |
+
# CLI
|
| 222 |
+
# -----------------------------
|
| 223 |
+
|
| 224 |
+
@click.group()
|
| 225 |
+
@click.option(
|
| 226 |
+
"--metadata",
|
| 227 |
+
default="src/task_metadata.json",
|
| 228 |
+
show_default=True,
|
| 229 |
+
help="Path to task metadata JSON file.",
|
| 230 |
+
)
|
| 231 |
+
@click.option(
|
| 232 |
+
"--dest",
|
| 233 |
+
default="tasks",
|
| 234 |
+
show_default=True,
|
| 235 |
+
help="Base output directory where task folders will be created.",
|
| 236 |
+
)
|
| 237 |
+
@click.pass_context
|
| 238 |
+
def cli(ctx: click.Context, metadata: str, dest: str) -> None:
|
| 239 |
+
"""BioAgent dataset manager."""
|
| 240 |
+
ctx.obj = BioAgentDataset(metadata_path=metadata, base_dir=dest)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@cli.command("list-tasks")
|
| 244 |
+
@click.pass_obj
|
| 245 |
+
def cli_list_tasks(dataset: BioAgentDataset) -> None:
|
| 246 |
+
"""List available task IDs."""
|
| 247 |
+
for task_id in dataset.list_tasks():
|
| 248 |
+
click.echo(task_id)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@cli.command("download")
|
| 252 |
+
@click.option("--task", "task_ids", multiple=True, help="Task ID(s) to download.")
|
| 253 |
+
@click.option("--all", "download_all", is_flag=True, help="Operate on all tasks.")
|
| 254 |
+
@click.option("--data/--no-data", default=True, show_default=True, help="Download data files.")
|
| 255 |
+
@click.option(
|
| 256 |
+
"--reference/--no-reference",
|
| 257 |
+
default=False,
|
| 258 |
+
show_default=True,
|
| 259 |
+
help="Include reference data.",
|
| 260 |
+
)
|
| 261 |
+
@click.option(
|
| 262 |
+
"--results/--no-results",
|
| 263 |
+
default=False,
|
| 264 |
+
show_default=True,
|
| 265 |
+
help="Include results files.",
|
| 266 |
+
)
|
| 267 |
+
@click.option(
|
| 268 |
+
"--dest",
|
| 269 |
+
default=None,
|
| 270 |
+
help="Base output directory where task folders will be created.",
|
| 271 |
+
)
|
| 272 |
+
@click.pass_obj
|
| 273 |
+
def cli_download(
|
| 274 |
+
dataset: BioAgentDataset,
|
| 275 |
+
task_ids: List[str],
|
| 276 |
+
download_all: bool,
|
| 277 |
+
data: bool,
|
| 278 |
+
reference: bool,
|
| 279 |
+
results: bool,
|
| 280 |
+
dest: Optional[str],
|
| 281 |
+
) -> None:
|
| 282 |
+
"""Download datasets for tasks (data, reference, results)."""
|
| 283 |
+
if dest:
|
| 284 |
+
dataset.base_dir = Path(dest)
|
| 285 |
+
if not download_all and not task_ids:
|
| 286 |
+
click.echo("Specify at least one --task or use --all", err=True)
|
| 287 |
+
raise SystemExit(1)
|
| 288 |
+
|
| 289 |
+
# If only results are requested, optimize the flow
|
| 290 |
+
if results and not data and not reference:
|
| 291 |
+
if download_all:
|
| 292 |
+
ok = dataset.download_all_results()
|
| 293 |
+
raise SystemExit(0 if ok else 1)
|
| 294 |
+
else:
|
| 295 |
+
ok = True
|
| 296 |
+
for tid in task_ids:
|
| 297 |
+
ok = dataset.download_results(tid) and ok
|
| 298 |
+
raise SystemExit(0 if ok else 1)
|
| 299 |
+
|
| 300 |
+
target_ids = dataset.list_tasks() if download_all else list(task_ids)
|
| 301 |
+
ok = True
|
| 302 |
+
for tid in target_ids:
|
| 303 |
+
if data:
|
| 304 |
+
ok = dataset.download_task(tid, include_reference=reference) and ok
|
| 305 |
+
elif reference:
|
| 306 |
+
ok = dataset.download_reference_data(tid) and ok
|
| 307 |
+
if results:
|
| 308 |
+
ok = dataset.download_results(tid) and ok
|
| 309 |
+
raise SystemExit(0 if ok else 1)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@cli.command("download-all-results")
|
| 313 |
+
@click.option(
|
| 314 |
+
"--dest",
|
| 315 |
+
default=None,
|
| 316 |
+
help="Base output directory where task folders will be created.",
|
| 317 |
+
)
|
| 318 |
+
@click.pass_obj
|
| 319 |
+
def cli_download_all_results(dataset: BioAgentDataset, dest: Optional[str]) -> None:
|
| 320 |
+
"""Download results for all tasks."""
|
| 321 |
+
if dest:
|
| 322 |
+
dataset.base_dir = Path(dest)
|
| 323 |
+
ok = dataset.download_all_results()
|
| 324 |
+
raise SystemExit(0 if ok else 1)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
cli()
|