Skip to content

Commit af104c8

Browse files
Use new non-git based API (#8)
* Use new non-git base API * Update dependencies and version number Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
1 parent 085cccb commit af104c8

4 files changed

Lines changed: 60 additions & 58 deletions

File tree

README.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,8 @@ To check if the command has been registered successfully:
2525
python -m spacy huggingface-hub --help
2626
```
2727

28-
Hugging Face uses **Git Large File Storage** (LFS) to handle files larger than 10mb. You can find instructions on how to download it [here](https://git-lfs.github.com/).
2928

30-
You can then upload any pipeline packaged with [`spacy package`](https://spacy.io/api/cli#package). Make sure to set `--build wheel` to output a binary `.whl` file. The uploader will read all metadata from the pipeline package, including the auto-generated pretty `README.md` and the model details available in the `meta.json`.
29+
You can upload any pipeline packaged with [`spacy package`](https://spacy.io/api/cli#package). Make sure to set `--build wheel` to output a binary `.whl` file. The uploader will read all metadata from the pipeline package, including the auto-generated pretty `README.md` and the model details available in the `meta.json`.
3130

3231
```bash
3332
huggingface-cli login
@@ -68,7 +67,6 @@ python -m spacy_huggingface_hub push [whl_path] [--org] [--msg] [--local-repo] [
6867
| `whl_path` | str / `Path` | The path to the `.whl` file packaged with [`spacy package`](https://spacy.io/api/cli#package). |
6968
| `--org`, `-o` | str | Optional name of organization to which the pipeline should be uploaded. |
7069
| `--msg`, `-m` | str | Commit message to use for update. Defaults to `"Update spaCy pipeline"`. |
71-
| `--local-repo`, `-l` | str / `Path` | Local path to the model repository (will be created if it doesn't exist). Defaults to `hub` in the current working directory. |
7270
| `--verbose`, `-V` | bool | Output additional info for debugging, e.g. the full generated hub metadata. |
7371

7472
### Usage from Python

requirements.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
huggingface_hub>=0.0.12,<0.1.0
1+
huggingface_hub>=0.8.1,<0.1.0
22
wasabi>=0.8.1,<1.1.0
3-
typer>=0.3.0,<0.4.0
3+
typer>=0.3.0,<0.5.0
44
PyYAML

setup.cfg

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[metadata]
2-
version = 0.0.6
2+
version = 0.0.7
33
description = Quickly push your spaCy pipelines to the Hugging Face Hub
44
url = https://spacy.io
55
author = Explosion and Hugging Face
@@ -21,9 +21,9 @@ classifiers =
2121
[options]
2222
python_requires = >=3.6
2323
install_requires =
24-
huggingface_hub==0.0.12
24+
huggingface_hub>=0.8.1,<0.9.0
2525
wasabi>=0.8.1,<1.1.0
26-
typer>=0.3.0,<0.4.0
26+
typer>=0.3.0,<0.5.0
2727
PyYAML
2828

2929
[options.entry_points]

spacy_huggingface_hub/push.py

Lines changed: 54 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
import shutil
55
import json
66
import yaml
7-
from huggingface_hub import Repository, HfApi, HfFolder
7+
from huggingface_hub import HfApi, upload_folder, whoami
88
from pathlib import Path
9+
import tempfile
910
from wasabi import Printer
1011

1112
# Allow using the package without spaCy being installed
@@ -43,21 +44,19 @@ def huggingface_hub_push_cli(
4344
whl_path: Path = typer.Argument(..., help="Path to whl file", exists=True),
4445
organization: Optional[str] = typer.Option(None, "--org", "-o", help="Name of organization to which the pipeline should be uploaded"),
4546
commit_msg: str = typer.Option("Update spaCy pipeline", "--msg", "-m", help="Commit message to use for update"),
46-
local_repo_path: Path = typer.Option("hub", "--local-repo", "-l", help="Local path for creating repo"),
4747
verbose: bool = typer.Option(False, "--verbose", "-V", help="Output additional info for debugging, e.g. the full generated hub metadata"),
4848
# fmt: on
4949
):
5050
"""
5151
Push a spaCy pipeline (.whl) to the Hugging Face Hub.
5252
"""
53-
push(whl_path, organization, commit_msg, local_repo_path, verbose=verbose)
53+
push(whl_path, organization, commit_msg, verbose=verbose)
5454

5555

5656
def push(
5757
whl_path: Union[str, Path],
5858
namespace: Optional[str] = None,
5959
commit_msg: str = "Update spaCy pipeline",
60-
local_repo_path: Union[Path, str] = "hub",
6160
*,
6261
silent: bool = False,
6362
verbose: bool = False,
@@ -74,38 +73,38 @@ def push(
7473
)
7574
filename = whl_path.stem
7675
repo_name, version, _, _, _ = filename.split("-")
77-
versioned_name = repo_name + "-" + version
78-
repo_local_path = Path(local_repo_path) / repo_name
76+
77+
if namespace is None:
78+
namespace = whoami()["name"]
79+
repo_id = f"{namespace}/{repo_name}"
7980

8081
# Create the repo (or clone its content if it's nonempty)
81-
api = HfApi()
82-
repo_url = api.create_repo(
83-
name=repo_name,
84-
token=HfFolder.get_token(),
85-
organization=namespace,
82+
HfApi().create_repo(
83+
repo_id=repo_id,
8684
# TODO: Can we support private packages as well via a flag?
8785
private=False,
8886
exist_ok=True,
8987
)
90-
repo = Repository(repo_local_path, clone_from=repo_url)
91-
repo.git_pull(rebase=True)
92-
# TODO: Are there other files we need to add here?
93-
repo.lfs_track(["*.whl", "*.npz", "*strings.json", "vectors", "model"])
94-
info_msg = f"Publishing to repository '{repo_name}'"
95-
if namespace is not None:
96-
info_msg += f" ({namespace})"
97-
msg.info(info_msg)
98-
99-
# Extract information from whl file
100-
with zipfile.ZipFile(whl_path, "r") as zip_ref:
101-
base_name = Path(repo_name) / versioned_name
102-
for file_name in zip_ref.namelist():
103-
if str(Path(file_name)).startswith(str(base_name)):
104-
zip_ref.extract(file_name, local_repo_path)
105-
msg.good("Extracted information from .whl file")
106-
107-
# Move files up one directory when repo is not from HF
108-
if version != "any":
88+
msg.info(f"Publishing to repository '{repo_id}'")
89+
90+
with tempfile.TemporaryDirectory() as tmpdirname:
91+
repo_local_path = Path(tmpdirname) / repo_name
92+
# Extract information from whl file
93+
with zipfile.ZipFile(whl_path, "r") as zip_ref:
94+
for file_name in zip_ref.namelist():
95+
if Path(file_name) != Path(repo_name) / "__init__.py":
96+
print("result", zip_ref.extract(file_name, tmpdirname), file_name)
97+
msg.good("Extracted information from .whl file")
98+
99+
# Some whl files might not have the version in the name (such as the ones at HF)
100+
# but the version can be found in the meta.json file.
101+
if version == "any":
102+
version = json.load(open(Path(tmpdirname) / repo_name / "meta.json"))["version"]
103+
104+
# Move files up one directory
105+
# The original structure is ca_core/ca_core-version/files. files are moved one level
106+
# up.
107+
versioned_name = repo_name + "-" + version
109108
extracted_dir = repo_local_path / versioned_name
110109
for filename in extracted_dir.iterdir():
111110
dst = repo_local_path / filename.name
@@ -116,26 +115,31 @@ def push(
116115
shutil.move(str(filename), str(dst))
117116
shutil.rmtree(str(extracted_dir))
118117

119-
# Create model card, including HF tags
120-
metadata = _create_model_card(repo_name, repo_local_path)
121-
msg.good("Created model card")
122-
msg.text(f"{repo_name} (v{version})")
123-
if verbose:
124-
print(metadata)
125-
126-
# Remove version from whl filename
127-
dst_file = repo_local_path / f"{repo_name}-any-py3-none-any.whl"
128-
shutil.copyfile(str(whl_path), str(dst_file))
129-
130-
msg.text("Pushing repository to the hub...")
131-
url = repo.push_to_hub(commit_message=commit_msg)
132-
url, _ = url.split("/commit/")
133-
msg.good(f"Pushed repository '{repo_name}' to the hub")
134-
whl_url = f"{url}/resolve/main/{repo_name}-any-py3-none-any.whl"
135-
if not silent:
136-
print(f"\nView your model here:\n{url}\n")
137-
print(f"Install your model:\npip install {whl_url}")
138-
return {"url": url, "whl_url": whl_url}
118+
# Create model card, including HF tags
119+
metadata = _create_model_card(repo_name, repo_local_path)
120+
msg.good("Created model card")
121+
msg.text(f"{repo_name} (v{version})")
122+
if verbose:
123+
print(metadata)
124+
125+
# Remove version from whl filename
126+
dst_file = repo_local_path / f"{repo_name}-any-py3-none-any.whl"
127+
shutil.copyfile(str(whl_path), str(dst_file))
128+
129+
msg.text("Pushing repository to the hub...")
130+
url = upload_folder(
131+
repo_id=repo_id,
132+
folder_path=repo_local_path,
133+
path_in_repo="",
134+
commit_message=commit_msg,
135+
)
136+
url, _ = url.split("/tree/")
137+
msg.good(f"Pushed repository '{repo_name}' to the hub")
138+
whl_url = f"{url}/resolve/main/{repo_name}-any-py3-none-any.whl"
139+
if not silent:
140+
print(f"\nView your model here:\n{url}\n")
141+
print(f"Install your model:\npip install {whl_url}")
142+
return {"url": url, "whl_url": whl_url}
139143

140144

141145
def _create_model_card(repo_name: str, repo_dir: Path) -> Dict[str, Any]:

0 commit comments

Comments
 (0)