File size: 3,715 Bytes
3e51a60
 
 
 
 
 
 
 
 
 
 
 
bbb4495
 
 
3e51a60
 
 
 
 
 
 
 
 
 
 
 
 
bbb4495
3e51a60
 
 
 
8609330
3e51a60
 
bbb4495
 
 
 
 
 
 
3e51a60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Download the SchemaBio reference bundle (hg19 or hg38) from Hugging Face.

Always downloaded:
  - reference genome (*.fa.gz, *.fai)
  - bed/
  - schema_bundle/
  - VEP cache tarball (homo_sapiens_merged_vep_*.tar.gz)

Optional:
  --index bwa|minibwa|all   aligner index (default: none)
                            matched by file suffix under {genome}/:
                            bwa     -> .amb .ann .bwt .pac .sa
                            minibwa -> .l2b .mbw (incl. .meth.mbw)
  --extract-vep             extract the VEP cache into <outdir>/vep (default: no)

Examples:
  python download_bundle.py -g hg38 -o /data/database
  python download_bundle.py -g hg19 -o /data/database --index bwa --extract-vep

Requires: pip install huggingface_hub
Set HF_ENDPOINT=https://hf-mirror.com to use a mirror.
"""
import argparse, fnmatch, os, sys, tarfile

REPO = "pzweuj/SchemaBio_Bundle"
BWA_EXT = (".amb", ".ann", ".bwt", ".pac", ".sa")
MINIBWA_EXT = (".l2b", ".mbw")


def select(files, genome, index):
    pats = [f"{genome}/Homo_sapiens.*.fa.gz", f"{genome}/Homo_sapiens.*.fa.fai",
            f"{genome}/homo_sapiens_merged_vep_*.tar.gz", f"{genome}/{genome}_default.bed",
            f"{genome}/bed/*", f"{genome}/schema_bundle/*"]
    out = [f for f in files if any(fnmatch.fnmatch(f, p) for p in pats)]
    gfiles = [f for f in files if f.startswith(f"{genome}/")]
    for name, ext in (("bwa", BWA_EXT), ("minibwa", MINIBWA_EXT)):
        if index in (name, "all"):
            hit = [f for f in gfiles if f.endswith(ext)]
            if not hit:
                print(f"[warn] no {name} index ({' '.join(ext)}) found for {genome}, skipped", file=sys.stderr)
            out += hit
    return sorted(set(out))


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("-g", "--genome", required=True, choices=["hg19", "hg38"])
    ap.add_argument("-o", "--outdir", default=".", help="output directory (default: .)")
    ap.add_argument("--index", default="none", choices=["none", "bwa", "minibwa", "all"],
                    help="aligner index to download (default: none)")
    ap.add_argument("--extract-vep", action="store_true", help="extract VEP cache after download")
    ap.add_argument("--revision", default="main")
    ap.add_argument("--dry-run", action="store_true", help="only list files")
    a = ap.parse_args()

    try:
        from huggingface_hub import HfApi, hf_hub_download
    except ImportError:
        sys.exit("huggingface_hub not installed: pip install huggingface_hub")

    files = [f.path for f in HfApi().list_repo_tree(REPO, repo_type="dataset", recursive=True,
                                                    revision=a.revision) if hasattr(f, "size")]
    todo = select(files, a.genome, a.index)
    print(f"{len(todo)} files to download for {a.genome} (index={a.index})")
    for f in todo:
        print("  " + f)
    if a.dry_run:
        return

    os.makedirs(a.outdir, exist_ok=True)
    for i, f in enumerate(todo, 1):
        print(f"[{i}/{len(todo)}] {f}", flush=True)
        hf_hub_download(REPO, f, repo_type="dataset", revision=a.revision, local_dir=a.outdir)

    if a.extract_vep:
        for f in todo:
            if os.path.basename(f).startswith("homo_sapiens_merged_vep_"):
                src = os.path.join(a.outdir, f)
                dst = os.path.join(a.outdir, a.genome, "vep")
                os.makedirs(dst, exist_ok=True)
                print(f"extracting {src} -> {dst}", flush=True)
                with tarfile.open(src) as t:
                    t.extractall(dst)
    print("done")


if __name__ == "__main__":
    main()