Debian Codegraph @

av/datasets.py

raw
1 import errno
2 import logging
3 import os
4 import sys
5 from typing import Iterator
6 from urllib.request import urlopen
7
8 log = logging.getLogger(__name__)
9
10
11 def iter_data_dirs(check_writable: bool = False) -> Iterator[str]:
12 try:
13 yield os.environ["PYAV_TESTDATA_DIR"]
14 except KeyError:
15 pass
16
17 if os.name == "nt":
18 yield os.path.join(sys.prefix, "pyav", "datasets")
19 return
20
21 bases = [
22 "/usr/local/share",
23 "/usr/local/lib",
24 "/usr/share",
25 "/usr/lib",
26 ]
27
28 # Prefer the local virtualenv.
29 if hasattr(sys, "real_prefix"):
30 bases.insert(0, sys.prefix)
31
32 for base in bases:
33 dir_ = os.path.join(base, "pyav", "datasets")
34 if check_writable:
35 if os.path.exists(dir_):
36 if not os.access(dir_, os.W_OK):
37 continue
38 else:
39 if not os.access(base, os.W_OK):
40 continue
41 yield dir_
42
43 yield os.path.join(os.path.expanduser("~"), ".pyav", "datasets")
44
45
46 def cached_download(url: str, name: str) -> str:
47 """Download the data at a URL, and cache it under the given name.
48
49 The file is stored under `pyav/test` with the given name in the directory
50 :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of:
51
52 - the current virtualenv
53 - ``/usr/local/share``
54 - ``/usr/local/lib``
55 - ``/usr/share``
56 - ``/usr/lib``
57 - the user's home
58
59 """
60
61 clean_name = os.path.normpath(name)
62 if clean_name != name:
63 raise ValueError(f"{name} is not normalized.")
64
65 for dir_ in iter_data_dirs():
66 path = os.path.join(dir_, name)
67 if os.path.exists(path):
68 return path
69
70 dir_ = next(iter_data_dirs(True))
71 path = os.path.join(dir_, name)
72
73 log.info(f"Downloading {url} to {path}")
74
75 response = urlopen(url)
76 if response.getcode() != 200:
77 raise ValueError(f"HTTP {response.getcode()}")
78
79 dir_ = os.path.dirname(path)
80 try:
81 os.makedirs(dir_)
82 except OSError as e:
83 if e.errno != errno.EEXIST:
84 raise
85
86 tmp_path = path + ".tmp"
87 with open(tmp_path, "wb") as fh:
88 while True:
89 chunk = response.read(8196)
90 if chunk:
91 fh.write(chunk)
92 else:
93 break
94
95 os.rename(tmp_path, path)
96
97 return path
98
99
100 def fate(name: str) -> str:
101 """Download and return a path to a sample from the FFmpeg test suite.
102
103 Data is handled by :func:`cached_download`.
104
105 See the `FFmpeg Automated Test Environment <https://www.ffmpeg.org/fate.html>`_
106
107 """
108 return cached_download(
109 "http://fate.ffmpeg.org/fate-suite/" + name,
110 os.path.join("fate-suite", name.replace("/", os.path.sep)),
111 )
112
113
114 def curated(name: str) -> str:
115 """Download and return a path to a sample that is curated by the PyAV developers.
116
117 Data is handled by :func:`cached_download`.
118
119 """
120 return cached_download(
121 "https://pyav.org/datasets/" + name,
122 os.path.join("pyav-curated", name.replace("/", os.path.sep)),
123 )