hfpin 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hfpin/__init__.py +3 -0
- hfpin/__main__.py +5 -0
- hfpin/cli.py +203 -0
- hfpin/hub.py +92 -0
- hfpin/rewrite.py +41 -0
- hfpin/scanner.py +223 -0
- hfpin-0.1.0.dist-info/METADATA +124 -0
- hfpin-0.1.0.dist-info/RECORD +11 -0
- hfpin-0.1.0.dist-info/WHEEL +4 -0
- hfpin-0.1.0.dist-info/entry_points.txt +2 -0
- hfpin-0.1.0.dist-info/licenses/LICENSE +21 -0
hfpin/__init__.py
ADDED
hfpin/__main__.py
ADDED
hfpin/cli.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import difflib
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from fnmatch import fnmatch
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Dict, List, Optional, Sequence
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .hub import Hub, HubError, RepoInfo, RepoNotFound, default_token
|
|
15
|
+
from .rewrite import pin_source
|
|
16
|
+
from .scanner import Finding, iter_python_files, scan_source
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Problem:
|
|
20
|
+
def __init__(self, finding: Finding, level: str, kind: str, message: str):
|
|
21
|
+
self.finding = finding
|
|
22
|
+
self.level = level
|
|
23
|
+
self.kind = kind
|
|
24
|
+
self.message = message
|
|
25
|
+
|
|
26
|
+
def as_dict(self) -> dict:
|
|
27
|
+
f = self.finding
|
|
28
|
+
return {
|
|
29
|
+
"path": f.path,
|
|
30
|
+
"line": f.line,
|
|
31
|
+
"column": f.col,
|
|
32
|
+
"level": self.level,
|
|
33
|
+
"kind": self.kind,
|
|
34
|
+
"message": self.message,
|
|
35
|
+
"call": f.call,
|
|
36
|
+
"repo_id": f.repo_id,
|
|
37
|
+
"repo_type": f.repo_type,
|
|
38
|
+
"revision": f.revision,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def collect(paths: Sequence[str], exclude: Sequence[str]) -> List[Finding]:
|
|
43
|
+
findings: List[Finding] = []
|
|
44
|
+
for file in iter_python_files(paths, exclude):
|
|
45
|
+
try:
|
|
46
|
+
source = file.read_text(encoding="utf-8")
|
|
47
|
+
findings.extend(scan_source(source, str(file)))
|
|
48
|
+
except (SyntaxError, UnicodeDecodeError) as error:
|
|
49
|
+
print(f"hfpin: skipping {file}: {error}", file=sys.stderr)
|
|
50
|
+
findings.sort(key=lambda f: (f.path, f.line, f.col))
|
|
51
|
+
return findings
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _label(f: Finding) -> str:
|
|
55
|
+
return f"{f.repo_type} '{f.repo_id}' ({f.call})"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def evaluate(findings: List[Finding], args: argparse.Namespace, hub: Optional[Hub]) -> List[Problem]:
|
|
59
|
+
problems: List[Problem] = []
|
|
60
|
+
for f in findings:
|
|
61
|
+
if f.status == "unpinned":
|
|
62
|
+
problems.append(Problem(f, "error", "unpinned", f"unpinned {_label(f)}: add revision=<commit sha>"))
|
|
63
|
+
elif f.status == "mutable" and not args.allow_mutable:
|
|
64
|
+
problems.append(
|
|
65
|
+
Problem(f, "error", "mutable", f"{_label(f)} uses revision '{f.revision}', which can change: use a commit sha")
|
|
66
|
+
)
|
|
67
|
+
if f.trust_remote_code:
|
|
68
|
+
hint = "" if f.status == "pinned" else " and the code can change at any time"
|
|
69
|
+
problems.append(
|
|
70
|
+
Problem(f, "warning", "remote-code", f"trust_remote_code runs Python code from '{f.repo_id}'{hint}")
|
|
71
|
+
)
|
|
72
|
+
if hub is None:
|
|
73
|
+
continue
|
|
74
|
+
try:
|
|
75
|
+
info = hub.resolve(f.repo_id, f.repo_type, f.revision or "main")
|
|
76
|
+
except RepoNotFound as error:
|
|
77
|
+
problems.append(Problem(f, "error", "not-found", f"{error} (typo, private repo, or a made-up name?)"))
|
|
78
|
+
continue
|
|
79
|
+
if info.gated:
|
|
80
|
+
problems.append(Problem(f, "warning", "gated", f"'{info.repo_id}' is gated: users must accept its terms"))
|
|
81
|
+
license_name = info.license or "none"
|
|
82
|
+
for pattern in args.deny_license:
|
|
83
|
+
if any(fnmatch(name.strip(), pattern) for name in license_name.split(",")):
|
|
84
|
+
problems.append(
|
|
85
|
+
Problem(f, "error", "license", f"'{info.repo_id}' has license '{license_name}' (denied by '{pattern}')")
|
|
86
|
+
)
|
|
87
|
+
break
|
|
88
|
+
return problems
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _print_problems(problems: List[Problem], fmt: str, files: int) -> None:
|
|
92
|
+
if fmt == "json":
|
|
93
|
+
print(json.dumps([p.as_dict() for p in problems], indent=2))
|
|
94
|
+
return
|
|
95
|
+
for p in problems:
|
|
96
|
+
f = p.finding
|
|
97
|
+
if fmt == "github":
|
|
98
|
+
print(f"::{p.level} file={f.path},line={f.line},col={f.col},title=hfpin {p.kind}::{p.message}")
|
|
99
|
+
else:
|
|
100
|
+
prefix = "" if p.level == "error" else "warning: "
|
|
101
|
+
print(f"{f.path}:{f.line}:{f.col}: {prefix}{p.message}")
|
|
102
|
+
if fmt == "text":
|
|
103
|
+
errors = sum(p.level == "error" for p in problems)
|
|
104
|
+
if errors:
|
|
105
|
+
fixable = any(p.kind in ("unpinned", "mutable") for p in problems)
|
|
106
|
+
hint = " Run `hfpin pin` to fix." if fixable else ""
|
|
107
|
+
print(f"\n{errors} problem(s) found.{hint}")
|
|
108
|
+
else:
|
|
109
|
+
print(f"All Hugging Face downloads are pinned ({files} checked).")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
113
|
+
findings = collect(args.paths, args.exclude)
|
|
114
|
+
hub = Hub(token=args.token or default_token()) if (args.online or args.deny_license) else None
|
|
115
|
+
try:
|
|
116
|
+
problems = evaluate(findings, args, hub)
|
|
117
|
+
except HubError as error:
|
|
118
|
+
print(f"hfpin: {error}", file=sys.stderr)
|
|
119
|
+
return 2
|
|
120
|
+
_print_problems(problems, args.format, len(findings))
|
|
121
|
+
return 1 if any(p.level == "error" for p in problems) else 0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_pin(args: argparse.Namespace) -> int:
|
|
125
|
+
findings = [f for f in collect(args.paths, args.exclude) if f.status != "pinned"]
|
|
126
|
+
hub = Hub(token=args.token or default_token())
|
|
127
|
+
by_file: Dict[str, list] = {}
|
|
128
|
+
failed = 0
|
|
129
|
+
for f in findings:
|
|
130
|
+
try:
|
|
131
|
+
info: RepoInfo = hub.resolve(f.repo_id, f.repo_type, f.revision or "main")
|
|
132
|
+
except RepoNotFound as error:
|
|
133
|
+
print(f"{f.path}:{f.line}:{f.col}: skipped: {error}", file=sys.stderr)
|
|
134
|
+
failed += 1
|
|
135
|
+
continue
|
|
136
|
+
except HubError as error:
|
|
137
|
+
print(f"hfpin: {error}", file=sys.stderr)
|
|
138
|
+
return 2
|
|
139
|
+
by_file.setdefault(f.path, []).append((f, info.sha))
|
|
140
|
+
renamed = f" (now '{info.repo_id}')" if info.repo_id != f.repo_id else ""
|
|
141
|
+
print(
|
|
142
|
+
f"{f.path}:{f.line}:{f.col}: {f.repo_id}@{f.revision or 'main'} -> {info.sha[:12]}{renamed}",
|
|
143
|
+
file=sys.stderr,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
for path, pins in by_file.items():
|
|
147
|
+
source = Path(path).read_text(encoding="utf-8")
|
|
148
|
+
updated = pin_source(source, pins)
|
|
149
|
+
if args.dry_run:
|
|
150
|
+
sys.stdout.writelines(
|
|
151
|
+
difflib.unified_diff(
|
|
152
|
+
source.splitlines(keepends=True),
|
|
153
|
+
updated.splitlines(keepends=True),
|
|
154
|
+
fromfile=f"a/{path}",
|
|
155
|
+
tofile=f"b/{path}",
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
else:
|
|
159
|
+
Path(path).write_text(updated, encoding="utf-8")
|
|
160
|
+
|
|
161
|
+
pinned = sum(len(p) for p in by_file.values())
|
|
162
|
+
verb = "Would pin" if args.dry_run else "Pinned"
|
|
163
|
+
print(f"{verb} {pinned} download(s) in {len(by_file)} file(s).", file=sys.stderr)
|
|
164
|
+
return 1 if failed else 0
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
168
|
+
parser = argparse.ArgumentParser(
|
|
169
|
+
prog="hfpin",
|
|
170
|
+
description="Pin Hugging Face models and datasets in your code to exact commits.",
|
|
171
|
+
)
|
|
172
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
173
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
174
|
+
|
|
175
|
+
def common(p: argparse.ArgumentParser) -> None:
|
|
176
|
+
p.add_argument("paths", nargs="*", default=["."], help="files or directories (default: .)")
|
|
177
|
+
p.add_argument("--exclude", action="append", default=[], metavar="GLOB", help="skip files matching GLOB")
|
|
178
|
+
p.add_argument("--token", help="Hugging Face token (default: HF_TOKEN or the huggingface-cli login)")
|
|
179
|
+
|
|
180
|
+
check = sub.add_parser("check", help="report unpinned downloads (exit 1 if any)")
|
|
181
|
+
common(check)
|
|
182
|
+
check.add_argument("--format", choices=("text", "json", "github"), default="text")
|
|
183
|
+
check.add_argument("--allow-mutable", action="store_true", help="accept branch and tag revisions")
|
|
184
|
+
check.add_argument("--online", action="store_true", help="also verify repos exist on the Hub")
|
|
185
|
+
check.add_argument(
|
|
186
|
+
"--deny-license",
|
|
187
|
+
action="append",
|
|
188
|
+
default=[],
|
|
189
|
+
metavar="PATTERN",
|
|
190
|
+
help="fail on licenses matching PATTERN, e.g. 'cc-by-nc*' (implies --online)",
|
|
191
|
+
)
|
|
192
|
+
check.set_defaults(func=cmd_check)
|
|
193
|
+
|
|
194
|
+
pin = sub.add_parser("pin", help="rewrite files to pin downloads to the current commit")
|
|
195
|
+
common(pin)
|
|
196
|
+
pin.add_argument("--dry-run", action="store_true", help="print a diff instead of writing files")
|
|
197
|
+
pin.set_defaults(func=cmd_pin)
|
|
198
|
+
return parser
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
202
|
+
args = build_parser().parse_args(argv)
|
|
203
|
+
return args.func(args)
|
hfpin/hub.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Minimal Hugging Face Hub API client (stdlib only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Dict, Optional, Tuple
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
|
|
16
|
+
ENDPOINT = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class RepoInfo:
|
|
21
|
+
repo_id: str
|
|
22
|
+
sha: str
|
|
23
|
+
license: Optional[str]
|
|
24
|
+
gated: bool
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class HubError(Exception):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RepoNotFound(HubError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def default_token() -> Optional[str]:
|
|
36
|
+
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
|
37
|
+
if token:
|
|
38
|
+
return token
|
|
39
|
+
hf_home = Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface"))
|
|
40
|
+
token_file = hf_home / "token"
|
|
41
|
+
if token_file.is_file():
|
|
42
|
+
return token_file.read_text().strip() or None
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _license(data: dict) -> Optional[str]:
|
|
47
|
+
value = (data.get("cardData") or {}).get("license")
|
|
48
|
+
if not value:
|
|
49
|
+
value = [t.split(":", 1)[1] for t in data.get("tags", []) if t.startswith("license:")]
|
|
50
|
+
if isinstance(value, list):
|
|
51
|
+
return ", ".join(value) or None
|
|
52
|
+
return value or None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Hub:
|
|
56
|
+
def __init__(self, token: Optional[str] = None, endpoint: str = ENDPOINT):
|
|
57
|
+
self.token = token
|
|
58
|
+
self.endpoint = endpoint
|
|
59
|
+
self._cache: Dict[Tuple[str, str, str], RepoInfo] = {}
|
|
60
|
+
|
|
61
|
+
def resolve(self, repo_id: str, repo_type: str = "model", revision: str = "main") -> RepoInfo:
|
|
62
|
+
key = (repo_type, repo_id, revision)
|
|
63
|
+
if key not in self._cache:
|
|
64
|
+
self._cache[key] = self._fetch(repo_id, repo_type, revision)
|
|
65
|
+
return self._cache[key]
|
|
66
|
+
|
|
67
|
+
def _fetch(self, repo_id: str, repo_type: str, revision: str) -> RepoInfo:
|
|
68
|
+
url = "{}/api/{}s/{}/revision/{}".format(
|
|
69
|
+
self.endpoint,
|
|
70
|
+
repo_type,
|
|
71
|
+
repo_id,
|
|
72
|
+
urllib.parse.quote(revision, safe=""),
|
|
73
|
+
)
|
|
74
|
+
request = urllib.request.Request(url, headers={"User-Agent": f"hfpin/{__version__}"})
|
|
75
|
+
if self.token:
|
|
76
|
+
request.add_header("Authorization", f"Bearer {self.token}")
|
|
77
|
+
try:
|
|
78
|
+
with urllib.request.urlopen(request, timeout=30) as response:
|
|
79
|
+
data = json.load(response)
|
|
80
|
+
except urllib.error.HTTPError as error:
|
|
81
|
+
# The Hub answers 401 for missing repos when unauthenticated.
|
|
82
|
+
if error.code in (401, 404):
|
|
83
|
+
raise RepoNotFound(f"{repo_type} '{repo_id}' at revision '{revision}' not found on the Hub") from None
|
|
84
|
+
raise HubError(f"Hub request failed for {repo_id}: HTTP {error.code}") from None
|
|
85
|
+
except urllib.error.URLError as error:
|
|
86
|
+
raise HubError(f"Cannot reach {self.endpoint}: {error.reason}") from None
|
|
87
|
+
return RepoInfo(
|
|
88
|
+
repo_id=data.get("id", repo_id),
|
|
89
|
+
sha=data["sha"],
|
|
90
|
+
license=_license(data),
|
|
91
|
+
gated=bool(data.get("gated")),
|
|
92
|
+
)
|
hfpin/rewrite.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Rewrite source code so Hub downloads use an exact commit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import List, Tuple
|
|
6
|
+
|
|
7
|
+
from .scanner import Finding, Position
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _offset(lines: List[bytes], position: Position) -> int:
|
|
11
|
+
line, col = position
|
|
12
|
+
return sum(len(chunk) for chunk in lines[: line - 1]) + col
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def pin_source(source: str, pins: List[Tuple[Finding, str]]) -> str:
|
|
16
|
+
"""Return ``source`` with each finding pinned to its commit sha."""
|
|
17
|
+
data = source.encode()
|
|
18
|
+
lines = data.splitlines(keepends=True)
|
|
19
|
+
edits = []
|
|
20
|
+
for finding, sha in pins:
|
|
21
|
+
if finding.revision_span is not None:
|
|
22
|
+
start, end = finding.revision_span
|
|
23
|
+
begin = _offset(lines, start)
|
|
24
|
+
quote = data[begin : begin + 1].decode()
|
|
25
|
+
quote = quote if quote in ("'", '"') else '"'
|
|
26
|
+
edits.append((begin, _offset(lines, end), f"{quote}{sha}{quote}"))
|
|
27
|
+
elif finding.arg_indent is not None:
|
|
28
|
+
at = _offset(lines, finding.insert_at)
|
|
29
|
+
rest = data[at:].lstrip(b" \t")
|
|
30
|
+
if rest.startswith(b","):
|
|
31
|
+
at = data.index(b",", at) + 1
|
|
32
|
+
edits.append((at, at, f'\n{finding.arg_indent}revision="{sha}",'))
|
|
33
|
+
else:
|
|
34
|
+
edits.append((at, at, f',\n{finding.arg_indent}revision="{sha}"'))
|
|
35
|
+
else:
|
|
36
|
+
at = _offset(lines, finding.insert_at)
|
|
37
|
+
edits.append((at, at, f', revision="{sha}"'))
|
|
38
|
+
|
|
39
|
+
for begin, end, text in sorted(edits, reverse=True):
|
|
40
|
+
data = data[:begin] + text.encode() + data[end:]
|
|
41
|
+
return data.decode()
|
hfpin/scanner.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Find Hugging Face Hub downloads in Python source code."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Iterator, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
SHA_RE = re.compile(r"[0-9a-f]{40}")
|
|
12
|
+
REPO_ID_RE = re.compile(r"[A-Za-z0-9][\w.-]*(/[A-Za-z0-9][\w.-]*)?")
|
|
13
|
+
IGNORE_MARKER = "hfpin: ignore"
|
|
14
|
+
|
|
15
|
+
# load_dataset() names that are local file loaders, not Hub repos.
|
|
16
|
+
BUILTIN_DATASET_BUILDERS = {
|
|
17
|
+
"arrow",
|
|
18
|
+
"audiofolder",
|
|
19
|
+
"csv",
|
|
20
|
+
"generator",
|
|
21
|
+
"imagefolder",
|
|
22
|
+
"json",
|
|
23
|
+
"pandas",
|
|
24
|
+
"parquet",
|
|
25
|
+
"spark",
|
|
26
|
+
"sql",
|
|
27
|
+
"text",
|
|
28
|
+
"videofolder",
|
|
29
|
+
"webdataset",
|
|
30
|
+
"xml",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
SKIP_DIRS = {
|
|
34
|
+
".git",
|
|
35
|
+
".hg",
|
|
36
|
+
".mypy_cache",
|
|
37
|
+
".nox",
|
|
38
|
+
".pytest_cache",
|
|
39
|
+
".ruff_cache",
|
|
40
|
+
".tox",
|
|
41
|
+
".venv",
|
|
42
|
+
"__pycache__",
|
|
43
|
+
"build",
|
|
44
|
+
"dist",
|
|
45
|
+
"node_modules",
|
|
46
|
+
"site-packages",
|
|
47
|
+
"venv",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
# (line, byte column) as reported by the ast module.
|
|
51
|
+
Position = Tuple[int, int]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Finding:
|
|
56
|
+
path: str
|
|
57
|
+
line: int
|
|
58
|
+
col: int
|
|
59
|
+
call: str
|
|
60
|
+
repo_id: str
|
|
61
|
+
repo_type: str
|
|
62
|
+
revision: Optional[str]
|
|
63
|
+
trust_remote_code: bool
|
|
64
|
+
insert_at: Position
|
|
65
|
+
revision_span: Optional[Tuple[Position, Position]] = None
|
|
66
|
+
# Indentation for a new argument line when arguments are one per line.
|
|
67
|
+
arg_indent: Optional[str] = None
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def status(self) -> str:
|
|
71
|
+
if self.revision is None:
|
|
72
|
+
return "unpinned"
|
|
73
|
+
if SHA_RE.fullmatch(self.revision):
|
|
74
|
+
return "pinned"
|
|
75
|
+
return "mutable"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _call_name(func: ast.expr) -> Optional[str]:
|
|
79
|
+
if isinstance(func, ast.Name):
|
|
80
|
+
return func.id
|
|
81
|
+
if isinstance(func, ast.Attribute):
|
|
82
|
+
return func.attr
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _str_const(node: Optional[ast.expr]) -> Optional[str]:
|
|
87
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
88
|
+
return node.value
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _kwarg(call: ast.Call, *names: str) -> Optional[ast.keyword]:
|
|
93
|
+
for keyword in call.keywords:
|
|
94
|
+
if keyword.arg in names:
|
|
95
|
+
return keyword
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _arg(call: ast.Call, index: int, *names: str) -> Optional[ast.expr]:
|
|
100
|
+
keyword = _kwarg(call, *names)
|
|
101
|
+
if keyword is not None:
|
|
102
|
+
return keyword.value
|
|
103
|
+
if len(call.args) > index and not any(isinstance(a, ast.Starred) for a in call.args[: index + 1]):
|
|
104
|
+
return call.args[index]
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _target(call: ast.Call) -> Optional[Tuple[ast.expr, str]]:
|
|
109
|
+
"""Return the repo id expression and repo type for a Hub download call."""
|
|
110
|
+
name = _call_name(call.func)
|
|
111
|
+
if name == "from_pretrained":
|
|
112
|
+
node = _arg(call, 0, "pretrained_model_name_or_path", "model_id")
|
|
113
|
+
if _str_const(node) is None:
|
|
114
|
+
# PeftModel.from_pretrained(base_model, "org/adapter")
|
|
115
|
+
node = _arg(call, 1, "model_id")
|
|
116
|
+
return (node, "model") if node is not None else None
|
|
117
|
+
if name == "SentenceTransformer":
|
|
118
|
+
node = _arg(call, 0, "model_name_or_path")
|
|
119
|
+
return (node, "model") if node is not None else None
|
|
120
|
+
if name == "pipeline":
|
|
121
|
+
node = _arg(call, 1, "model")
|
|
122
|
+
return (node, "model") if node is not None else None
|
|
123
|
+
if name in ("hf_hub_download", "snapshot_download"):
|
|
124
|
+
node = _arg(call, 0, "repo_id")
|
|
125
|
+
if node is None:
|
|
126
|
+
return None
|
|
127
|
+
repo_type = _str_const(getattr(_kwarg(call, "repo_type"), "value", None)) or "model"
|
|
128
|
+
return node, repo_type
|
|
129
|
+
if name == "load_dataset":
|
|
130
|
+
node = _arg(call, 0, "path")
|
|
131
|
+
return (node, "dataset") if node is not None else None
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _looks_like_hub_id(value: str, repo_type: str, base_dir: Path) -> bool:
|
|
136
|
+
if not REPO_ID_RE.fullmatch(value):
|
|
137
|
+
return False
|
|
138
|
+
if repo_type == "dataset" and value in BUILTIN_DATASET_BUILDERS:
|
|
139
|
+
return False
|
|
140
|
+
# A path that exists next to the file or in the working directory is local.
|
|
141
|
+
return not ((base_dir / value).exists() or Path(value).exists())
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _end(node: ast.AST) -> Position:
|
|
145
|
+
return node.end_lineno, node.end_col_offset # type: ignore[attr-defined]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def scan_source(source: str, path: str = "<string>") -> Iterator[Finding]:
|
|
149
|
+
"""Yield a Finding for every Hub download call with a literal repo id."""
|
|
150
|
+
tree = ast.parse(source, filename=path)
|
|
151
|
+
lines = source.splitlines()
|
|
152
|
+
base_dir = Path(path).parent
|
|
153
|
+
|
|
154
|
+
for node in ast.walk(tree):
|
|
155
|
+
if not isinstance(node, ast.Call):
|
|
156
|
+
continue
|
|
157
|
+
target = _target(node)
|
|
158
|
+
if target is None:
|
|
159
|
+
continue
|
|
160
|
+
repo_node, repo_type = target
|
|
161
|
+
repo_id = _str_const(repo_node)
|
|
162
|
+
if repo_id is None or repo_type not in ("model", "dataset", "space"):
|
|
163
|
+
continue
|
|
164
|
+
if not _looks_like_hub_id(repo_id, repo_type, base_dir):
|
|
165
|
+
continue
|
|
166
|
+
call_lines = lines[node.lineno - 1 : node.end_lineno]
|
|
167
|
+
if any(IGNORE_MARKER in line for line in call_lines):
|
|
168
|
+
continue
|
|
169
|
+
|
|
170
|
+
revision_kw = _kwarg(node, "revision")
|
|
171
|
+
revision: Optional[str] = None
|
|
172
|
+
revision_span = None
|
|
173
|
+
if revision_kw is not None:
|
|
174
|
+
revision = _str_const(revision_kw.value)
|
|
175
|
+
if revision is None:
|
|
176
|
+
# Computed revision (variable, f-string, ...): can't judge it.
|
|
177
|
+
continue
|
|
178
|
+
value = revision_kw.value
|
|
179
|
+
revision_span = ((value.lineno, value.col_offset), _end(value))
|
|
180
|
+
|
|
181
|
+
trust_kw = _kwarg(node, "trust_remote_code")
|
|
182
|
+
trust_remote_code = trust_kw is not None and not (
|
|
183
|
+
isinstance(trust_kw.value, ast.Constant) and trust_kw.value.value is False
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
last_arg = max(
|
|
187
|
+
list(node.args) + list(node.keywords),
|
|
188
|
+
key=lambda n: (n.lineno, n.col_offset),
|
|
189
|
+
)
|
|
190
|
+
arg_indent = None
|
|
191
|
+
if last_arg.lineno > node.lineno:
|
|
192
|
+
arg_line = lines[last_arg.lineno - 1]
|
|
193
|
+
arg_indent = arg_line[: len(arg_line) - len(arg_line.lstrip())]
|
|
194
|
+
line_bytes = lines[node.lineno - 1].encode()
|
|
195
|
+
col = len(line_bytes[: node.col_offset].decode(errors="replace"))
|
|
196
|
+
yield Finding(
|
|
197
|
+
path=path,
|
|
198
|
+
line=node.lineno,
|
|
199
|
+
col=col + 1,
|
|
200
|
+
call=ast.unparse(node.func),
|
|
201
|
+
repo_id=repo_id,
|
|
202
|
+
repo_type=repo_type,
|
|
203
|
+
revision=revision,
|
|
204
|
+
trust_remote_code=trust_remote_code,
|
|
205
|
+
insert_at=_end(last_arg),
|
|
206
|
+
revision_span=revision_span,
|
|
207
|
+
arg_indent=arg_indent,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def iter_python_files(paths, exclude=()) -> Iterator[Path]:
|
|
212
|
+
for raw in paths:
|
|
213
|
+
root = Path(raw)
|
|
214
|
+
if root.is_file():
|
|
215
|
+
yield root
|
|
216
|
+
continue
|
|
217
|
+
for file in sorted(root.rglob("*.py")):
|
|
218
|
+
rel = file.relative_to(root)
|
|
219
|
+
if any(part in SKIP_DIRS for part in rel.parts[:-1]):
|
|
220
|
+
continue
|
|
221
|
+
if any(file.match(pattern) for pattern in exclude):
|
|
222
|
+
continue
|
|
223
|
+
yield file
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hfpin
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pin Hugging Face models and datasets in your code to exact commits
|
|
5
|
+
Project-URL: Homepage, https://github.com/DipPansuriya/hfpin
|
|
6
|
+
Project-URL: Issues, https://github.com/DipPansuriya/hfpin/issues
|
|
7
|
+
Author: Dip Pansuriya
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: huggingface,mlops,pinning,security,supply-chain,transformers
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Classifier: Topic :: Security
|
|
17
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# hfpin
|
|
22
|
+
|
|
23
|
+
**Pin the Hugging Face models and datasets in your code to exact commits.**
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
# Before: downloads whatever is on the Hub today
|
|
27
|
+
model = AutoModel.from_pretrained("google-bert/bert-base-uncased")
|
|
28
|
+
|
|
29
|
+
# After `hfpin pin`: always the same files
|
|
30
|
+
model = AutoModel.from_pretrained("google-bert/bert-base-uncased", revision="86b5e0934494bd15c9632b12f734a8a67f723594")
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Why
|
|
34
|
+
|
|
35
|
+
`from_pretrained("org/model")` downloads the latest commit of the `main` branch. That commit can change at any time:
|
|
36
|
+
|
|
37
|
+
- **Silent changes.** The owner updates weights, tokenizer or config, and your results change with no code change on your side.
|
|
38
|
+
- **Supply chain attacks.** If the owner's account is compromised, the attacker's files go straight into your app. With `trust_remote_code=True`, that includes Python code that runs on your machine.
|
|
39
|
+
- **Reproducibility.** A paper, a test, or a training run from last month may not give the same result today.
|
|
40
|
+
|
|
41
|
+
Pinning a commit sha (`revision="<sha>"`) fixes all three. It is the same idea as pinning GitHub Actions to a sha, and Hugging Face [recommends it](https://huggingface.co/docs/huggingface_hub/guides/download#from-specific-version). Doing it by hand means looking up a 40-character sha for every model, which is why almost nobody does. `hfpin` does it for you.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install hfpin
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requires Python 3.10+. No dependencies.
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### Find unpinned downloads
|
|
54
|
+
|
|
55
|
+
```console
|
|
56
|
+
$ hfpin check
|
|
57
|
+
train.py:5:7: unpinned model 'bert-base-uncased' (AutoTokenizer.from_pretrained): add revision=<commit sha>
|
|
58
|
+
train.py:10:7: model 'distilbert/distilbert-base-uncased-finetuned-sst-2-english' (pipeline) uses revision 'main', which can change: use a commit sha
|
|
59
|
+
train.py:11:6: unpinned dataset 'stanfordnlp/imdb' (load_dataset): add revision=<commit sha>
|
|
60
|
+
train.py:13:7: warning: trust_remote_code runs Python code from 'microsoft/phi-2' and the code can change at any time
|
|
61
|
+
|
|
62
|
+
3 problem(s) found. Run `hfpin pin` to fix.
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`check` works offline and exits with code 1 when it finds a problem, so it fits in CI and pre-commit hooks.
|
|
66
|
+
|
|
67
|
+
Options:
|
|
68
|
+
|
|
69
|
+
| Option | What it does |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `--online` | Also checks that every repo and revision exists on the Hub. Catches typos and model names made up by AI assistants. |
|
|
72
|
+
| `--deny-license PATTERN` | Fails on models or datasets whose license matches, for example `--deny-license "cc-by-nc*"`. Repeatable. Implies `--online`. |
|
|
73
|
+
| `--allow-mutable` | Accepts branch and tag revisions such as `revision="v1.0"`. |
|
|
74
|
+
| `--format text\|json\|github` | Output format. `github` prints workflow annotations. |
|
|
75
|
+
| `--exclude GLOB` | Skips matching files. Repeatable. |
|
|
76
|
+
|
|
77
|
+
### Pin them
|
|
78
|
+
|
|
79
|
+
```console
|
|
80
|
+
$ hfpin pin
|
|
81
|
+
train.py:5:7: bert-base-uncased@main -> 86b5e0934494 (now 'google-bert/bert-base-uncased')
|
|
82
|
+
train.py:10:7: distilbert/distilbert-base-uncased-finetuned-sst-2-english@main -> 714eb0fa89d2
|
|
83
|
+
train.py:11:6: stanfordnlp/imdb@main -> e6281661ce1c
|
|
84
|
+
Pinned 3 download(s) in 1 file(s).
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`pin` looks up the current commit of each repo (or of the branch or tag you already use) and edits only the call, keeping your formatting. Use `--dry-run` to see a diff first. For private or gated repos, log in with `huggingface-cli login` or set `HF_TOKEN`.
|
|
88
|
+
|
|
89
|
+
To update a model later, delete its `revision=` and run `hfpin pin` again.
|
|
90
|
+
|
|
91
|
+
### GitHub Action
|
|
92
|
+
|
|
93
|
+
```yaml
|
|
94
|
+
- uses: actions/checkout@v4
|
|
95
|
+
- uses: DipPansuriya/hfpin@v0.1.0
|
|
96
|
+
with:
|
|
97
|
+
paths: src # default: .
|
|
98
|
+
args: --online --deny-license "cc-by-nc*" # optional
|
|
99
|
+
hf-token: ${{ secrets.HF_TOKEN }} # optional, for private or gated repos
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Problems show up as annotations on the pull request diff.
|
|
103
|
+
|
|
104
|
+
## What it detects
|
|
105
|
+
|
|
106
|
+
| Call | Repo type |
|
|
107
|
+
| --- | --- |
|
|
108
|
+
| `*.from_pretrained(...)` (transformers, diffusers, peft, timm, ...) | model |
|
|
109
|
+
| `pipeline(task, model=...)` | model |
|
|
110
|
+
| `SentenceTransformer(...)` | model |
|
|
111
|
+
| `hf_hub_download(...)`, `snapshot_download(...)` | model, dataset or space (`repo_type=`) |
|
|
112
|
+
| `load_dataset(...)` | dataset |
|
|
113
|
+
|
|
114
|
+
It only looks at repo names written as string literals. It skips local paths, built-in dataset loaders such as `load_dataset("csv", ...)`, and calls whose `revision=` is a variable.
|
|
115
|
+
|
|
116
|
+
To ignore a call, add `# hfpin: ignore` on any of its lines.
|
|
117
|
+
|
|
118
|
+
## Compared with Bandit
|
|
119
|
+
|
|
120
|
+
[Bandit](https://github.com/PyCQA/bandit) rule B615 warns about unpinned Hugging Face downloads. `hfpin` also fixes them, checks that the repos exist, and checks licenses.
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
hfpin/__init__.py,sha256=163i5QKfKJdUq2XfERvEW5HjokksRYtWA2cWH9xeM4U,84
|
|
2
|
+
hfpin/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
hfpin/cli.py,sha256=K3Y8oWMuLdnVHxgPg9MuN58DFo00-kGdyPmmDZPBxmg,8128
|
|
4
|
+
hfpin/hub.py,sha256=AMW7b497QGEOTAfcP-MntLFuDSrRlb0teo2c3LGUJZI,3032
|
|
5
|
+
hfpin/rewrite.py,sha256=RFTm5e_eWUpW6pw03OYGfEAsnXQnd2G3b3AiXyrbJ7c,1577
|
|
6
|
+
hfpin/scanner.py,sha256=s09IvgXxBJf4Bejg7pqbgwGOzzNx04SmlM9TjgmjFco,6953
|
|
7
|
+
hfpin-0.1.0.dist-info/METADATA,sha256=meCjIMuL4RpLml4RUxAU3VcjG7Wuyn7muN8cn5lFl4I,5240
|
|
8
|
+
hfpin-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
hfpin-0.1.0.dist-info/entry_points.txt,sha256=k2TVaYWTu1bEM_cwizvIbYzNvug3zsdLhCvbrAdzVz8,41
|
|
10
|
+
hfpin-0.1.0.dist-info/licenses/LICENSE,sha256=2jQ_xMTqg8aYoMktYgKcvkwzT5PYo7ueOqNBkLOwROE,1070
|
|
11
|
+
hfpin-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dip Pansuriya
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|