hfpin 0.1.0__tar.gz
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-0.1.0/.github/workflows/ci.yml +46 -0
- hfpin-0.1.0/.github/workflows/publish.yml +40 -0
- hfpin-0.1.0/.gitignore +5 -0
- hfpin-0.1.0/LICENSE +21 -0
- hfpin-0.1.0/PKG-INFO +124 -0
- hfpin-0.1.0/README.md +104 -0
- hfpin-0.1.0/action.yml +33 -0
- hfpin-0.1.0/examples/pinned.py +10 -0
- hfpin-0.1.0/examples/unpinned.py +9 -0
- hfpin-0.1.0/pyproject.toml +37 -0
- hfpin-0.1.0/src/hfpin/__init__.py +3 -0
- hfpin-0.1.0/src/hfpin/__main__.py +5 -0
- hfpin-0.1.0/src/hfpin/cli.py +203 -0
- hfpin-0.1.0/src/hfpin/hub.py +92 -0
- hfpin-0.1.0/src/hfpin/rewrite.py +41 -0
- hfpin-0.1.0/src/hfpin/scanner.py +223 -0
- hfpin-0.1.0/tests/test_cli.py +81 -0
- hfpin-0.1.0/tests/test_scanner_rewrite.py +137 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
strategy:
|
|
15
|
+
fail-fast: false
|
|
16
|
+
matrix:
|
|
17
|
+
python: ["3.10", "3.11", "3.12", "3.13", "3.14"]
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
20
|
+
with:
|
|
21
|
+
persist-credentials: false
|
|
22
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
23
|
+
with:
|
|
24
|
+
python-version: ${{ matrix.python }}
|
|
25
|
+
- run: pip install -e . pytest
|
|
26
|
+
- run: pytest -q
|
|
27
|
+
|
|
28
|
+
action:
|
|
29
|
+
runs-on: ubuntu-latest
|
|
30
|
+
steps:
|
|
31
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
32
|
+
with:
|
|
33
|
+
persist-credentials: false
|
|
34
|
+
- name: Action passes on pinned code
|
|
35
|
+
uses: ./
|
|
36
|
+
with:
|
|
37
|
+
paths: examples/pinned.py
|
|
38
|
+
args: --online --deny-license "cc-by-nc*"
|
|
39
|
+
- name: Action fails on unpinned code
|
|
40
|
+
id: unpinned
|
|
41
|
+
continue-on-error: true
|
|
42
|
+
uses: ./
|
|
43
|
+
with:
|
|
44
|
+
paths: examples/unpinned.py
|
|
45
|
+
- if: steps.unpinned.outcome != 'failure'
|
|
46
|
+
run: exit 1
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
workflow_dispatch:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
build:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
16
|
+
with:
|
|
17
|
+
persist-credentials: false
|
|
18
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
19
|
+
with:
|
|
20
|
+
python-version: "3.13"
|
|
21
|
+
- run: pip install build && python -m build
|
|
22
|
+
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
|
23
|
+
with:
|
|
24
|
+
name: dist
|
|
25
|
+
path: dist/
|
|
26
|
+
|
|
27
|
+
publish:
|
|
28
|
+
needs: build
|
|
29
|
+
runs-on: ubuntu-latest
|
|
30
|
+
environment:
|
|
31
|
+
name: pypi
|
|
32
|
+
url: https://pypi.org/project/hfpin/
|
|
33
|
+
permissions:
|
|
34
|
+
id-token: write
|
|
35
|
+
steps:
|
|
36
|
+
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
|
37
|
+
with:
|
|
38
|
+
name: dist
|
|
39
|
+
path: dist/
|
|
40
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
hfpin-0.1.0/.gitignore
ADDED
hfpin-0.1.0/LICENSE
ADDED
|
@@ -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.
|
hfpin-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
hfpin-0.1.0/README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# hfpin
|
|
2
|
+
|
|
3
|
+
**Pin the Hugging Face models and datasets in your code to exact commits.**
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
# Before: downloads whatever is on the Hub today
|
|
7
|
+
model = AutoModel.from_pretrained("google-bert/bert-base-uncased")
|
|
8
|
+
|
|
9
|
+
# After `hfpin pin`: always the same files
|
|
10
|
+
model = AutoModel.from_pretrained("google-bert/bert-base-uncased", revision="86b5e0934494bd15c9632b12f734a8a67f723594")
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Why
|
|
14
|
+
|
|
15
|
+
`from_pretrained("org/model")` downloads the latest commit of the `main` branch. That commit can change at any time:
|
|
16
|
+
|
|
17
|
+
- **Silent changes.** The owner updates weights, tokenizer or config, and your results change with no code change on your side.
|
|
18
|
+
- **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.
|
|
19
|
+
- **Reproducibility.** A paper, a test, or a training run from last month may not give the same result today.
|
|
20
|
+
|
|
21
|
+
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.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install hfpin
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Requires Python 3.10+. No dependencies.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
### Find unpinned downloads
|
|
34
|
+
|
|
35
|
+
```console
|
|
36
|
+
$ hfpin check
|
|
37
|
+
train.py:5:7: unpinned model 'bert-base-uncased' (AutoTokenizer.from_pretrained): add revision=<commit sha>
|
|
38
|
+
train.py:10:7: model 'distilbert/distilbert-base-uncased-finetuned-sst-2-english' (pipeline) uses revision 'main', which can change: use a commit sha
|
|
39
|
+
train.py:11:6: unpinned dataset 'stanfordnlp/imdb' (load_dataset): add revision=<commit sha>
|
|
40
|
+
train.py:13:7: warning: trust_remote_code runs Python code from 'microsoft/phi-2' and the code can change at any time
|
|
41
|
+
|
|
42
|
+
3 problem(s) found. Run `hfpin pin` to fix.
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`check` works offline and exits with code 1 when it finds a problem, so it fits in CI and pre-commit hooks.
|
|
46
|
+
|
|
47
|
+
Options:
|
|
48
|
+
|
|
49
|
+
| Option | What it does |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `--online` | Also checks that every repo and revision exists on the Hub. Catches typos and model names made up by AI assistants. |
|
|
52
|
+
| `--deny-license PATTERN` | Fails on models or datasets whose license matches, for example `--deny-license "cc-by-nc*"`. Repeatable. Implies `--online`. |
|
|
53
|
+
| `--allow-mutable` | Accepts branch and tag revisions such as `revision="v1.0"`. |
|
|
54
|
+
| `--format text\|json\|github` | Output format. `github` prints workflow annotations. |
|
|
55
|
+
| `--exclude GLOB` | Skips matching files. Repeatable. |
|
|
56
|
+
|
|
57
|
+
### Pin them
|
|
58
|
+
|
|
59
|
+
```console
|
|
60
|
+
$ hfpin pin
|
|
61
|
+
train.py:5:7: bert-base-uncased@main -> 86b5e0934494 (now 'google-bert/bert-base-uncased')
|
|
62
|
+
train.py:10:7: distilbert/distilbert-base-uncased-finetuned-sst-2-english@main -> 714eb0fa89d2
|
|
63
|
+
train.py:11:6: stanfordnlp/imdb@main -> e6281661ce1c
|
|
64
|
+
Pinned 3 download(s) in 1 file(s).
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`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`.
|
|
68
|
+
|
|
69
|
+
To update a model later, delete its `revision=` and run `hfpin pin` again.
|
|
70
|
+
|
|
71
|
+
### GitHub Action
|
|
72
|
+
|
|
73
|
+
```yaml
|
|
74
|
+
- uses: actions/checkout@v4
|
|
75
|
+
- uses: DipPansuriya/hfpin@v0.1.0
|
|
76
|
+
with:
|
|
77
|
+
paths: src # default: .
|
|
78
|
+
args: --online --deny-license "cc-by-nc*" # optional
|
|
79
|
+
hf-token: ${{ secrets.HF_TOKEN }} # optional, for private or gated repos
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Problems show up as annotations on the pull request diff.
|
|
83
|
+
|
|
84
|
+
## What it detects
|
|
85
|
+
|
|
86
|
+
| Call | Repo type |
|
|
87
|
+
| --- | --- |
|
|
88
|
+
| `*.from_pretrained(...)` (transformers, diffusers, peft, timm, ...) | model |
|
|
89
|
+
| `pipeline(task, model=...)` | model |
|
|
90
|
+
| `SentenceTransformer(...)` | model |
|
|
91
|
+
| `hf_hub_download(...)`, `snapshot_download(...)` | model, dataset or space (`repo_type=`) |
|
|
92
|
+
| `load_dataset(...)` | dataset |
|
|
93
|
+
|
|
94
|
+
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.
|
|
95
|
+
|
|
96
|
+
To ignore a call, add `# hfpin: ignore` on any of its lines.
|
|
97
|
+
|
|
98
|
+
## Compared with Bandit
|
|
99
|
+
|
|
100
|
+
[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.
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT
|
hfpin-0.1.0/action.yml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
name: hfpin
|
|
2
|
+
description: Fail when Hugging Face models or datasets in your code are not pinned to an exact commit
|
|
3
|
+
author: Dip Pansuriya
|
|
4
|
+
branding:
|
|
5
|
+
icon: lock
|
|
6
|
+
color: yellow
|
|
7
|
+
inputs:
|
|
8
|
+
paths:
|
|
9
|
+
description: Files or directories to check, separated by spaces
|
|
10
|
+
default: "."
|
|
11
|
+
args:
|
|
12
|
+
description: Extra arguments for `hfpin check`, for example `--online --deny-license "cc-by-nc*"`
|
|
13
|
+
default: ""
|
|
14
|
+
hf-token:
|
|
15
|
+
description: Hugging Face token, needed with --online for private or gated repos
|
|
16
|
+
default: ""
|
|
17
|
+
runs:
|
|
18
|
+
using: composite
|
|
19
|
+
steps:
|
|
20
|
+
- name: Check Hugging Face pins
|
|
21
|
+
shell: bash
|
|
22
|
+
env:
|
|
23
|
+
HFPIN_PATHS: ${{ inputs.paths }}
|
|
24
|
+
HFPIN_ARGS: ${{ inputs.args }}
|
|
25
|
+
HF_TOKEN: ${{ inputs.hf-token }}
|
|
26
|
+
PYTHONPATH: ${{ github.action_path }}/src
|
|
27
|
+
run: |
|
|
28
|
+
python3 - <<'PY'
|
|
29
|
+
import os, shlex, sys
|
|
30
|
+
from hfpin.cli import main
|
|
31
|
+
args = shlex.split(os.environ["HFPIN_ARGS"]) + shlex.split(os.environ["HFPIN_PATHS"])
|
|
32
|
+
sys.exit(main(["check", "--format", "github", *args]))
|
|
33
|
+
PY
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from datasets import load_dataset
|
|
2
|
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
|
3
|
+
|
|
4
|
+
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased", revision="12040accade4e8a0f71eabdb258fecc2e7e948be")
|
|
5
|
+
model = AutoModelForSequenceClassification.from_pretrained(
|
|
6
|
+
"distilbert/distilbert-base-uncased",
|
|
7
|
+
num_labels=2,
|
|
8
|
+
revision="12040accade4e8a0f71eabdb258fecc2e7e948be",
|
|
9
|
+
)
|
|
10
|
+
dataset = load_dataset("stanfordnlp/imdb", revision="e6281661ce1c48d982bc483cf8a173c1bbeb5d31")
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from datasets import load_dataset
|
|
2
|
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
|
3
|
+
|
|
4
|
+
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
|
|
5
|
+
model = AutoModelForSequenceClassification.from_pretrained(
|
|
6
|
+
"distilbert/distilbert-base-uncased",
|
|
7
|
+
num_labels=2,
|
|
8
|
+
)
|
|
9
|
+
dataset = load_dataset("stanfordnlp/imdb", revision="main")
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hfpin"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Pin Hugging Face models and datasets in your code to exact commits"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Dip Pansuriya" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = []
|
|
15
|
+
keywords = ["huggingface", "supply-chain", "security", "transformers", "pinning", "mlops"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Environment :: Console",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
"Topic :: Security",
|
|
23
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/DipPansuriya/hfpin"
|
|
28
|
+
Issues = "https://github.com/DipPansuriya/hfpin/issues"
|
|
29
|
+
|
|
30
|
+
[project.scripts]
|
|
31
|
+
hfpin = "hfpin.cli:main"
|
|
32
|
+
|
|
33
|
+
[tool.hatch.version]
|
|
34
|
+
path = "src/hfpin/__init__.py"
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
testpaths = ["tests"]
|
|
@@ -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)
|
|
@@ -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
|
+
)
|
|
@@ -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()
|
|
@@ -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,81 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from hfpin import cli
|
|
6
|
+
from hfpin.hub import RepoInfo, RepoNotFound
|
|
7
|
+
|
|
8
|
+
SHA = "b" * 40
|
|
9
|
+
REPOS = {
|
|
10
|
+
"google-bert/bert-base-uncased": RepoInfo("google-bert/bert-base-uncased", SHA, "apache-2.0", False),
|
|
11
|
+
"bert-base-uncased": RepoInfo("google-bert/bert-base-uncased", SHA, "apache-2.0", False),
|
|
12
|
+
"org/nc-model": RepoInfo("org/nc-model", SHA, "cc-by-nc-4.0", True),
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture(autouse=True)
|
|
17
|
+
def fake_hub(monkeypatch):
|
|
18
|
+
def resolve(self, repo_id, repo_type="model", revision="main"):
|
|
19
|
+
if repo_id not in REPOS:
|
|
20
|
+
raise RepoNotFound(f"{repo_type} '{repo_id}' at revision '{revision}' not found on the Hub")
|
|
21
|
+
return REPOS[repo_id]
|
|
22
|
+
|
|
23
|
+
monkeypatch.setattr(cli.Hub, "resolve", resolve)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.fixture
|
|
27
|
+
def project(tmp_path, monkeypatch):
|
|
28
|
+
monkeypatch.chdir(tmp_path)
|
|
29
|
+
(tmp_path / "train.py").write_text(
|
|
30
|
+
'tok = AutoTokenizer.from_pretrained("bert-base-uncased")\n'
|
|
31
|
+
'model = AutoModel.from_pretrained("org/nc-model", trust_remote_code=True)\n'
|
|
32
|
+
)
|
|
33
|
+
return tmp_path
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_check_reports_unpinned_and_fails(project, capsys):
|
|
37
|
+
assert cli.main(["check"]) == 1
|
|
38
|
+
out = capsys.readouterr().out
|
|
39
|
+
assert "train.py:1:7: unpinned model 'bert-base-uncased'" in out
|
|
40
|
+
assert "warning: trust_remote_code runs Python code from 'org/nc-model'" in out
|
|
41
|
+
assert "Run `hfpin pin` to fix." in out
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_check_json_with_license_policy(project, capsys):
|
|
45
|
+
assert cli.main(["check", "--format", "json", "--deny-license", "cc-by-nc*"]) == 1
|
|
46
|
+
kinds = {(p["repo_id"], p["kind"]) for p in json.loads(capsys.readouterr().out)}
|
|
47
|
+
assert ("org/nc-model", "license") in kinds
|
|
48
|
+
assert ("org/nc-model", "gated") in kinds
|
|
49
|
+
assert ("bert-base-uncased", "license") not in kinds
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_check_github_annotations(project, capsys):
|
|
53
|
+
cli.main(["check", "--format", "github"])
|
|
54
|
+
assert "::error file=train.py,line=1,col=7,title=hfpin unpinned::" in capsys.readouterr().out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_pin_then_check_passes(project, capsys):
|
|
58
|
+
assert cli.main(["pin"]) == 0
|
|
59
|
+
assert f'from_pretrained("bert-base-uncased", revision="{SHA}")' in (project / "train.py").read_text()
|
|
60
|
+
assert "(now 'google-bert/bert-base-uncased')" in capsys.readouterr().err
|
|
61
|
+
assert cli.main(["check"]) == 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_pin_dry_run_does_not_write(project, capsys):
|
|
65
|
+
before = (project / "train.py").read_text()
|
|
66
|
+
assert cli.main(["pin", "--dry-run"]) == 0
|
|
67
|
+
assert (project / "train.py").read_text() == before
|
|
68
|
+
assert f'+tok = AutoTokenizer.from_pretrained("bert-base-uncased", revision="{SHA}")' in capsys.readouterr().out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_pin_skips_missing_repo(project, capsys):
|
|
72
|
+
(project / "other.py").write_text('m = AutoModel.from_pretrained("org/made-up-model")\n')
|
|
73
|
+
assert cli.main(["pin"]) == 1
|
|
74
|
+
assert "not found on the Hub" in capsys.readouterr().err
|
|
75
|
+
assert "revision" not in (project / "other.py").read_text()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_check_online_flags_missing_repo(project, capsys):
|
|
79
|
+
(project / "other.py").write_text(f'm = AutoModel.from_pretrained("org/made-up-model", revision="{SHA}")\n')
|
|
80
|
+
assert cli.main(["check", "--online", "other.py"]) == 1
|
|
81
|
+
assert "made-up name?" in capsys.readouterr().out
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import textwrap
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from hfpin.rewrite import pin_source
|
|
7
|
+
from hfpin.scanner import scan_source
|
|
8
|
+
|
|
9
|
+
SHA = "a" * 40
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def scan(code, path="<string>"):
|
|
13
|
+
return list(scan_source(textwrap.dedent(code), path))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.mark.parametrize(
|
|
17
|
+
"code, repo_id, repo_type",
|
|
18
|
+
[
|
|
19
|
+
('AutoModel.from_pretrained("org/model")', "org/model", "model"),
|
|
20
|
+
('AutoTokenizer.from_pretrained(pretrained_model_name_or_path="gpt2")', "gpt2", "model"),
|
|
21
|
+
('PeftModel.from_pretrained(base, "org/adapter")', "org/adapter", "model"),
|
|
22
|
+
('SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")', "sentence-transformers/all-MiniLM-L6-v2", "model"),
|
|
23
|
+
('pipeline("text-generation", model="org/model")', "org/model", "model"),
|
|
24
|
+
('pipeline("text-generation", "org/model")', "org/model", "model"),
|
|
25
|
+
('hf_hub_download("org/model", "config.json")', "org/model", "model"),
|
|
26
|
+
('snapshot_download(repo_id="org/data", repo_type="dataset")', "org/data", "dataset"),
|
|
27
|
+
('datasets.load_dataset("org/data", split="train")', "org/data", "dataset"),
|
|
28
|
+
],
|
|
29
|
+
)
|
|
30
|
+
def test_detects_hub_downloads(code, repo_id, repo_type):
|
|
31
|
+
[finding] = scan(code)
|
|
32
|
+
assert (finding.repo_id, finding.repo_type, finding.status) == (repo_id, repo_type, "unpinned")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@pytest.mark.parametrize(
|
|
36
|
+
"code",
|
|
37
|
+
[
|
|
38
|
+
'load_dataset("csv", data_files="train.csv")',
|
|
39
|
+
"AutoModel.from_pretrained(model_name)",
|
|
40
|
+
'AutoModel.from_pretrained("./checkpoints/run-1")',
|
|
41
|
+
'AutoModel.from_pretrained("org/model", revision=REVISION)',
|
|
42
|
+
'AutoModel.from_pretrained("org/model") # hfpin: ignore',
|
|
43
|
+
'pipeline("sentiment-analysis")',
|
|
44
|
+
'other_function("org/model")',
|
|
45
|
+
],
|
|
46
|
+
)
|
|
47
|
+
def test_ignores_non_hub_or_unknown_calls(code):
|
|
48
|
+
assert scan(code) == []
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_skips_existing_local_directory(tmp_path):
|
|
52
|
+
(tmp_path / "my-model").mkdir()
|
|
53
|
+
assert scan('AutoModel.from_pretrained("my-model")', str(tmp_path / "train.py")) == []
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_classifies_revisions():
|
|
57
|
+
findings = scan(
|
|
58
|
+
f"""
|
|
59
|
+
AutoModel.from_pretrained("org/a", revision="{SHA}")
|
|
60
|
+
AutoModel.from_pretrained("org/b", revision="v1.0")
|
|
61
|
+
AutoModel.from_pretrained("org/c")
|
|
62
|
+
"""
|
|
63
|
+
)
|
|
64
|
+
assert [f.status for f in findings] == ["pinned", "mutable", "unpinned"]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_trust_remote_code_flag():
|
|
68
|
+
on, off = scan(
|
|
69
|
+
"""
|
|
70
|
+
AutoModel.from_pretrained("org/a", trust_remote_code=True)
|
|
71
|
+
AutoModel.from_pretrained("org/b", trust_remote_code=False)
|
|
72
|
+
"""
|
|
73
|
+
)
|
|
74
|
+
assert on.trust_remote_code and not off.trust_remote_code
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def pin(code):
|
|
78
|
+
code = textwrap.dedent(code)
|
|
79
|
+
result = pin_source(code, [(f, SHA) for f in scan_source(code)])
|
|
80
|
+
ast.parse(result)
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_pin_inline_call():
|
|
85
|
+
assert pin('m = AutoModel.from_pretrained("org/m", dtype="auto")\n') == (
|
|
86
|
+
f'm = AutoModel.from_pretrained("org/m", dtype="auto", revision="{SHA}")\n'
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_pin_replaces_mutable_revision_keeping_quotes():
|
|
91
|
+
assert pin("m = AutoModel.from_pretrained('org/m', revision='main')\n") == (
|
|
92
|
+
f"m = AutoModel.from_pretrained('org/m', revision='{SHA}')\n"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_pin_one_argument_per_line_with_trailing_comma():
|
|
97
|
+
assert pin(
|
|
98
|
+
"""\
|
|
99
|
+
m = AutoModel.from_pretrained(
|
|
100
|
+
"org/m",
|
|
101
|
+
dtype="auto",
|
|
102
|
+
)
|
|
103
|
+
"""
|
|
104
|
+
) == textwrap.dedent(
|
|
105
|
+
f"""\
|
|
106
|
+
m = AutoModel.from_pretrained(
|
|
107
|
+
"org/m",
|
|
108
|
+
dtype="auto",
|
|
109
|
+
revision="{SHA}",
|
|
110
|
+
)
|
|
111
|
+
"""
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_pin_one_argument_per_line_without_trailing_comma():
|
|
116
|
+
assert pin(
|
|
117
|
+
"""\
|
|
118
|
+
m = AutoModel.from_pretrained(
|
|
119
|
+
"org/m"
|
|
120
|
+
)
|
|
121
|
+
"""
|
|
122
|
+
) == textwrap.dedent(
|
|
123
|
+
f"""\
|
|
124
|
+
m = AutoModel.from_pretrained(
|
|
125
|
+
"org/m",
|
|
126
|
+
revision="{SHA}"
|
|
127
|
+
)
|
|
128
|
+
"""
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_pin_handles_multiple_calls_and_non_ascii_text():
|
|
133
|
+
result = pin('a = ("é", AutoTokenizer.from_pretrained("org/t"), AutoModel.from_pretrained("org/m"))\n')
|
|
134
|
+
assert result == (
|
|
135
|
+
f'a = ("é", AutoTokenizer.from_pretrained("org/t", revision="{SHA}"), '
|
|
136
|
+
f'AutoModel.from_pretrained("org/m", revision="{SHA}"))\n'
|
|
137
|
+
)
|