Repository navigation
Expand file tree
/
Copy patharchive.py
More file actions
86 lines (67 loc) · 3.24 KB
/
Copy patharchive.py
File metadata and controls
86 lines (67 loc) · 3.24 KB
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
"""Tar extraction and spaCy model-directory discovery.
Both concerns are shared by every :class:`~nlp_lambda.model_source.ModelSource`
that ships models as ``.tar.gz``, so they live here rather than in any one source.
"""
from __future__ import annotations
import tarfile
from collections.abc import Iterable
from pathlib import Path
from nlp_lambda.errors import ModelUnavailableError, UnsafeArchiveError
#: Files that mark a directory as a loadable spaCy pipeline.
_V3_MARKER = "config.cfg"
_V2_MARKERS = ("meta.json", "tokenizer")
_MAX_SEARCH_DEPTH = 4
def safe_extract(archive: Path, dest: Path) -> None:
"""Extract ``archive`` into ``dest``, refusing members that escape it.
``TarFile.extractall`` will happily write to ``../../etc/cron.d`` if the archive
says so (CVE-2007-4559). The ``data`` filter blocks that, but on 3.12 it is not
yet the default, and a rejected member mid-extraction leaves a partial tree; the
up-front scan refuses the whole archive before a single byte is written.
"""
dest = dest.resolve()
dest.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive) as tar:
for member in tar.getmembers():
target = (dest / member.name).resolve()
if target != dest and dest not in target.parents:
raise UnsafeArchiveError(
f"archive member {member.name!r} would extract outside {dest}"
)
if member.issym() or member.islnk():
link_target = (target.parent / member.linkname).resolve()
if link_target != dest and dest not in link_target.parents:
raise UnsafeArchiveError(f"archive link {member.name!r} points outside {dest}")
tar.extractall(path=dest, filter="data")
def _is_pipeline_dir(path: Path) -> bool:
if (path / _V3_MARKER).is_file():
return True
return all((path / marker).exists() for marker in _V2_MARKERS)
def _walk(root: Path, depth: int) -> Iterable[Path]:
"""Breadth-first directory walk, shallowest first, bounded depth."""
level = [root]
for _ in range(depth + 1):
if not level:
return
yield from level
level = [child for parent in level for child in sorted(parent.iterdir()) if child.is_dir()]
def find_model_dir(root: Path) -> Path:
"""Return the loadable pipeline directory inside an extracted model tree.
A spaCy model archive unpacks to ``<name>-<version>/<name>/<name>-<version>/``:
the outer directory is a Python sdist, only the inner one can be passed to
``spacy.load``. The original code rebuilt that path by string surgery on the
model name, which broke for any model whose name did not contain exactly one
``-``. Looking for the marker files works for v2 and v3 layouts alike.
"""
root = Path(root)
if not root.is_dir():
raise ModelUnavailableError(f"{root} is not a directory")
deepest: Path | None = None
for candidate in _walk(root, _MAX_SEARCH_DEPTH):
if _is_pipeline_dir(candidate):
deepest = candidate
if deepest is None:
raise ModelUnavailableError(
f"no spaCy pipeline found under {root} "
f"(looked for {_V3_MARKER} or {'+'.join(_V2_MARKERS)})"
)
return deepest