File size: 1,151 Bytes
e13a654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, tarfile
from pathlib import Path

def _safe_members(tf, prefix):
    if not prefix.endswith('/'):
        prefix += '/'
    for m in tf.getmembers():
        if not m.name.startswith(prefix):
            continue
        # basic traversal guard
        p = Path(m.name)
        if any(part == '..' for part in p.parts) or p.is_absolute():
            continue
        yield m

def ensure_tar_tree(repo_id: str, root: str, *, token: str | None = None, max_workers: int = 4):
    os.environ.setdefault('HF_HUB_ENABLE_HF_TRANSFER', '1')
    from huggingface_hub import snapshot_download
    base = Path(snapshot_download(repo_id=repo_id, repo_type='dataset',
        allow_patterns=[f'{root}.tar', 'index.jsonl', 'README.md', 'LICENSE'],
        resume_download=True, token=token, max_workers=max_workers))
    root_dir = base / root
    if root_dir.exists():
        return root_dir
    tar_path = base / f'{root}.tar'
    if not tar_path.exists():
        raise FileNotFoundError(f'Expected {tar_path} in snapshot')
    with tarfile.open(tar_path, 'r') as tf:
        tf.extractall(base, members=_safe_members(tf, root))
    return root_dir