File size: 4,085 Bytes
1a258c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fetch complete author code at pinned commits without git or remote experiment paths."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import io
import json
from pathlib import Path
import tarfile
import time

import requests

ROOT = Path(__file__).resolve().parents[1]


def fetch(item):
    name, spec = item
    target = ROOT / spec['destination']
    marker = ROOT / 'provenance' / f'{name}_SOURCE.json'
    if marker.is_file():
        previous = json.loads(marker.read_text())
        assert previous['revision'] == spec['revision']
        assert all((target/p).is_file() and hashlib.sha256((target/p).read_bytes()).hexdigest()==h
                   for p,h in previous['files'].items())
        print(name, 'verified source already present', flush=True)
        return
    url = f"https://codeload.github.com/{spec['repository']}/tar.gz/{spec['revision']}"
    if name in ('l2l_trevor','dystream','deca'):
        response=requests.get(f"https://api.github.com/repos/{spec['repository']}/git/trees/{spec['revision']}",
                              params={'recursive':1},timeout=30)
        response.raise_for_status()
        blobs=[f for f in response.json()['tree'] if f['type']=='blob']
        excluded={'.mp4','.webm','.gif','.png','.jpg','.jpeg','.wav','.zip','.tar','.pth','.ckpt'}
        kept=[f for f in blobs if (Path(f['path']).suffix.lower() not in excluded or
              (name=='l2l_trevor' and f['path']=='src/configs/trevor_configs.tar'))
              and not f['path'].endswith('.pyc') and '__pycache__' not in Path(f['path']).parts]
        def one(blob):
            path=target/blob['path']
            path.parent.mkdir(parents=True,exist_ok=True)
            raw=f"https://raw.githubusercontent.com/{spec['repository']}/{spec['revision']}/{blob['path']}"
            for attempt in range(3):
                try:
                    data=requests.get(raw,timeout=25).content
                    check=hashlib.sha1(f'blob {len(data)}\0'.encode()+data).hexdigest()
                    assert check==blob['sha'],blob['path']
                    path.write_bytes(data)
                    return blob['path'],hashlib.sha256(data).hexdigest()
                except Exception:
                    if attempt==2:raise
                    time.sleep(2)
        with ThreadPoolExecutor(8) as pool:files=dict(pool.map(one,kept))
        marker.write_text(json.dumps(dict(**spec,files=files,
            omitted_noncode_files=[f['path'] for f in blobs if f not in kept],at=time.time()),indent=2)+'\n')
        print(name,'downloaded',len(files),'source files',flush=True)
        return
    response = requests.get(url, timeout=(15,120))
    response.raise_for_status()
    target.mkdir(parents=True, exist_ok=True)
    files = {}
    with tarfile.open(fileobj=io.BytesIO(response.content), mode='r:gz') as archive:
        for member in archive.getmembers():
            parts = Path(member.name).parts[1:]
            if not parts:
                continue
            relative = Path(*parts)
            output = target / relative
            assert output.resolve().is_relative_to(target.resolve()), member.name
            if member.isdir():
                output.mkdir(parents=True, exist_ok=True)
            elif member.isfile():
                output.parent.mkdir(parents=True, exist_ok=True)
                data = archive.extractfile(member).read()
                output.write_bytes(data)
                output.chmod(member.mode & 0o777)
                files[str(relative)] = hashlib.sha256(data).hexdigest()
            else:
                raise ValueError(f'Unexpected archive member type: {member.name}')
    marker.write_text(json.dumps(dict(**spec, files=files,
        archive_sha256=hashlib.sha256(response.content).hexdigest(), url=url,at=time.time()),indent=2)+'\n')
    print(name, 'downloaded',len(files),'source files',flush=True)


if __name__ == '__main__':
    specs=json.loads((ROOT/'configs/sources.json').read_text())
    with ThreadPoolExecutor(5) as pool:
        list(pool.map(fetch,specs.items()))