hf-rdm 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.
- hf_rdm-0.1.0/.gitignore +3 -0
- hf_rdm-0.1.0/LICENSE +21 -0
- hf_rdm-0.1.0/PKG-INFO +90 -0
- hf_rdm-0.1.0/README.md +77 -0
- hf_rdm-0.1.0/hf_rdm/__init__.py +28 -0
- hf_rdm-0.1.0/hf_rdm/hub.py +220 -0
- hf_rdm-0.1.0/hf_rdm/invenio.py +199 -0
- hf_rdm-0.1.0/hf_rdm/switch.py +53 -0
- hf_rdm-0.1.0/hf_rdm/upload.py +58 -0
- hf_rdm-0.1.0/hf_rdm.pth +1 -0
- hf_rdm-0.1.0/hf_rdm.start +1 -0
- hf_rdm-0.1.0/pyproject.toml +23 -0
- hf_rdm-0.1.0/tests/test_read.py +71 -0
- hf_rdm-0.1.0/tests/test_upload.py +89 -0
hf_rdm-0.1.0/.gitignore
ADDED
hf_rdm-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ülkü Tuncer Küçüktaş
|
|
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.
|
hf_rdm-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hf-rdm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read records of InvenioRDM repositories such as Aperta and Zenodo, and upload and publish there, with the unchanged Hugging Face libraries
|
|
5
|
+
Project-URL: Repository, https://github.com/UlkuTuncerKucuktas/hf-rdm
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: huggingface,inveniordm,open science,research data,zenodo
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Requires-Dist: httpx2<3,>=2
|
|
11
|
+
Requires-Dist: huggingface-hub<3,>=2.5
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# hf-rdm
|
|
15
|
+
|
|
16
|
+
Keep models and datasets in an InvenioRDM repository, such as Aperta or Zenodo, and push, pull and publish them with the unchanged Hugging Face libraries.
|
|
17
|
+
|
|
18
|
+
## 1. Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install hf-rdm
|
|
22
|
+
export HF_RDM=1
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`HF_RDM=1` switches it on. In a notebook, `hf_rdm.on()` in the first cell does the same, before a Hugging Face library is imported.
|
|
26
|
+
|
|
27
|
+
## 2. Add your key
|
|
28
|
+
|
|
29
|
+
Make a token in your account at the repository, at `<its address>/account/settings/applications/tokens/new/`, and give it next to the repository's address. It goes nowhere else. Pulling a published record needs no key.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
export HF_RDM_TOKENS="https://aperta.ulakbim.gov.tr=<your token>"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## 3. Add a repository
|
|
36
|
+
|
|
37
|
+
Aperta and Zenodo are known as `aperta` and `zenodo`. Any other InvenioRDM repository gets a short name you choose, and its DOI prefix if you want to name its records by DOI:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
export HF_RDM_SITES="tuwien=https://researchdata.tuwien.ac.at 10.48436=https://researchdata.tuwien.ac.at"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 4. Push a model
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
model.push_to_hub("aperta/my-bert")
|
|
47
|
+
tokenizer.push_to_hub("aperta/my-bert")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
This fills a draft titled `my-bert`, a new one or your draft with that title, and prints its id, such as `aperta/304123`. Nobody else sees a draft. `Dataset.push_to_hub`, `upload_folder` and `hf upload` work the same way. A later push replaces a file, and `delete_repo` discards the draft. The files wait in the folder `hf-rdm` of the Hugging Face cache until they are sent, so a push needs that much free disk.
|
|
51
|
+
|
|
52
|
+
## 5. Pull a model
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
model = AutoModel.from_pretrained("aperta/my-bert")
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
With your key this reads your draft, by its title or by its id. Once it is published, anyone reads it by its id or its DOI, without a key:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
AutoModel.from_pretrained("aperta/304123")
|
|
62
|
+
AutoTokenizer.from_pretrained("10.48623/aperta.304123")
|
|
63
|
+
load_dataset("aperta/303981", data_files="STI_Knowledge_Attitudes_Medical_Students_Data.csv")
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`hf download aperta/304005 --repo-type dataset` works too. Every name that is not a repository's goes to huggingface.co as before.
|
|
67
|
+
|
|
68
|
+
## 6. Publish
|
|
69
|
+
|
|
70
|
+
Publishing cannot be taken back, so it is a call of its own. It returns the DOI.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import hf_rdm
|
|
74
|
+
|
|
75
|
+
hf_rdm.publish(
|
|
76
|
+
"aperta/my-bert",
|
|
77
|
+
creators=["Yılmaz, Ayşe"],
|
|
78
|
+
license="cc-by-4.0",
|
|
79
|
+
publisher="Aperta",
|
|
80
|
+
fields={"custom_fields.aperta:science_branches": [{"id": "sub_991"}]},
|
|
81
|
+
)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
A creator written as `Family, Given` is a person, any other name is an organisation. Every other field has the name the repository itself uses, and a name that is not a Python word goes in `fields`. When a field is missing, the repository says which, and nothing is published. `hf_rdm.choices("aperta", "aperta:science_branches", "dil")` lists the ids such a field allows.
|
|
85
|
+
|
|
86
|
+
## What was tried
|
|
87
|
+
|
|
88
|
+
Pulling from Aperta, Zenodo and TU Wien. Pushing into drafts on Aperta and on Zenodo Sandbox, Zenodo's site for tests. Publishing on both: the ten records of [aperta-model-repository](https://github.com/UlkuTuncerKucuktas/aperta-model-repository) were filled and published on Aperta with it. A published record takes no more files, and a new version of one is not built yet.
|
|
89
|
+
|
|
90
|
+
The tests read from Aperta, Zenodo, TU Wien and the Hub: `pip install pytest transformers datasets`, then `HF_RDM=1 pytest`. With a Zenodo Sandbox token in `HF_RDM_TOKENS` they also fill drafts there and discard them.
|
hf_rdm-0.1.0/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# hf-rdm
|
|
2
|
+
|
|
3
|
+
Keep models and datasets in an InvenioRDM repository, such as Aperta or Zenodo, and push, pull and publish them with the unchanged Hugging Face libraries.
|
|
4
|
+
|
|
5
|
+
## 1. Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install hf-rdm
|
|
9
|
+
export HF_RDM=1
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`HF_RDM=1` switches it on. In a notebook, `hf_rdm.on()` in the first cell does the same, before a Hugging Face library is imported.
|
|
13
|
+
|
|
14
|
+
## 2. Add your key
|
|
15
|
+
|
|
16
|
+
Make a token in your account at the repository, at `<its address>/account/settings/applications/tokens/new/`, and give it next to the repository's address. It goes nowhere else. Pulling a published record needs no key.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
export HF_RDM_TOKENS="https://aperta.ulakbim.gov.tr=<your token>"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## 3. Add a repository
|
|
23
|
+
|
|
24
|
+
Aperta and Zenodo are known as `aperta` and `zenodo`. Any other InvenioRDM repository gets a short name you choose, and its DOI prefix if you want to name its records by DOI:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
export HF_RDM_SITES="tuwien=https://researchdata.tuwien.ac.at 10.48436=https://researchdata.tuwien.ac.at"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## 4. Push a model
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
model.push_to_hub("aperta/my-bert")
|
|
34
|
+
tokenizer.push_to_hub("aperta/my-bert")
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
This fills a draft titled `my-bert`, a new one or your draft with that title, and prints its id, such as `aperta/304123`. Nobody else sees a draft. `Dataset.push_to_hub`, `upload_folder` and `hf upload` work the same way. A later push replaces a file, and `delete_repo` discards the draft. The files wait in the folder `hf-rdm` of the Hugging Face cache until they are sent, so a push needs that much free disk.
|
|
38
|
+
|
|
39
|
+
## 5. Pull a model
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
model = AutoModel.from_pretrained("aperta/my-bert")
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
With your key this reads your draft, by its title or by its id. Once it is published, anyone reads it by its id or its DOI, without a key:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
AutoModel.from_pretrained("aperta/304123")
|
|
49
|
+
AutoTokenizer.from_pretrained("10.48623/aperta.304123")
|
|
50
|
+
load_dataset("aperta/303981", data_files="STI_Knowledge_Attitudes_Medical_Students_Data.csv")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`hf download aperta/304005 --repo-type dataset` works too. Every name that is not a repository's goes to huggingface.co as before.
|
|
54
|
+
|
|
55
|
+
## 6. Publish
|
|
56
|
+
|
|
57
|
+
Publishing cannot be taken back, so it is a call of its own. It returns the DOI.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import hf_rdm
|
|
61
|
+
|
|
62
|
+
hf_rdm.publish(
|
|
63
|
+
"aperta/my-bert",
|
|
64
|
+
creators=["Yılmaz, Ayşe"],
|
|
65
|
+
license="cc-by-4.0",
|
|
66
|
+
publisher="Aperta",
|
|
67
|
+
fields={"custom_fields.aperta:science_branches": [{"id": "sub_991"}]},
|
|
68
|
+
)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
A creator written as `Family, Given` is a person, any other name is an organisation. Every other field has the name the repository itself uses, and a name that is not a Python word goes in `fields`. When a field is missing, the repository says which, and nothing is published. `hf_rdm.choices("aperta", "aperta:science_branches", "dil")` lists the ids such a field allows.
|
|
72
|
+
|
|
73
|
+
## What was tried
|
|
74
|
+
|
|
75
|
+
Pulling from Aperta, Zenodo and TU Wien. Pushing into drafts on Aperta and on Zenodo Sandbox, Zenodo's site for tests. Publishing on both: the ten records of [aperta-model-repository](https://github.com/UlkuTuncerKucuktas/aperta-model-repository) were filled and published on Aperta with it. A published record takes no more files, and a new version of one is not built yet.
|
|
76
|
+
|
|
77
|
+
The tests read from Aperta, Zenodo, TU Wien and the Hub: `pip install pytest transformers datasets`, then `HF_RDM=1 pytest`. With a Zenodo Sandbox token in `HF_RDM_TOKENS` they also fill drafts there and discard them.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from . import switch
|
|
5
|
+
|
|
6
|
+
# The startup file loads this package in every Python process, so the Hub library is loaded only inside a call.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def on():
|
|
10
|
+
# For a notebook, where HF_RDM cannot be set before Python starts. A cell that runs again changes nothing.
|
|
11
|
+
if os.environ.get("HF_ENDPOINT") == "https://hf-rdm.invalid":
|
|
12
|
+
return
|
|
13
|
+
if "huggingface_hub" in sys.modules:
|
|
14
|
+
raise RuntimeError("hf_rdm.on() has to come before the first import of a Hugging Face library")
|
|
15
|
+
os.environ["HF_RDM"] = "1"
|
|
16
|
+
switch.on()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def publish(repo, creators, license=None, fields=None, **more):
|
|
20
|
+
from . import invenio
|
|
21
|
+
|
|
22
|
+
return invenio.publish(repo, creators, license, fields, **more)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def choices(first, name, text=""):
|
|
26
|
+
from . import invenio
|
|
27
|
+
|
|
28
|
+
return invenio.choices(first, name, text)
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
from urllib.parse import parse_qs
|
|
5
|
+
|
|
6
|
+
import httpx2
|
|
7
|
+
from huggingface_hub import get_session
|
|
8
|
+
|
|
9
|
+
from . import invenio as repository
|
|
10
|
+
from . import upload
|
|
11
|
+
|
|
12
|
+
REPO = r"[^/]+/[^/]+"
|
|
13
|
+
API = rf"/api/(?:models|datasets)/{REPO}"
|
|
14
|
+
INFO = rf"{API}(?:/revision/(?P<revision>[^/]+))?"
|
|
15
|
+
TREE = rf"{API}/tree/(?P<revision>[^/]+)/?(?P<folder>.*)"
|
|
16
|
+
PATHS = rf"{API}/paths-info/(?P<revision>[^/]+)"
|
|
17
|
+
FILE = rf"/(?:datasets/)?{REPO}/resolve/(?P<revision>[^/]+)/(?P<path>.+)"
|
|
18
|
+
PREUPLOAD = rf"{API}/preupload/(?P<revision>[^/]+)"
|
|
19
|
+
BATCH = rf"/(?:datasets/)?{REPO}\.git/info/lfs/objects/batch"
|
|
20
|
+
COMMIT = rf"{API}/commit/(?P<revision>[^/]+)"
|
|
21
|
+
issued = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Refused(Exception):
|
|
25
|
+
def __init__(self, status, code, message):
|
|
26
|
+
# The message is in the body only, because a header cannot carry every letter.
|
|
27
|
+
self.response = httpx2.Response(status, headers={"X-Error-Code": code}, json={"error": message})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def answer(request):
|
|
31
|
+
method, path = request.method, request.url.path
|
|
32
|
+
if method == "PUT" and path.startswith("/staged/"):
|
|
33
|
+
upload.stage(path.removeprefix("/staged/"), request.stream)
|
|
34
|
+
return httpx2.Response(200)
|
|
35
|
+
# The call does not say which repo the card belongs to, so no card goes to the Hub.
|
|
36
|
+
if path == "/api/validate-yaml":
|
|
37
|
+
return httpx2.Response(200, json={"errors": [], "warnings": []})
|
|
38
|
+
repo = named(request)
|
|
39
|
+
if repo is None or not repository.owns(repo):
|
|
40
|
+
return to_the_hub(request)
|
|
41
|
+
try:
|
|
42
|
+
if method == "GET" and (found := re.fullmatch(INFO, path)):
|
|
43
|
+
record = record_at(repo, found["revision"] or "main")
|
|
44
|
+
return httpx2.Response(200, json=info(repo, record))
|
|
45
|
+
if method == "GET" and (found := re.fullmatch(TREE, path)):
|
|
46
|
+
record = record_at(repo, found["revision"])
|
|
47
|
+
recursive = request.url.params.get("recursive") == "true"
|
|
48
|
+
return httpx2.Response(200, json=tree(repo, record, found["folder"], recursive))
|
|
49
|
+
if method == "POST" and (found := re.fullmatch(PATHS, path)):
|
|
50
|
+
record = record_at(repo, found["revision"])
|
|
51
|
+
paths = parse_qs(request.read().decode()).get("paths", [])
|
|
52
|
+
return httpx2.Response(200, json=paths_info(record, paths))
|
|
53
|
+
if found := re.fullmatch(FILE, path):
|
|
54
|
+
record = record_at(repo, found["revision"])
|
|
55
|
+
if method == "HEAD" or found["path"] not in record["files"]:
|
|
56
|
+
return head(record, found["path"])
|
|
57
|
+
if method == "GET":
|
|
58
|
+
return repository.content(record["files"][found["path"]], request.headers.get("Range"))
|
|
59
|
+
if path == "/api/repos/create":
|
|
60
|
+
asked = json.loads(request.read())
|
|
61
|
+
if asked.get("visibility", "public") != "public":
|
|
62
|
+
raise Refused(400, "", f"{repo} cannot be private: only its owner sees a draft, and everyone a record")
|
|
63
|
+
kind = asked.get("type", "model")
|
|
64
|
+
id = repository.draft(repo, kind)
|
|
65
|
+
# The libraries go on with the id in this address, whatever name they came with.
|
|
66
|
+
return httpx2.Response(200, json={"url": address(kind, f"{repo.split('/')[0]}/{id}")})
|
|
67
|
+
if path == "/api/repos/delete":
|
|
68
|
+
draft_at(repo, "main")
|
|
69
|
+
repository.discard(repo)
|
|
70
|
+
return httpx2.Response(200)
|
|
71
|
+
if "create_pr" in request.url.params:
|
|
72
|
+
raise Refused(400, "", "a repository has no pull requests")
|
|
73
|
+
if method == "POST" and (found := re.fullmatch(PREUPLOAD, path)):
|
|
74
|
+
draft_at(repo, found["revision"])
|
|
75
|
+
files = json.loads(request.read())["files"]
|
|
76
|
+
modes = [{"path": file["path"], "uploadMode": "lfs", "shouldIgnore": False} for file in files]
|
|
77
|
+
return httpx2.Response(200, json={"files": modes})
|
|
78
|
+
if method == "POST" and re.fullmatch(BATCH, path):
|
|
79
|
+
return httpx2.Response(200, json=upload.places(json.loads(request.read())["objects"]))
|
|
80
|
+
if method == "POST" and (found := re.fullmatch(COMMIT, path)):
|
|
81
|
+
return committed(request, repo, found["revision"])
|
|
82
|
+
except Refused as refused:
|
|
83
|
+
return refused.response
|
|
84
|
+
except httpx2.HTTPStatusError as error:
|
|
85
|
+
status = error.response.status_code
|
|
86
|
+
code = {403: "GatedRepo", 404: "RepoNotFound"}.get(status, "")
|
|
87
|
+
# A site says in a message of its own why it refused.
|
|
88
|
+
said = error.response.json()["message"] if "json" in error.response.headers.get("Content-Type", "") else ""
|
|
89
|
+
return Refused(status, code, f"{error.request.url} answered {status}. {said}").response
|
|
90
|
+
return Refused(405, "", f"hf-rdm has no answer to {method} {path}").response
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def to_the_hub(request):
|
|
94
|
+
session = get_session()
|
|
95
|
+
host = request.url.host.replace("hf-rdm.invalid", "huggingface.co")
|
|
96
|
+
# The Host header would still name the made-up address.
|
|
97
|
+
headers = [(name, value) for name, value in request.headers.raw if name.lower() != b"host"]
|
|
98
|
+
forwarded = session.build_request(
|
|
99
|
+
request.method,
|
|
100
|
+
request.url.copy_with(host=host),
|
|
101
|
+
headers=headers,
|
|
102
|
+
content=request.read(),
|
|
103
|
+
extensions=request.extensions,
|
|
104
|
+
)
|
|
105
|
+
return session.send(forwarded, stream=True, follow_redirects=False)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def named(request):
|
|
109
|
+
# datasets asks the dataset viewer about a repo in the query.
|
|
110
|
+
if "dataset" in request.url.params:
|
|
111
|
+
return request.url.params["dataset"]
|
|
112
|
+
# create_repo, delete_repo and move_repo name the repo in the body.
|
|
113
|
+
if request.url.path in ("/api/repos/create", "/api/repos/delete"):
|
|
114
|
+
body = json.loads(request.read())
|
|
115
|
+
return f"{body['organization']}/{body['name']}"
|
|
116
|
+
if request.url.path == "/api/repos/move":
|
|
117
|
+
return json.loads(request.read())["fromRepo"]
|
|
118
|
+
found = re.match(rf"/(?:api/)?(?:(?:models|datasets|spaces|kernels)/)?({REPO})", request.url.path)
|
|
119
|
+
if found:
|
|
120
|
+
return found[1].removesuffix(".git")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def record_at(repo, revision):
|
|
124
|
+
# A hash we gave out keeps meaning the same files, also after the record got a new version.
|
|
125
|
+
if (repo, revision) in issued:
|
|
126
|
+
return issued[repo, revision]
|
|
127
|
+
record = repository.load(repo)
|
|
128
|
+
if record["restricted"]:
|
|
129
|
+
raise Refused(403, "GatedRepo", f"the files of {repo} are restricted")
|
|
130
|
+
listing = sorted((path, file["md5"]) for path, file in record["files"].items())
|
|
131
|
+
# A draft and the record it becomes have the same hash while their files are the same.
|
|
132
|
+
place = record["url"].removesuffix("/draft")
|
|
133
|
+
record["sha"] = hashlib.sha1(json.dumps([place, listing]).encode()).hexdigest()
|
|
134
|
+
# A draft can still change, so its hash is good only while it fits.
|
|
135
|
+
if not record["draft"]:
|
|
136
|
+
issued[repo, record["sha"]] = record
|
|
137
|
+
if revision not in ("main", record["sha"]):
|
|
138
|
+
raise Refused(404, "RevisionNotFound", f"{repo} has no revision {revision}, each version has its own id")
|
|
139
|
+
return record
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def draft_at(repo, revision):
|
|
143
|
+
record = record_at(repo, revision)
|
|
144
|
+
if not record["draft"]:
|
|
145
|
+
raise Refused(403, "", f"{repo} is published and cannot be changed")
|
|
146
|
+
return record
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def address(kind, name):
|
|
150
|
+
folder = "datasets/" if kind == "dataset" else ""
|
|
151
|
+
return f"https://hf-rdm.invalid/{folder}{name}"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def committed(request, repo, revision):
|
|
155
|
+
record = draft_at(repo, revision)
|
|
156
|
+
try:
|
|
157
|
+
upload.commit(record, [json.loads(line) for line in request.read().splitlines()])
|
|
158
|
+
finally:
|
|
159
|
+
# The next question about the draft gets its new file list, under each of its names.
|
|
160
|
+
repository.loaded.clear()
|
|
161
|
+
record = record_at(repo, "main")
|
|
162
|
+
kind = "dataset" if request.url.path.startswith("/api/datasets/") else "model"
|
|
163
|
+
return httpx2.Response(
|
|
164
|
+
200,
|
|
165
|
+
headers={"X-HF-Warning": f"{record['name']}; {record['name']} is a draft and not published yet"},
|
|
166
|
+
json={"commitUrl": f"{address(kind, record['name'])}/commit/{record['sha']}", "commitOid": record["sha"]},
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def info(repo, record):
|
|
171
|
+
siblings = []
|
|
172
|
+
for path, file in record["files"].items():
|
|
173
|
+
siblings.append({"rfilename": path, "size": file["size"]})
|
|
174
|
+
return {"id": repo, "sha": record["sha"], "siblings": siblings}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def tree(repo, record, folder, recursive):
|
|
178
|
+
inside = folder + "/" if folder else ""
|
|
179
|
+
entries = []
|
|
180
|
+
for path, file in record["files"].items():
|
|
181
|
+
if path.startswith(inside):
|
|
182
|
+
entries.append(entry(path, file))
|
|
183
|
+
if folder and not entries:
|
|
184
|
+
raise Refused(404, "EntryNotFound", f"{repo} has no folder {folder}")
|
|
185
|
+
for path in folders(record["files"]):
|
|
186
|
+
if path.startswith(inside):
|
|
187
|
+
entries.append({"type": "directory", "path": path, "oid": record["sha"]})
|
|
188
|
+
if not recursive:
|
|
189
|
+
entries = [e for e in entries if "/" not in e["path"].removeprefix(inside)]
|
|
190
|
+
return sorted(entries, key=lambda e: e["path"])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def paths_info(record, paths):
|
|
194
|
+
files = record["files"]
|
|
195
|
+
found = [entry(path, files[path]) for path in paths if path in files]
|
|
196
|
+
for path in folders(files):
|
|
197
|
+
if path in paths:
|
|
198
|
+
found.append({"type": "directory", "path": path, "oid": record["sha"]})
|
|
199
|
+
return found
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def head(record, path):
|
|
203
|
+
commit = {"X-Repo-Commit": record["sha"]}
|
|
204
|
+
if path not in record["files"]:
|
|
205
|
+
return httpx2.Response(404, headers=commit | {"X-Error-Code": "EntryNotFound"})
|
|
206
|
+
file = record["files"][path]
|
|
207
|
+
return httpx2.Response(200, headers=commit | {"ETag": f'"{file["md5"]}"', "Content-Length": str(file["size"])})
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def entry(path, file):
|
|
211
|
+
return {"type": "file", "path": path, "size": file["size"], "oid": file["md5"]}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def folders(files):
|
|
215
|
+
found = set()
|
|
216
|
+
for path in files:
|
|
217
|
+
parts = path.split("/")
|
|
218
|
+
for n in range(1, len(parts)):
|
|
219
|
+
found.add("/".join(parts[:n]))
|
|
220
|
+
return found
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import time
|
|
3
|
+
from datetime import date
|
|
4
|
+
from urllib.parse import quote
|
|
5
|
+
|
|
6
|
+
import httpx2
|
|
7
|
+
from huggingface_hub import get_session
|
|
8
|
+
|
|
9
|
+
SITES = {
|
|
10
|
+
"aperta": "https://aperta.ulakbim.gov.tr",
|
|
11
|
+
"10.48623": "https://aperta.ulakbim.gov.tr",
|
|
12
|
+
"zenodo": "https://zenodo.org",
|
|
13
|
+
"10.5281": "https://zenodo.org",
|
|
14
|
+
}
|
|
15
|
+
for added in os.environ.get("HF_RDM_SITES", "").split():
|
|
16
|
+
first, site = added.split("=")
|
|
17
|
+
SITES[first] = site.rstrip("/")
|
|
18
|
+
TOKENS = {}
|
|
19
|
+
for added in os.environ.get("HF_RDM_TOKENS", "").split():
|
|
20
|
+
site, token = added.split("=", 1)
|
|
21
|
+
TOKENS[site.rstrip("/")] = token
|
|
22
|
+
loaded = {}
|
|
23
|
+
drafts = {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def owns(repo):
|
|
27
|
+
return repo.split("/")[0] in SITES
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def authorization(url):
|
|
31
|
+
# A token goes only to the address it was given for.
|
|
32
|
+
for site, token in TOKENS.items():
|
|
33
|
+
if url.startswith(site + "/"):
|
|
34
|
+
return {"Authorization": f"Bearer {token}"}
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def ask(method, url, timeout=10, **more):
|
|
39
|
+
headers = {"Accept": "application/vnd.inveniordm.v1+json"} | authorization(url)
|
|
40
|
+
if "content" in more:
|
|
41
|
+
headers["Content-Type"] = "application/octet-stream"
|
|
42
|
+
answer = get_session().request(method, url, headers=headers, timeout=timeout, **more)
|
|
43
|
+
if answer.status_code == 429:
|
|
44
|
+
# A site allows so many calls a minute, and says in how many seconds the next one is free.
|
|
45
|
+
time.sleep(int(answer.headers["Retry-After"]) + 1)
|
|
46
|
+
if "content" in more:
|
|
47
|
+
more["content"].seek(0)
|
|
48
|
+
answer = get_session().request(method, url, headers=headers, timeout=timeout, **more)
|
|
49
|
+
answer.raise_for_status()
|
|
50
|
+
return answer
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def load(repo):
|
|
54
|
+
# A site allows so many calls a minute, so an answer is kept for ten seconds.
|
|
55
|
+
if repo in loaded and time.monotonic() - loaded[repo][0] < 10:
|
|
56
|
+
return loaded[repo][1]
|
|
57
|
+
first, id = repo.split("/")
|
|
58
|
+
site = SITES[first]
|
|
59
|
+
if first.startswith("10."):
|
|
60
|
+
# <site>/doi/<doi> leads to the page of the record, <site>/records/<id>.
|
|
61
|
+
page = get_session().head(f"{site}/doi/{repo}", timeout=10)
|
|
62
|
+
page.raise_for_status()
|
|
63
|
+
id = page.url.path.split("/")[-1]
|
|
64
|
+
try:
|
|
65
|
+
found = ask("GET", f"{site}/api/records/{drafts.get(repo, id)}").json()
|
|
66
|
+
except httpx2.HTTPStatusError as error:
|
|
67
|
+
if error.response.status_code != 404 or site not in TOKENS:
|
|
68
|
+
raise
|
|
69
|
+
# What is not published answers only as a draft, and only to its owner.
|
|
70
|
+
found = ask("GET", f"{site}/api/records/{mine(site, repo, id)}/draft").json()
|
|
71
|
+
# The search learns of a new draft only after a second or two, so this one is remembered.
|
|
72
|
+
drafts[repo] = found["id"]
|
|
73
|
+
# The address is put together here and not taken from the answer, so that a token stays on its own site.
|
|
74
|
+
url = f"{site}/api/records/{found['id']}" + ("" if found["is_published"] else "/draft")
|
|
75
|
+
files = {}
|
|
76
|
+
# A record with restricted files lists none, and a file whose upload did not finish has no checksum.
|
|
77
|
+
for key, file in found["files"].get("entries", {}).items():
|
|
78
|
+
if "checksum" in file:
|
|
79
|
+
files[key] = {
|
|
80
|
+
"size": file["size"],
|
|
81
|
+
"md5": file["checksum"].removeprefix("md5:"),
|
|
82
|
+
"content": f"{url}/files/{quote(key)}/content",
|
|
83
|
+
}
|
|
84
|
+
record = {
|
|
85
|
+
"name": f"{first}/{found['id']}",
|
|
86
|
+
"url": url,
|
|
87
|
+
"draft": not found["is_published"],
|
|
88
|
+
"restricted": found["access"]["files"] == "restricted",
|
|
89
|
+
"files": files,
|
|
90
|
+
}
|
|
91
|
+
loaded[repo] = time.monotonic(), record
|
|
92
|
+
return record
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def mine(site, repo, name):
|
|
96
|
+
# A name that is not the id of a draft is the title of one of the owner's drafts.
|
|
97
|
+
if repo in drafts:
|
|
98
|
+
return drafts[repo]
|
|
99
|
+
found = ask("GET", f"{site}/api/user/records", params={"q": f'metadata.title:"{name}"'}).json()
|
|
100
|
+
for hit in found["hits"]["hits"]:
|
|
101
|
+
if hit["metadata"]["title"] == name and not hit["is_published"]:
|
|
102
|
+
return hit["id"]
|
|
103
|
+
return name
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def content(file, range):
|
|
107
|
+
session = get_session()
|
|
108
|
+
headers = authorization(file["content"]) | ({"Range": range} if range else {})
|
|
109
|
+
request = session.build_request("GET", file["content"], headers=headers, timeout=10)
|
|
110
|
+
return session.send(request, stream=True, follow_redirects=False)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def draft(repo, kind):
|
|
114
|
+
first, name = repo.split("/")
|
|
115
|
+
site = SITES[first]
|
|
116
|
+
if site not in TOKENS:
|
|
117
|
+
raise PermissionError(f"HF_RDM_TOKENS has no token for {site}")
|
|
118
|
+
try:
|
|
119
|
+
load(repo)
|
|
120
|
+
except httpx2.HTTPStatusError as error:
|
|
121
|
+
if error.response.status_code != 404:
|
|
122
|
+
raise
|
|
123
|
+
# A name that stands for nothing yet is the title of a new draft.
|
|
124
|
+
metadata = {"title": name, "resource_type": {"id": kind}, "publication_date": date.today().isoformat()}
|
|
125
|
+
drafts[repo] = ask("POST", f"{site}/api/records", json={"metadata": metadata}).json()["id"]
|
|
126
|
+
return drafts.get(repo, name)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def start(record, paths):
|
|
130
|
+
files = f"{record['url']}/files"
|
|
131
|
+
# A name cannot be written twice, so what a replaced file or a failed upload left there goes first.
|
|
132
|
+
for entry in ask("GET", files).json()["entries"]:
|
|
133
|
+
if entry["key"] in paths:
|
|
134
|
+
ask("DELETE", f"{files}/{quote(entry['key'])}")
|
|
135
|
+
ask("POST", files, json=[{"key": path} for path in paths])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def send(record, path, content):
|
|
139
|
+
file = f"{record['url']}/files/{quote(path)}"
|
|
140
|
+
ask("PUT", f"{file}/content", timeout=None, content=content)
|
|
141
|
+
ask("POST", f"{file}/commit")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def remove(record, path):
|
|
145
|
+
ask("DELETE", f"{record['url']}/files/{quote(path)}")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def discard(repo):
|
|
149
|
+
ask("DELETE", load(repo)["url"])
|
|
150
|
+
# The draft is forgotten under each of its names.
|
|
151
|
+
gone = drafts[repo]
|
|
152
|
+
for name in [name for name, id in drafts.items() if id == gone]:
|
|
153
|
+
del drafts[name]
|
|
154
|
+
loaded.clear()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def choices(first, name, text=""):
|
|
158
|
+
# A list has the name of its field, with or without the section in front.
|
|
159
|
+
url = f"{SITES[first]}/api/vocabularies/{name.rpartition('.')[2]}"
|
|
160
|
+
found = ask("GET", url, params={"q": text, "size": 25}).json()
|
|
161
|
+
return {hit["id"]: hit["title_l10n"] for hit in found["hits"]["hits"]}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def publish(repo, creators, license=None, fields=None, **more):
|
|
165
|
+
record = load(repo)
|
|
166
|
+
if not record["draft"]:
|
|
167
|
+
raise ValueError(f"{repo} is published already")
|
|
168
|
+
found = ask("GET", record["url"]).json()
|
|
169
|
+
people = []
|
|
170
|
+
for name in creators:
|
|
171
|
+
# "Family, Given" is a person, any other name an organisation.
|
|
172
|
+
if ", " in name:
|
|
173
|
+
family, given = name.split(", ", 1)
|
|
174
|
+
who = {"type": "personal", "family_name": family, "given_name": given}
|
|
175
|
+
else:
|
|
176
|
+
who = {"type": "organizational", "name": name}
|
|
177
|
+
people.append({"person_or_org": who})
|
|
178
|
+
found["metadata"]["creators"] = people
|
|
179
|
+
if license:
|
|
180
|
+
found["metadata"]["rights"] = [{"id": license}]
|
|
181
|
+
# Every other field has the name the site gives it: "section.name", or plainly the name of a metadata field.
|
|
182
|
+
for name, value in ((fields or {}) | more).items():
|
|
183
|
+
section, _, key = name.rpartition(".")
|
|
184
|
+
found[section or "metadata"][key] = value
|
|
185
|
+
try:
|
|
186
|
+
saved = ask("PUT", record["url"], json=found).json()
|
|
187
|
+
except httpx2.HTTPStatusError as error:
|
|
188
|
+
if error.response.status_code != 400:
|
|
189
|
+
raise
|
|
190
|
+
# A value the site does not know is refused at once, with a message that says which.
|
|
191
|
+
raise ValueError(f"{repo} was not saved. {error.response.json()['message']}") from None
|
|
192
|
+
if saved.get("errors"):
|
|
193
|
+
missing = [f"{error['field']}: {' '.join(error['messages'])}" for error in saved["errors"]]
|
|
194
|
+
raise ValueError(f"{repo} cannot be published yet. {'; '.join(missing)}")
|
|
195
|
+
published = ask("POST", f"{record['url']}/actions/publish", timeout=60).json()
|
|
196
|
+
loaded.clear()
|
|
197
|
+
# A site that gives no DOI still gives the record its id.
|
|
198
|
+
doi = published["pids"].get("doi")
|
|
199
|
+
return doi["identifier"] if doi else published["id"]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def on():
|
|
7
|
+
# Python 3.12 reads a .pth file twice in a virtual environment.
|
|
8
|
+
if os.environ.get("HF_RDM") != "1" or waiting in sys.meta_path:
|
|
9
|
+
return
|
|
10
|
+
# An address that exists only inside this process. A process without this package
|
|
11
|
+
# that inherits it cannot resolve it, so a Hub token never goes anywhere.
|
|
12
|
+
os.environ["HF_ENDPOINT"] = "https://hf-rdm.invalid"
|
|
13
|
+
# Xet's own client would ask that address for its next token, in the middle of a long download.
|
|
14
|
+
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
|
15
|
+
sys.meta_path.insert(0, waiting)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class WhenTheHubLoads:
|
|
19
|
+
# Mounting waits for the import of huggingface_hub, so a script can still set HF_HOME before it.
|
|
20
|
+
def find_spec(self, name, path, target=None):
|
|
21
|
+
if name != "huggingface_hub":
|
|
22
|
+
return None
|
|
23
|
+
sys.meta_path.remove(self)
|
|
24
|
+
spec = importlib.util.find_spec(name)
|
|
25
|
+
load = spec.loader.exec_module
|
|
26
|
+
|
|
27
|
+
def exec_module(module):
|
|
28
|
+
load(module)
|
|
29
|
+
mount()
|
|
30
|
+
|
|
31
|
+
spec.loader.exec_module = exec_module
|
|
32
|
+
return spec
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
waiting = WhenTheHubLoads()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def mount():
|
|
39
|
+
import httpx2
|
|
40
|
+
import huggingface_hub
|
|
41
|
+
|
|
42
|
+
from . import hub
|
|
43
|
+
|
|
44
|
+
class Adapter(httpx2.BaseTransport):
|
|
45
|
+
def handle_request(self, request):
|
|
46
|
+
return hub.answer(request)
|
|
47
|
+
|
|
48
|
+
hooks = huggingface_hub.get_session().event_hooks
|
|
49
|
+
huggingface_hub.set_client_factory(
|
|
50
|
+
lambda: httpx2.Client(
|
|
51
|
+
mounts={"all://*hf-rdm.invalid": Adapter()}, event_hooks=hooks, follow_redirects=True, timeout=None
|
|
52
|
+
)
|
|
53
|
+
)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
|
|
6
|
+
from huggingface_hub import constants
|
|
7
|
+
|
|
8
|
+
from . import invenio as repository
|
|
9
|
+
|
|
10
|
+
# The client sends the bytes of a file under their hash and names the path only in the commit.
|
|
11
|
+
# A repository cannot rename a file, so the bytes wait here until then.
|
|
12
|
+
STAGED = os.path.join(constants.HF_HOME, "hf-rdm")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def places(objects):
|
|
16
|
+
found = []
|
|
17
|
+
for wanted in objects:
|
|
18
|
+
place = {"oid": wanted["oid"], "size": wanted["size"]}
|
|
19
|
+
# Without an address the client takes the bytes as sent already, which they are after a commit that failed.
|
|
20
|
+
if not os.path.exists(os.path.join(STAGED, wanted["oid"])):
|
|
21
|
+
place["actions"] = {"upload": {"href": f"https://hf-rdm.invalid/staged/{wanted['oid']}"}}
|
|
22
|
+
found.append(place)
|
|
23
|
+
return {"transfer": "basic", "objects": found}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def stage(oid, stream):
|
|
27
|
+
os.makedirs(STAGED, exist_ok=True)
|
|
28
|
+
# Copies of one file come from several threads at once, so each of them writes a file of its own first.
|
|
29
|
+
with tempfile.NamedTemporaryFile(dir=STAGED, delete=False) as part:
|
|
30
|
+
for chunk in stream:
|
|
31
|
+
part.write(chunk)
|
|
32
|
+
os.replace(part.name, os.path.join(STAGED, oid))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def commit(record, lines):
|
|
36
|
+
files = {}
|
|
37
|
+
for line in lines:
|
|
38
|
+
kind, value = line["key"], line["value"]
|
|
39
|
+
if kind == "lfsFile":
|
|
40
|
+
files[value["path"]] = value["oid"]
|
|
41
|
+
# An empty file comes inside the commit, so it joins the waiting ones here.
|
|
42
|
+
if kind == "file":
|
|
43
|
+
content = base64.b64decode(value["content"])
|
|
44
|
+
files[value["path"]] = hashlib.sha256(content).hexdigest()
|
|
45
|
+
stage(files[value["path"]], [content])
|
|
46
|
+
if kind == "deletedFile":
|
|
47
|
+
repository.remove(record, value["path"])
|
|
48
|
+
if kind == "deletedFolder":
|
|
49
|
+
for path in record["files"]:
|
|
50
|
+
if path.startswith(value["path"].rstrip("/") + "/"):
|
|
51
|
+
repository.remove(record, path)
|
|
52
|
+
if files:
|
|
53
|
+
repository.start(record, list(files))
|
|
54
|
+
for path, oid in files.items():
|
|
55
|
+
with open(os.path.join(STAGED, oid), "rb") as content:
|
|
56
|
+
repository.send(record, path, content)
|
|
57
|
+
for oid in set(files.values()):
|
|
58
|
+
os.remove(os.path.join(STAGED, oid))
|
hf_rdm-0.1.0/hf_rdm.pth
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import hf_rdm.switch; hf_rdm.switch.on()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hf_rdm.switch:on
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hf-rdm"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Read records of InvenioRDM repositories such as Aperta and Zenodo, and upload and publish there, with the unchanged Hugging Face libraries"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["huggingface_hub>=2.5,<3", "httpx2>=2,<3"]
|
|
13
|
+
keywords = ["huggingface", "zenodo", "inveniordm", "research data", "open science"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/UlkuTuncerKucuktas/hf-rdm"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["hf_rdm"]
|
|
20
|
+
|
|
21
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
22
|
+
"hf_rdm.pth" = "hf_rdm.pth"
|
|
23
|
+
"hf_rdm.start" = "hf_rdm.start"
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from datasets import load_dataset
|
|
8
|
+
from huggingface_hub import HfApi, HfFileSystem, hf_hub_download
|
|
9
|
+
from huggingface_hub.errors import EntryNotFoundError, GatedRepoError, RepositoryNotFoundError
|
|
10
|
+
from transformers import AutoTokenizer
|
|
11
|
+
|
|
12
|
+
import hf_rdm
|
|
13
|
+
from hf_rdm.invenio import SITES
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_a_file_from_aperta():
|
|
17
|
+
path = hf_hub_download("aperta/304005", "Supplementary Material.pdf", repo_type="dataset")
|
|
18
|
+
assert hashlib.md5(open(path, "rb").read()).hexdigest() == "c27354ed4b0342e28ab51bfb1abf449e"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_a_doi_names_the_record():
|
|
22
|
+
assert HfApi().dataset_info("10.48623/aperta.304004").sha == HfApi().dataset_info("aperta/304004").sha
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_what_is_missing_or_restricted():
|
|
26
|
+
with pytest.raises(EntryNotFoundError):
|
|
27
|
+
hf_hub_download("aperta/304005", "nothing.bin", repo_type="dataset")
|
|
28
|
+
with pytest.raises(RepositoryNotFoundError):
|
|
29
|
+
HfApi().dataset_info("aperta/999999999")
|
|
30
|
+
with pytest.raises(GatedRepoError):
|
|
31
|
+
HfApi().dataset_info("aperta/263720")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_a_folder_and_a_ranged_read_from_zenodo():
|
|
35
|
+
fs = HfFileSystem()
|
|
36
|
+
assert fs.ls("zenodo/8211850", detail=False) == ["zenodo/8211850/epifanio"]
|
|
37
|
+
with fs.open("zenodo/8211850/epifanio/numba_spatial-v0.1.zip", block_size=256) as file:
|
|
38
|
+
assert file.read(4) == b"PK\x03\x04"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_a_tokenizer_from_zenodo():
|
|
42
|
+
tokenizer = AutoTokenizer.from_pretrained("zenodo/20337937")
|
|
43
|
+
assert tokenizer("Merhaba Aperta")["input_ids"] == [45, 69, 82, 72, 65, 66, 65, 221, 33, 80, 69, 82, 84, 65]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_a_csv_from_aperta():
|
|
47
|
+
csv = "STI_Knowledge_Attitudes_Medical_Students_Data.csv"
|
|
48
|
+
assert load_dataset("aperta/303981", data_files=csv, split="train").num_rows == 167
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_a_site_added_while_running():
|
|
52
|
+
SITES["tuwien"] = "https://researchdata.tuwien.ac.at"
|
|
53
|
+
SITES["10.48436"] = "https://researchdata.tuwien.ac.at"
|
|
54
|
+
assert load_dataset("tuwien/f8tjt-k8y11", data_files="armstate_labeled.csv", split="train").num_rows == 100
|
|
55
|
+
assert HfApi().dataset_info("10.48436/f8tjt-k8y11").sha == HfApi().dataset_info("tuwien/f8tjt-k8y11").sha
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_a_hub_model_while_the_switch_is_on():
|
|
59
|
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
|
|
60
|
+
assert tokenizer("Merhaba Aperta")["input_ids"]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_the_values_a_field_allows():
|
|
64
|
+
assert "sub_991" in hf_rdm.choices("aperta", "custom_fields.aperta:science_branches", "Doğal Dil")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_the_switch_from_inside_python():
|
|
68
|
+
code = "import hf_rdm; hf_rdm.on(); import huggingface_hub as hub; print(hub.HfApi().dataset_info('aperta/304005').sha)"
|
|
69
|
+
outside = {key: value for key, value in os.environ.items() if key not in ("HF_RDM", "HF_ENDPOINT")}
|
|
70
|
+
done = subprocess.run([sys.executable, "-c", code], env=outside, capture_output=True, text=True)
|
|
71
|
+
assert len(done.stdout.strip()) == 40
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from datasets import Dataset, load_dataset
|
|
6
|
+
from huggingface_hub import HfApi, hf_hub_download
|
|
7
|
+
from huggingface_hub.errors import BadRequestError
|
|
8
|
+
from transformers import AutoTokenizer
|
|
9
|
+
|
|
10
|
+
from hf_rdm.invenio import SITES, TOKENS, drafts, loaded
|
|
11
|
+
|
|
12
|
+
SITES["sandbox"] = "https://sandbox.zenodo.org"
|
|
13
|
+
pytestmark = pytest.mark.skipif("https://sandbox.zenodo.org" not in TOKENS, reason="no token for Zenodo Sandbox")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture
|
|
17
|
+
def name():
|
|
18
|
+
name = f"sandbox/hf-rdm-test-{time.time_ns()}"
|
|
19
|
+
yield name
|
|
20
|
+
HfApi().delete_repo(name)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_a_folder_into_a_new_draft(name, tmp_path):
|
|
24
|
+
folder = tmp_path / "folder"
|
|
25
|
+
(folder / "onnx").mkdir(parents=True)
|
|
26
|
+
(folder / "config.json").write_text("{}")
|
|
27
|
+
(folder / "onnx" / "model.bin").write_bytes(os.urandom(1_000_000))
|
|
28
|
+
(folder / "empty.txt").touch()
|
|
29
|
+
api = HfApi()
|
|
30
|
+
repo = api.create_repo(name).repo_id
|
|
31
|
+
api.upload_folder(repo_id=repo, folder_path=folder)
|
|
32
|
+
assert sorted(api.list_repo_files(repo)) == ["config.json", "empty.txt", "onnx/model.bin"]
|
|
33
|
+
path = hf_hub_download(repo, "onnx/model.bin", cache_dir=tmp_path)
|
|
34
|
+
assert open(path, "rb").read() == (folder / "onnx" / "model.bin").read_bytes()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_a_file_replaced_and_a_file_deleted(name, tmp_path):
|
|
38
|
+
api = HfApi()
|
|
39
|
+
api.create_repo(name)
|
|
40
|
+
api.upload_file(path_or_fileobj=b"first", path_in_repo="a.txt", repo_id=name)
|
|
41
|
+
api.upload_file(path_or_fileobj=b"more", path_in_repo="b.txt", repo_id=name)
|
|
42
|
+
api.upload_file(path_or_fileobj=b"second", path_in_repo="a.txt", repo_id=name)
|
|
43
|
+
api.delete_file("b.txt", repo_id=name)
|
|
44
|
+
assert api.list_repo_files(name) == ["a.txt"]
|
|
45
|
+
assert open(hf_hub_download(name, "a.txt", cache_dir=tmp_path), "rb").read() == b"second"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_copies_of_one_file(name, tmp_path):
|
|
49
|
+
same = os.urandom(200_000)
|
|
50
|
+
for n in range(3):
|
|
51
|
+
(tmp_path / f"checkpoint-{n}").mkdir()
|
|
52
|
+
(tmp_path / f"checkpoint-{n}" / "tokenizer.bin").write_bytes(same)
|
|
53
|
+
api = HfApi()
|
|
54
|
+
api.create_repo(name)
|
|
55
|
+
api.upload_folder(repo_id=name, folder_path=tmp_path)
|
|
56
|
+
assert len(api.list_repo_files(name)) == 3
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_the_title_in_a_new_process(name):
|
|
60
|
+
api = HfApi()
|
|
61
|
+
api.create_repo(name)
|
|
62
|
+
api.upload_file(path_or_fileobj=b"first", path_in_repo="a.txt", repo_id=name)
|
|
63
|
+
# The search of the site learns of a new draft only after a second or two.
|
|
64
|
+
time.sleep(4)
|
|
65
|
+
drafts.clear()
|
|
66
|
+
loaded.clear()
|
|
67
|
+
assert api.list_repo_files(name) == ["a.txt"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_what_a_draft_refuses(name):
|
|
71
|
+
api = HfApi()
|
|
72
|
+
with pytest.raises(BadRequestError):
|
|
73
|
+
api.create_repo(name, private=True)
|
|
74
|
+
api.create_repo(name)
|
|
75
|
+
with pytest.raises(BadRequestError):
|
|
76
|
+
api.upload_file(path_or_fileobj=b"first", path_in_repo="a.txt", repo_id=name, create_pr=True)
|
|
77
|
+
assert api.list_repo_files(name) == []
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_a_tokenizer_with_push_to_hub(name, tmp_path):
|
|
81
|
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
|
|
82
|
+
repo = tokenizer.push_to_hub(name).repo_url.repo_id
|
|
83
|
+
again = AutoTokenizer.from_pretrained(repo, cache_dir=tmp_path)
|
|
84
|
+
assert again("Merhaba Aperta")["input_ids"] == tokenizer("Merhaba Aperta")["input_ids"]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_a_dataset_with_push_to_hub(name, tmp_path):
|
|
88
|
+
repo = Dataset.from_dict({"text": ["a", "b", "c"]}).push_to_hub(name).repo_url.repo_id
|
|
89
|
+
assert load_dataset(repo, split="train", cache_dir=str(tmp_path))["text"] == ["a", "b", "c"]
|