-
Notifications
You must be signed in to change notification settings - Fork 631
/
Copy pathtest_hf_api.py
4365 lines (3666 loc) · 186 KB
/
test_hf_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import os
import re
import subprocess
import tempfile
import time
import types
import unittest
import uuid
from collections.abc import Iterable
from concurrent.futures import Future
from dataclasses import fields
from io import BytesIO
from pathlib import Path
from typing import List, Optional, Set, Union, get_args
from unittest.mock import Mock, patch
from urllib.parse import quote, urlparse
import pytest
import requests
from requests.exceptions import HTTPError
import huggingface_hub.lfs
from huggingface_hub import HfApi, SpaceHardware, SpaceStage, SpaceStorage, constants
from huggingface_hub._commit_api import (
CommitOperationAdd,
CommitOperationCopy,
CommitOperationDelete,
_fetch_upload_modes,
)
from huggingface_hub.community import DiscussionComment, DiscussionWithDetails
from huggingface_hub.errors import (
BadRequestError,
EntryNotFoundError,
GatedRepoError,
HfHubHTTPError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from huggingface_hub.file_download import hf_hub_download
from huggingface_hub.hf_api import (
AccessRequest,
Collection,
CommitInfo,
DatasetInfo,
ExpandDatasetProperty_T,
ExpandModelProperty_T,
ExpandSpaceProperty_T,
ModelInfo,
RepoSibling,
RepoUrl,
SpaceInfo,
SpaceRuntime,
User,
WebhookInfo,
WebhookWatchedItem,
repo_type_and_id_from_hf_id,
)
from huggingface_hub.repocard_data import DatasetCardData, ModelCardData
from huggingface_hub.utils import (
NotASafetensorsRepoError,
SafetensorsFileMetadata,
SafetensorsParsingError,
SafetensorsRepoMetadata,
SoftTemporaryDirectory,
TensorInfo,
get_session,
hf_raise_for_status,
logging,
)
from huggingface_hub.utils.endpoint_helpers import _is_emission_within_threshold
from .testing_constants import (
ENDPOINT_STAGING,
ENTERPRISE_ORG,
ENTERPRISE_TOKEN,
FULL_NAME,
OTHER_TOKEN,
OTHER_USER,
TOKEN,
USER,
)
from .testing_utils import (
DUMMY_DATASET_ID,
DUMMY_DATASET_ID_REVISION_ONE_SPECIFIC_COMMIT,
DUMMY_MODEL_ID,
DUMMY_MODEL_ID_REVISION_ONE_SPECIFIC_COMMIT,
ENDPOINT_PRODUCTION,
SAMPLE_DATASET_IDENTIFIER,
expect_deprecation,
repo_name,
require_git_lfs,
rmtree_with_retry,
use_tmp_repo,
with_production_testing,
)
logger = logging.get_logger(__name__)
WORKING_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures/working_repo")
LARGE_FILE_14MB = "https://cdn-media.huggingface.co/lfs-largefiles/progit.epub"
LARGE_FILE_18MB = "https://cdn-media.huggingface.co/lfs-largefiles/progit.pdf"
INVALID_MODELCARD = """
---
model-index: foo
---
This is a modelcard with an invalid metadata section.
"""
class HfApiCommonTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Share the valid token in all tests below."""
cls._token = TOKEN
cls._api = HfApi(endpoint=ENDPOINT_STAGING, token=TOKEN)
class HfApiRepoFileExistsTest(HfApiCommonTest):
def setUp(self) -> None:
super().setUp()
self.repo_id = self._api.create_repo(repo_name(), private=True).repo_id
self.upload = self._api.upload_file(repo_id=self.repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
def tearDown(self) -> None:
self._api.delete_repo(self.repo_id)
return super().tearDown()
def test_repo_exists(self):
assert self._api.repo_exists(self.repo_id)
self.assertFalse(self._api.repo_exists(self.repo_id, token=False)) # private repo
self.assertFalse(self._api.repo_exists("repo-that-does-not-exist")) # missing repo
def test_revision_exists(self):
assert self._api.revision_exists(self.repo_id, "main")
assert not self._api.revision_exists(self.repo_id, "revision-that-does-not-exist") # missing revision
assert not self._api.revision_exists(self.repo_id, "main", token=False) # private repo
assert not self._api.revision_exists("repo-that-does-not-exist", "main") # missing repo
@patch("huggingface_hub.constants.ENDPOINT", "https://hub-ci.huggingface.co")
@patch(
"huggingface_hub.constants.HUGGINGFACE_CO_URL_TEMPLATE",
"https://hub-ci.huggingface.co/{repo_id}/resolve/{revision}/{filename}",
)
def test_file_exists(self):
assert self._api.file_exists(self.repo_id, "file.txt")
self.assertFalse(self._api.file_exists("repo-that-does-not-exist", "file.txt")) # missing repo
self.assertFalse(self._api.file_exists(self.repo_id, "file-does-not-exist")) # missing file
self.assertFalse(
self._api.file_exists(self.repo_id, "file.txt", revision="revision-that-does-not-exist")
) # missing revision
self.assertFalse(self._api.file_exists(self.repo_id, "file.txt", token=False)) # private repo
class HfApiEndpointsTest(HfApiCommonTest):
def test_whoami_with_passing_token(self):
info = self._api.whoami(token=self._token)
self.assertEqual(info["name"], USER)
self.assertEqual(info["fullname"], FULL_NAME)
self.assertIsInstance(info["orgs"], list)
valid_org = [org for org in info["orgs"] if org["name"] == "valid_org"][0]
self.assertEqual(valid_org["fullname"], "Dummy Org")
@patch("huggingface_hub.utils._headers.get_token", return_value=TOKEN)
def test_whoami_with_implicit_token_from_login(self, mock_get_token: Mock) -> None:
"""Test using `whoami` after a `huggingface-cli login`."""
with patch.object(self._api, "token", None): # no default token
info = self._api.whoami()
self.assertEqual(info["name"], USER)
@patch("huggingface_hub.utils._headers.get_token")
def test_whoami_with_implicit_token_from_hf_api(self, mock_get_token: Mock) -> None:
"""Test using `whoami` with token from the HfApi client."""
info = self._api.whoami()
self.assertEqual(info["name"], USER)
mock_get_token.assert_not_called()
def test_delete_repo_error_message(self):
# test for #751
# See https://github.com/huggingface/huggingface_hub/issues/751
with self.assertRaisesRegex(
requests.exceptions.HTTPError,
re.compile(
r"404 Client Error(.+)\(Request ID: .+\)(.*)Repository Not Found",
flags=re.DOTALL,
),
):
self._api.delete_repo("repo-that-does-not-exist")
def test_delete_repo_missing_ok(self) -> None:
self._api.delete_repo("repo-that-does-not-exist", missing_ok=True)
def test_update_repo_visibility(self):
repo_id = self._api.create_repo(repo_id=repo_name()).repo_id
self._api.update_repo_settings(repo_id=repo_id, private=True)
assert self._api.model_info(repo_id).private
self._api.update_repo_settings(repo_id=repo_id, private=False)
assert not self._api.model_info(repo_id).private
self._api.delete_repo(repo_id=repo_id)
def test_move_repo_normal_usage(self):
repo_id = f"{USER}/{repo_name()}"
new_repo_id = f"{USER}/{repo_name()}"
# Spaces not tested on staging (error 500)
for repo_type in [None, constants.REPO_TYPE_MODEL, constants.REPO_TYPE_DATASET]:
self._api.create_repo(repo_id=repo_id, repo_type=repo_type)
self._api.move_repo(from_id=repo_id, to_id=new_repo_id, repo_type=repo_type)
self._api.delete_repo(repo_id=new_repo_id, repo_type=repo_type)
def test_move_repo_target_already_exists(self) -> None:
repo_id_1 = f"{USER}/{repo_name()}"
repo_id_2 = f"{USER}/{repo_name()}"
self._api.create_repo(repo_id=repo_id_1)
self._api.create_repo(repo_id=repo_id_2)
with pytest.raises(HfHubHTTPError, match=r"A model repository called .* already exists"):
self._api.move_repo(from_id=repo_id_1, to_id=repo_id_2, repo_type=constants.REPO_TYPE_MODEL)
self._api.delete_repo(repo_id=repo_id_1)
self._api.delete_repo(repo_id=repo_id_2)
def test_move_repo_invalid_repo_id(self) -> None:
"""Test from_id and to_id must be in the form `"namespace/repo_name"`."""
with pytest.raises(ValueError, match=r"Invalid repo_id*"):
self._api.move_repo(from_id="namespace/repo_name", to_id="invalid_repo_id")
with pytest.raises(ValueError, match=r"Invalid repo_id*"):
self._api.move_repo(from_id="invalid_repo_id", to_id="namespace/repo_name")
@use_tmp_repo(repo_type="model")
def test_update_repo_settings(self, repo_url: RepoUrl):
repo_id = repo_url.repo_id
for gated_value in ["auto", "manual", False]:
for private_value in [True, False]: # Test both private and public settings
self._api.update_repo_settings(repo_id=repo_id, gated=gated_value, private=private_value)
info = self._api.model_info(repo_id)
assert info.gated == gated_value
assert info.private == private_value # Verify the private setting
@use_tmp_repo(repo_type="dataset")
def test_update_dataset_repo_settings(self, repo_url: RepoUrl):
repo_id = repo_url.repo_id
repo_type = repo_url.repo_type
for gated_value in ["auto", "manual", False]:
for private_value in [True, False]:
self._api.update_repo_settings(
repo_id=repo_id, repo_type=repo_type, gated=gated_value, private=private_value
)
info = self._api.dataset_info(repo_id)
assert info.gated == gated_value
assert info.private == private_value
@expect_deprecation("get_token_permission")
def test_get_token_permission_on_oauth_token(self):
whoami = {
"type": "user",
"auth": {"type": "oauth", "expiresAt": "2024-10-24T19:43:43.000Z"},
# ...
# other values are ignored as we only need to check the "auth" value
}
with patch.object(self._api, "whoami", return_value=whoami):
assert self._api.get_token_permission() is None
class CommitApiTest(HfApiCommonTest):
def setUp(self) -> None:
super().setUp()
self.tmp_dir = tempfile.mkdtemp()
self.tmp_file = os.path.join(self.tmp_dir, "temp")
self.tmp_file_content = "Content of the file"
with open(self.tmp_file, "w+") as f:
f.write(self.tmp_file_content)
os.makedirs(os.path.join(self.tmp_dir, "nested"))
self.nested_tmp_file = os.path.join(self.tmp_dir, "nested", "file.bin")
with open(self.nested_tmp_file, "wb+") as f:
f.truncate(1024 * 1024)
self.addCleanup(rmtree_with_retry, self.tmp_dir)
def test_upload_file_validation(self) -> None:
with self.assertRaises(ValueError, msg="Wrong repo type"):
self._api.upload_file(
path_or_fileobj=self.tmp_file,
path_in_repo="README.md",
repo_id="something",
repo_type="this type does not exist",
)
def test_commit_operation_validation(self):
with open(self.tmp_file, "rt") as ftext:
with self.assertRaises(
ValueError,
msg="If you passed a file-like object, make sure it is in binary mode",
):
CommitOperationAdd(path_or_fileobj=ftext, path_in_repo="README.md") # type: ignore
with self.assertRaises(ValueError, msg="path_or_fileobj is str but does not point to a file"):
CommitOperationAdd(
path_or_fileobj=os.path.join(self.tmp_dir, "nofile.pth"),
path_in_repo="README.md",
)
@use_tmp_repo()
def test_upload_file_str_path(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
return_val = self._api.upload_file(
path_or_fileobj=self.tmp_file,
path_in_repo="temp/new_file.md",
repo_id=repo_id,
)
self.assertEqual(return_val, f"{repo_url}/blob/main/temp/new_file.md")
self.assertIsInstance(return_val, CommitInfo)
with SoftTemporaryDirectory() as cache_dir:
with open(hf_hub_download(repo_id=repo_id, filename="temp/new_file.md", cache_dir=cache_dir)) as f:
self.assertEqual(f.read(), self.tmp_file_content)
@use_tmp_repo()
def test_upload_file_pathlib_path(self, repo_url: RepoUrl) -> None:
"""Regression test for https://github.com/huggingface/huggingface_hub/issues/1246."""
self._api.upload_file(path_or_fileobj=Path(self.tmp_file), path_in_repo="file.txt", repo_id=repo_url.repo_id)
self.assertIn("file.txt", self._api.list_repo_files(repo_id=repo_url.repo_id))
@use_tmp_repo()
def test_upload_file_fileobj(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
with open(self.tmp_file, "rb") as filestream:
return_val = self._api.upload_file(
path_or_fileobj=filestream,
path_in_repo="temp/new_file.md",
repo_id=repo_id,
)
self.assertEqual(return_val, f"{repo_url}/blob/main/temp/new_file.md")
with SoftTemporaryDirectory() as cache_dir:
with open(hf_hub_download(repo_id=repo_id, filename="temp/new_file.md", cache_dir=cache_dir)) as f:
self.assertEqual(f.read(), self.tmp_file_content)
@use_tmp_repo()
def test_upload_file_bytesio(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
content = BytesIO(b"File content, but in bytes IO")
return_val = self._api.upload_file(
path_or_fileobj=content,
path_in_repo="temp/new_file.md",
repo_id=repo_id,
)
self.assertEqual(return_val, f"{repo_url}/blob/main/temp/new_file.md")
with SoftTemporaryDirectory() as cache_dir:
with open(hf_hub_download(repo_id=repo_id, filename="temp/new_file.md", cache_dir=cache_dir)) as f:
self.assertEqual(f.read(), content.getvalue().decode())
@use_tmp_repo()
def test_upload_data_files_to_model_repo(self, repo_url: RepoUrl) -> None:
# If a .parquet file is uploaded to a model repo, it should be uploaded correctly but a warning is raised.
with self.assertWarns(UserWarning) as cm:
self._api.upload_file(
path_or_fileobj=b"content",
path_in_repo="data.parquet",
repo_id=repo_url.repo_id,
)
assert (
cm.warnings[0].message.args[0]
== "It seems that you are about to commit a data file (data.parquet) to a model repository. You are sure this is intended? If you are trying to upload a dataset, please set `repo_type='dataset'` or `--repo-type=dataset` in a CLI."
)
# Same for arrow file
with self.assertWarns(UserWarning) as cm:
self._api.upload_file(
path_or_fileobj=b"content",
path_in_repo="data.arrow",
repo_id=repo_url.repo_id,
)
# Still correctly uploaded
files = self._api.list_repo_files(repo_url.repo_id)
assert "data.parquet" in files
assert "data.arrow" in files
def test_create_repo_return_value(self) -> None:
REPO_NAME = repo_name("org")
url = self._api.create_repo(repo_id=REPO_NAME)
self.assertIsInstance(url, str)
self.assertIsInstance(url, RepoUrl)
self.assertEqual(url.repo_id, f"{USER}/{REPO_NAME}")
self._api.delete_repo(repo_id=url.repo_id)
def test_create_repo_already_exists_but_no_write_permission(self):
# Create under other user namespace
repo_id = self._api.create_repo(repo_id=repo_name(), token=OTHER_TOKEN).repo_id
# Try to create with our namespace -> should not fail as the repo already exists
self._api.create_repo(repo_id=repo_id, token=TOKEN, exist_ok=True)
# Clean up
self._api.delete_repo(repo_id=repo_id, token=OTHER_TOKEN)
def test_create_repo_private_by_default(self):
"""Enterprise Hub allows creating private repos by default. Let's test that."""
repo_id = f"{ENTERPRISE_ORG}/{repo_name()}"
self._api.create_repo(repo_id, token=ENTERPRISE_TOKEN)
info = self._api.model_info(repo_id, token=ENTERPRISE_TOKEN, expand="private")
assert info.private
self._api.delete_repo(repo_id, token=ENTERPRISE_TOKEN)
@use_tmp_repo()
def test_upload_file_create_pr(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
return_val = self._api.upload_file(
path_or_fileobj=self.tmp_file_content.encode(),
path_in_repo="temp/new_file.md",
repo_id=repo_id,
create_pr=True,
)
self.assertEqual(return_val, f"{repo_url}/blob/{quote('refs/pr/1', safe='')}/temp/new_file.md")
self.assertIsInstance(return_val, CommitInfo)
with SoftTemporaryDirectory() as cache_dir:
with open(
hf_hub_download(
repo_id=repo_id, filename="temp/new_file.md", revision="refs/pr/1", cache_dir=cache_dir
)
) as f:
self.assertEqual(f.read(), self.tmp_file_content)
@use_tmp_repo()
def test_delete_file(self, repo_url: RepoUrl) -> None:
self._api.upload_file(
path_or_fileobj=self.tmp_file,
path_in_repo="temp/new_file.md",
repo_id=repo_url.repo_id,
)
return_val = self._api.delete_file(path_in_repo="temp/new_file.md", repo_id=repo_url.repo_id)
self.assertIsInstance(return_val, CommitInfo)
with self.assertRaises(EntryNotFoundError):
# Should raise a 404
hf_hub_download(repo_url.repo_id, "temp/new_file.md")
def test_get_full_repo_name(self):
repo_name_with_no_org = self._api.get_full_repo_name("model")
self.assertEqual(repo_name_with_no_org, f"{USER}/model")
repo_name_with_no_org = self._api.get_full_repo_name("model", organization="org")
self.assertEqual(repo_name_with_no_org, "org/model")
@use_tmp_repo()
def test_upload_folder(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
# Upload folder
url = self._api.upload_folder(folder_path=self.tmp_dir, path_in_repo="temp/dir", repo_id=repo_id)
self.assertEqual(
url,
f"{self._api.endpoint}/{repo_id}/tree/main/temp/dir",
)
self.assertIsInstance(url, CommitInfo)
# Check files are uploaded
for rpath in ["temp", "nested/file.bin"]:
local_path = os.path.join(self.tmp_dir, rpath)
remote_path = f"temp/dir/{rpath}"
filepath = hf_hub_download(
repo_id=repo_id, filename=remote_path, revision="main", use_auth_token=self._token
)
assert filepath is not None
with open(filepath, "rb") as downloaded_file:
content = downloaded_file.read()
with open(local_path, "rb") as local_file:
expected_content = local_file.read()
self.assertEqual(content, expected_content)
# Re-uploading the same folder twice should be fine
return_val = self._api.upload_folder(folder_path=self.tmp_dir, path_in_repo="temp/dir", repo_id=repo_id)
self.assertIsInstance(return_val, CommitInfo)
@use_tmp_repo()
def test_upload_folder_create_pr(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
# Upload folder as a new PR
return_val = self._api.upload_folder(
folder_path=self.tmp_dir, path_in_repo="temp/dir", repo_id=repo_id, create_pr=True
)
self.assertEqual(return_val, f"{self._api.endpoint}/{repo_id}/tree/refs%2Fpr%2F1/temp/dir")
# Check files are uploaded
for rpath in ["temp", "nested/file.bin"]:
local_path = os.path.join(self.tmp_dir, rpath)
filepath = hf_hub_download(repo_id=repo_id, filename=f"temp/dir/{rpath}", revision="refs/pr/1")
assert Path(local_path).read_bytes() == Path(filepath).read_bytes()
def test_upload_folder_default_path_in_repo(self):
REPO_NAME = repo_name("upload_folder_to_root")
self._api.create_repo(repo_id=REPO_NAME, exist_ok=False)
url = self._api.upload_folder(folder_path=self.tmp_dir, repo_id=f"{USER}/{REPO_NAME}")
# URL to root of repository
self.assertEqual(url, f"{self._api.endpoint}/{USER}/{REPO_NAME}/tree/main/")
@use_tmp_repo()
def test_upload_folder_git_folder_excluded(self, repo_url: RepoUrl) -> None:
# Simulate a folder with a .git folder
def _create_file(*parts) -> None:
path = Path(self.tmp_dir, *parts)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("content")
_create_file(".git", "file.txt")
_create_file(".cache", "huggingface", "file.txt")
_create_file(".git", "folder", "file.txt")
_create_file("folder", ".git", "file.txt")
_create_file("folder", ".cache", "huggingface", "file.txt")
_create_file("folder", ".git", "folder", "file.txt")
_create_file(".git_something", "file.txt")
_create_file("file.git")
# Upload folder and check that .git folder is excluded
self._api.upload_folder(folder_path=self.tmp_dir, repo_id=repo_url.repo_id)
self.assertEqual(
set(self._api.list_repo_files(repo_id=repo_url.repo_id)),
{".gitattributes", ".git_something/file.txt", "file.git", "temp", "nested/file.bin"},
)
@use_tmp_repo()
def test_upload_folder_gitignore_already_exists(self, repo_url: RepoUrl) -> None:
# Ignore nested folder
self._api.upload_file(path_or_fileobj=b"nested/*\n", path_in_repo=".gitignore", repo_id=repo_url.repo_id)
# Upload folder
self._api.upload_folder(folder_path=self.tmp_dir, repo_id=repo_url.repo_id)
# Check nested file not uploaded
assert not self._api.file_exists(repo_url.repo_id, "nested/file.bin")
@use_tmp_repo()
def test_upload_folder_gitignore_in_commit(self, repo_url: RepoUrl) -> None:
# Create .gitignore file locally
(Path(self.tmp_dir) / ".gitignore").write_text("nested/*\n")
# Upload folder
self._api.upload_folder(folder_path=self.tmp_dir, repo_id=repo_url.repo_id)
# Check nested file not uploaded
assert not self._api.file_exists(repo_url.repo_id, "nested/file.bin")
@use_tmp_repo()
def test_create_commit_create_pr(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
# Upload a first file
self._api.upload_file(path_or_fileobj=self.tmp_file, path_in_repo="temp/new_file.md", repo_id=repo_id)
# Create a commit with a PR
operations = [
CommitOperationDelete(path_in_repo="temp/new_file.md"),
CommitOperationAdd(path_in_repo="buffer", path_or_fileobj=b"Buffer data"),
]
resp = self._api.create_commit(
operations=operations, commit_message="Test create_commit", repo_id=repo_id, create_pr=True
)
# Check commit info
self.assertIsInstance(resp, CommitInfo)
commit_id = resp.oid
self.assertIn("pr_revision='refs/pr/1'", repr(resp))
self.assertIsInstance(commit_id, str)
self.assertGreater(len(commit_id), 0)
self.assertEqual(resp.commit_url, f"{self._api.endpoint}/{repo_id}/commit/{commit_id}")
self.assertEqual(resp.commit_message, "Test create_commit")
self.assertEqual(resp.commit_description, "")
self.assertEqual(resp.pr_url, f"{self._api.endpoint}/{repo_id}/discussions/1")
self.assertEqual(resp.pr_num, 1)
self.assertEqual(resp.pr_revision, "refs/pr/1")
# File doesn't exist on main...
with self.assertRaises(HTTPError) as ctx:
# Should raise a 404
self._api.hf_hub_download(repo_id, "buffer")
self.assertEqual(ctx.exception.response.status_code, 404)
# ...but exists on PR
filepath = self._api.hf_hub_download(filename="buffer", repo_id=repo_id, revision="refs/pr/1")
with open(filepath, "rb") as downloaded_file:
content = downloaded_file.read()
self.assertEqual(content, b"Buffer data")
def test_create_commit_create_pr_against_branch(self):
repo_id = f"{USER}/{repo_name()}"
# Create repo and create a non-main branch
self._api.create_repo(repo_id=repo_id, exist_ok=False)
self._api.create_branch(repo_id=repo_id, branch="test_branch")
head = self._api.list_repo_refs(repo_id=repo_id).branches[0].target_commit
# Create PR against non-main branch works
resp = self._api.create_commit(
operations=[
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
],
commit_message="PR against existing branch",
repo_id=repo_id,
revision="test_branch",
create_pr=True,
)
self.assertIsInstance(resp, CommitInfo)
# Create PR against a oid fails
with self.assertRaises(RevisionNotFoundError):
self._api.create_commit(
operations=[
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
],
commit_message="PR against a oid",
repo_id=repo_id,
revision=head,
create_pr=True,
)
# Create PR against a non-existing branch fails
with self.assertRaises(RevisionNotFoundError):
self._api.create_commit(
operations=[
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
],
commit_message="PR against missing branch",
repo_id=repo_id,
revision="missing_branch",
create_pr=True,
)
# Cleanup
self._api.delete_repo(repo_id=repo_id)
def test_create_commit_create_pr_on_foreign_repo(self):
# Create a repo with another user. The normal CI user don't have rights on it.
# We must be able to create a PR on it
foreign_api = HfApi(token=OTHER_TOKEN)
foreign_repo_url = foreign_api.create_repo(repo_id=repo_name("repo-for-hfh-ci"))
self._api.create_commit(
operations=[
CommitOperationAdd(path_in_repo="regular.txt", path_or_fileobj=b"File content"),
CommitOperationAdd(path_in_repo="lfs.pkl", path_or_fileobj=b"File content"),
],
commit_message="PR on foreign repo",
repo_id=foreign_repo_url.repo_id,
create_pr=True,
)
foreign_api.delete_repo(repo_id=foreign_repo_url.repo_id)
@use_tmp_repo()
def test_create_commit(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
self._api.upload_file(path_or_fileobj=self.tmp_file, path_in_repo="temp/new_file.md", repo_id=repo_id)
with open(self.tmp_file, "rb") as fileobj:
operations = [
CommitOperationDelete(path_in_repo="temp/new_file.md"),
CommitOperationAdd(path_in_repo="buffer", path_or_fileobj=b"Buffer data"),
CommitOperationAdd(
path_in_repo="bytesio",
path_or_fileobj=BytesIO(b"BytesIO data"),
),
CommitOperationAdd(path_in_repo="fileobj", path_or_fileobj=fileobj),
CommitOperationAdd(
path_in_repo="nested/path",
path_or_fileobj=self.tmp_file,
),
]
resp = self._api.create_commit(operations=operations, commit_message="Test create_commit", repo_id=repo_id)
# Check commit info
self.assertIsInstance(resp, CommitInfo)
self.assertIsNone(resp.pr_url) # No pr created
self.assertIsNone(resp.pr_num)
self.assertIsNone(resp.pr_revision)
with self.assertRaises(HTTPError):
# Should raise a 404
hf_hub_download(repo_id, "temp/new_file.md")
for path, expected_content in [
("buffer", b"Buffer data"),
("bytesio", b"BytesIO data"),
("fileobj", self.tmp_file_content.encode()),
("nested/path", self.tmp_file_content.encode()),
]:
filepath = hf_hub_download(repo_id=repo_id, filename=path, revision="main")
assert filepath is not None
with open(filepath, "rb") as downloaded_file:
content = downloaded_file.read()
self.assertEqual(content, expected_content)
@use_tmp_repo()
def test_create_commit_conflict(self, repo_url: RepoUrl) -> None:
# Get commit on main
repo_id = repo_url.repo_id
parent_commit = self._api.model_info(repo_id).sha
# Upload new file
self._api.upload_file(path_or_fileobj=self.tmp_file, path_in_repo="temp/new_file.md", repo_id=repo_id)
# Creating a commit with a parent commit that is not the current main should fail
operations = [
CommitOperationAdd(path_in_repo="buffer", path_or_fileobj=b"Buffer data"),
]
with self.assertRaises(HTTPError) as exc_ctx:
self._api.create_commit(
operations=operations,
commit_message="Test create_commit",
repo_id=repo_id,
parent_commit=parent_commit,
)
self.assertEqual(exc_ctx.exception.response.status_code, 412)
self.assertIn(
# Check the server message is added to the exception
"A commit has happened since. Please refresh and try again.",
str(exc_ctx.exception),
)
def test_create_commit_repo_does_not_exist(self) -> None:
"""Test error message is detailed when creating a commit on a missing repo."""
with self.assertRaises(RepositoryNotFoundError) as context:
self._api.create_commit(
repo_id=f"{USER}/repo_that_do_not_exist",
operations=[CommitOperationAdd("config.json", b"content")],
commit_message="fake_message",
)
request_id = context.exception.response.headers.get("X-Request-Id")
expected_message = (
f"404 Client Error. (Request ID: {request_id})\n\nRepository Not"
" Found for url:"
f" {self._api.endpoint}/api/models/{USER}/repo_that_do_not_exist/preupload/main.\nPlease"
" make sure you specified the correct `repo_id` and"
" `repo_type`.\nIf you are trying to access a private or gated"
" repo, make sure you are authenticated.\nNote: Creating a commit"
" assumes that the repo already exists on the Huggingface Hub."
" Please use `create_repo` if it's not the case."
)
assert str(context.exception) == expected_message
@patch("huggingface_hub.utils._headers.get_token", return_value=TOKEN)
def test_create_commit_lfs_file_implicit_token(self, get_token_mock: Mock) -> None:
"""Test that uploading a file as LFS works with cached token.
Regression test for https://github.com/huggingface/huggingface_hub/pull/1084.
"""
REPO_NAME = repo_name("create_commit_with_lfs")
repo_id = f"{USER}/{REPO_NAME}"
with patch.object(self._api, "token", None): # no default token
# Create repo
self._api.create_repo(repo_id=REPO_NAME, exist_ok=False)
# Set repo to track png files as LFS
self._api.create_commit(
operations=[
CommitOperationAdd(
path_in_repo=".gitattributes",
path_or_fileobj=b"*.png filter=lfs diff=lfs merge=lfs -text",
),
],
commit_message="Update .gitattributes",
repo_id=repo_id,
)
# Upload a PNG file
self._api.create_commit(
operations=[
CommitOperationAdd(path_in_repo="image.png", path_or_fileobj=b"image data"),
],
commit_message="Test upload lfs file",
repo_id=repo_id,
)
# Check uploaded as LFS
info = self._api.model_info(repo_id=repo_id, files_metadata=True)
siblings = {file.rfilename: file for file in info.siblings}
self.assertIsInstance(siblings["image.png"].lfs, dict) # LFS file
# Delete repo
self._api.delete_repo(repo_id=REPO_NAME)
@use_tmp_repo()
def test_create_commit_huge_regular_files(self, repo_url: RepoUrl) -> None:
"""Test committing 12 text files (>100MB in total) at once.
This was not possible when using `json` format instead of `ndjson`
on the `/create-commit` endpoint.
See https://github.com/huggingface/huggingface_hub/pull/1117.
"""
operations = [
CommitOperationAdd(
path_in_repo=f"file-{num}.text",
path_or_fileobj=b"Hello regular " + b"a" * 1024 * 1024 * 9,
)
for num in range(12)
]
self._api.create_commit(
operations=operations, # 12*9MB regular => too much for "old" method
commit_message="Test create_commit with huge regular files",
repo_id=repo_url.repo_id,
)
@use_tmp_repo()
def test_commit_preflight_on_lots_of_lfs_files(self, repo_url: RepoUrl):
"""Test committing 1300 LFS files at once.
This was not possible when `_fetch_upload_modes` was not fetching metadata by
chunks. We are not testing the full upload as it would require to upload 1300
files which is unnecessary for the test. Having an overall large payload (for
`/create-commit` endpoint) is tested in `test_create_commit_huge_regular_files`.
There is also a 25k LFS files limit on the Hub but this is not tested.
See https://github.com/huggingface/huggingface_hub/pull/1117.
"""
operations = [
CommitOperationAdd(
path_in_repo=f"file-{num}.bin", # considered as LFS
path_or_fileobj=b"Hello LFS" + b"a" * 2048, # big enough sample
)
for num in range(1300)
]
# Test `_fetch_upload_modes` preflight ("are they regular or LFS files?")
_fetch_upload_modes(
additions=operations,
repo_type="model",
repo_id=repo_url.repo_id,
headers=self._api._build_hf_headers(),
revision="main",
endpoint=ENDPOINT_STAGING,
)
for operation in operations:
self.assertEqual(operation._upload_mode, "lfs")
self.assertFalse(operation._is_committed)
self.assertFalse(operation._is_uploaded)
def test_create_commit_repo_id_case_insensitive(self):
"""Test create commit but repo_id is lowercased.
Regression test for #1371. Hub API is already case insensitive. Somehow the issue was with the `requests`
streaming implementation when generating the ndjson payload "on the fly". It seems that the server was
receiving only the first line which causes a confusing "400 Bad Request - Add a line with the key `lfsFile`,
`file` or `deletedFile`". Passing raw bytes instead of a generator fixes the problem.
See https://github.com/huggingface/huggingface_hub/issues/1371.
"""
REPO_NAME = repo_name("CaSe_Is_ImPoRtAnT")
repo_id = self._api.create_repo(repo_id=REPO_NAME, exist_ok=False).repo_id
self._api.create_commit(
repo_id=repo_id.lower(), # API is case-insensitive!
commit_message="Add 1 regular and 1 LFs files.",
operations=[
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
CommitOperationAdd(path_in_repo="lfs.bin", path_or_fileobj=b"LFS content"),
],
)
repo_files = self._api.list_repo_files(repo_id=repo_id)
self.assertIn("file.txt", repo_files)
self.assertIn("lfs.bin", repo_files)
@use_tmp_repo()
def test_commit_copy_file(self, repo_url: RepoUrl) -> None:
"""Test CommitOperationCopy.
Works only when copying an LFS file.
"""
repo_id = repo_url.repo_id
self._api.upload_file(path_or_fileobj=b"content", repo_id=repo_id, path_in_repo="file.txt")
self._api.upload_file(path_or_fileobj=b"LFS content", repo_id=repo_id, path_in_repo="lfs.bin")
self._api.create_commit(
repo_id=repo_id,
commit_message="Copy LFS file.",
operations=[
CommitOperationCopy(src_path_in_repo="lfs.bin", path_in_repo="lfs Copy.bin"),
CommitOperationCopy(src_path_in_repo="lfs.bin", path_in_repo="lfs Copy (1).bin"),
],
)
self._api.create_commit(
repo_id=repo_id,
commit_message="Copy regular file.",
operations=[CommitOperationCopy(src_path_in_repo="file.txt", path_in_repo="file Copy.txt")],
)
with self.assertRaises(EntryNotFoundError):
self._api.create_commit(
repo_id=repo_id,
commit_message="Copy a file that doesn't exist.",
operations=[
CommitOperationCopy(src_path_in_repo="doesnt-exist.txt", path_in_repo="doesnt-exist Copy.txt")
],
)
# Check repo files
repo_files = self._api.list_repo_files(repo_id=repo_id)
self.assertIn("file.txt", repo_files)
self.assertIn("file Copy.txt", repo_files)
self.assertIn("lfs.bin", repo_files)
self.assertIn("lfs Copy.bin", repo_files)
self.assertIn("lfs Copy (1).bin", repo_files)
# Check same LFS file
repo_file1, repo_file2 = self._api.get_paths_info(repo_id=repo_id, paths=["lfs.bin", "lfs Copy.bin"])
self.assertEqual(repo_file1.lfs["sha256"], repo_file2.lfs["sha256"])
@use_tmp_repo()
def test_create_commit_mutates_operations(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
operations = [
CommitOperationAdd(path_in_repo="lfs.bin", path_or_fileobj=b"content"),
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
]
self._api.create_commit(
repo_id=repo_id,
commit_message="Copy LFS file.",
operations=operations,
)
assert operations[0]._is_committed
assert operations[0]._is_uploaded # LFS file
self.assertEqual(operations[0].path_or_fileobj, b"content") # not removed by default
assert operations[1]._is_committed
self.assertEqual(operations[1].path_or_fileobj, b"content")
@use_tmp_repo()
def test_pre_upload_before_commit(self, repo_url: RepoUrl) -> None:
repo_id = repo_url.repo_id
operations = [
CommitOperationAdd(path_in_repo="lfs.bin", path_or_fileobj=b"content1"),
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
CommitOperationAdd(path_in_repo="lfs2.bin", path_or_fileobj=b"content2"),
CommitOperationAdd(path_in_repo="file2.txt", path_or_fileobj=b"content"),
]
# First: preupload 1 by 1
for operation in operations:
self._api.preupload_lfs_files(repo_id, [operation])
assert operations[0]._is_uploaded
self.assertEqual(operations[0].path_or_fileobj, b"") # Freed memory
assert operations[2]._is_uploaded
self.assertEqual(operations[2].path_or_fileobj, b"") # Freed memory
# create commit and capture debug logs
with self.assertLogs("huggingface_hub", level="DEBUG") as debug_logs:
self._api.create_commit(
repo_id=repo_id,
commit_message="Copy LFS file.",
operations=operations,
)
# No LFS files uploaded during commit
assert any("No LFS files to upload." in log for log in debug_logs.output)
@use_tmp_repo()
def test_commit_modelcard_invalid_metadata(self, repo_url: RepoUrl) -> None:
with patch.object(self._api, "preupload_lfs_files") as mock:
with self.assertRaisesRegex(ValueError, "Invalid metadata in README.md"):
self._api.create_commit(
repo_id=repo_url.repo_id,
operations=[
CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=INVALID_MODELCARD.encode()),
CommitOperationAdd(path_in_repo="file.txt", path_or_fileobj=b"content"),
CommitOperationAdd(path_in_repo="lfs.bin", path_or_fileobj=b"content"),
],
commit_message="Test commit",
)