File size: 2,902 Bytes
4f9b1ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Weight resolution for this Arena wrapper (self-contained; no machine-specific paths).

A file is taken from the wrapper's directory when it is present there (a full `snapshot_download` /
`git clone` of this repo, or a manual copy); otherwise it is fetched with `hf_hub_download` from a
commit-pinned public Hugging Face repo into the normal HF cache. Files that must be derived from a
third-party checkpoint (unlicensed weights the Arena links but does not re-host) are built once and
cached under $ARENA_CKPT_CACHE (default ~/.cache/speech_spoof_bench/<Model>/).
"""
from __future__ import annotations

import hashlib
import os


def local_or_hub(here: str, name: str, repo_id: str, filename: str | None = None, revision: str | None = None,
                 sha256: str | None = None) -> str:
    """<here>/<name> if it exists (here = the calling wrapper's directory), else
    hf_hub_download(repo_id, filename or name, revision)."""
    p = os.path.join(here, name)
    if os.path.exists(p):
        return p
    from huggingface_hub import hf_hub_download
    p = hf_hub_download(repo_id, filename or name, revision=revision)
    if sha256 is not None:
        check_sha256(p, sha256)
    return p


def check_sha256(path: str, expected: str) -> None:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for b in iter(lambda: f.read(1 << 24), b""):
            h.update(b)
    if h.hexdigest() != expected:
        raise RuntimeError(f"{path}: sha256 {h.hexdigest()} != pinned {expected}")


def cache_dir(model: str) -> str:
    root = os.environ.get("ARENA_CKPT_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "speech_spoof_bench")
    d = os.path.join(root, model)
    os.makedirs(d, exist_ok=True)
    return d


def derived(here: str, name: str, model: str, build) -> str:
    """<here>/<name> if present, else <cache_dir(model)>/<name>, created once by build(out_path)."""
    p = os.path.join(here, name)
    if os.path.exists(p):
        return p
    p = os.path.join(cache_dir(model), name)
    if not os.path.exists(p):
        tmp = p + f".part{os.getpid()}"
        build(tmp)
        os.replace(tmp, p)
    return p


def local_or_gdrive(here: str, name: str, model: str, file_id: str, sha256: str) -> str:
    """<here>/<name> if present, else <cache_dir(model)>/<name> downloaded once from Google Drive with gdown
    (pip install gdown) and sha256-checked. For weights whose only public source is the authors' Drive."""
    def _get(out):
        try:
            import gdown
        except ImportError as e:
            raise RuntimeError(f"{name} is not in {here}: install gdown or download Google Drive file id {file_id} "
                               f"(sha256 {sha256}) to {os.path.join(here, name)}") from e
        gdown.download(id=file_id, output=out, quiet=False)
        check_sha256(out, sha256)
    return derived(here, name, model, _get)