ZTWHHH commited on
Commit
1cd5034
·
verified ·
1 Parent(s): 6975f24

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. evalkit_internvl/lib/python3.10/site-packages/annotated_types/__init__.py +432 -0
  2. evalkit_internvl/lib/python3.10/site-packages/annotated_types/__pycache__/__init__.cpython-310.pyc +0 -0
  3. evalkit_internvl/lib/python3.10/site-packages/annotated_types/__pycache__/test_cases.cpython-310.pyc +0 -0
  4. evalkit_internvl/lib/python3.10/site-packages/annotated_types/py.typed +0 -0
  5. evalkit_internvl/lib/python3.10/site-packages/annotated_types/test_cases.py +151 -0
  6. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/__init__.py +1002 -0
  7. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py +327 -0
  8. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py +396 -0
  9. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_local_folder.py +425 -0
  10. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_login.py +536 -0
  11. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py +306 -0
  12. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py +304 -0
  13. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_space_api.py +160 -0
  14. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_upload_large_folder.py +621 -0
  15. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py +137 -0
  16. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_webhooks_server.py +386 -0
  17. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/community.py +355 -0
  18. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/constants.py +225 -0
  19. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/errors.py +310 -0
  20. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/fastai_utils.py +424 -0
  21. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/file_download.py +1624 -0
  22. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/hf_api.py +0 -0
  23. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/__init__.py +0 -0
  24. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-310.pyc +0 -0
  25. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-310.pyc +0 -0
  26. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_client.py +0 -0
  27. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_common.py +478 -0
  28. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__init__.py +0 -0
  29. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc +0 -0
  30. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/_async_client.py +0 -0
  31. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py +165 -0
  32. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_classification.py +46 -0
  33. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_to_audio.py +31 -0
  34. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py +140 -0
  35. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/document_question_answering.py +85 -0
  36. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/feature_extraction.py +37 -0
  37. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_classification.py +46 -0
  38. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_segmentation.py +54 -0
  39. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_image.py +57 -0
  40. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py +44 -0
  41. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/table_question_answering.py +45 -0
  42. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text2text_generation.py +45 -0
  43. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_classification.py +48 -0
  44. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py +169 -0
  45. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_audio.py +105 -0
  46. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_speech.py +107 -0
  47. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/video_classification.py +47 -0
  48. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_classification.py +56 -0
  49. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py +55 -0
  50. evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference_api.py +217 -0
evalkit_internvl/lib/python3.10/site-packages/annotated_types/__init__.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ import types
4
+ from dataclasses import dataclass
5
+ from datetime import tzinfo
6
+ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
7
+
8
+ if sys.version_info < (3, 8):
9
+ from typing_extensions import Protocol, runtime_checkable
10
+ else:
11
+ from typing import Protocol, runtime_checkable
12
+
13
+ if sys.version_info < (3, 9):
14
+ from typing_extensions import Annotated, Literal
15
+ else:
16
+ from typing import Annotated, Literal
17
+
18
+ if sys.version_info < (3, 10):
19
+ EllipsisType = type(Ellipsis)
20
+ KW_ONLY = {}
21
+ SLOTS = {}
22
+ else:
23
+ from types import EllipsisType
24
+
25
+ KW_ONLY = {"kw_only": True}
26
+ SLOTS = {"slots": True}
27
+
28
+
29
+ __all__ = (
30
+ 'BaseMetadata',
31
+ 'GroupedMetadata',
32
+ 'Gt',
33
+ 'Ge',
34
+ 'Lt',
35
+ 'Le',
36
+ 'Interval',
37
+ 'MultipleOf',
38
+ 'MinLen',
39
+ 'MaxLen',
40
+ 'Len',
41
+ 'Timezone',
42
+ 'Predicate',
43
+ 'LowerCase',
44
+ 'UpperCase',
45
+ 'IsDigits',
46
+ 'IsFinite',
47
+ 'IsNotFinite',
48
+ 'IsNan',
49
+ 'IsNotNan',
50
+ 'IsInfinite',
51
+ 'IsNotInfinite',
52
+ 'doc',
53
+ 'DocInfo',
54
+ '__version__',
55
+ )
56
+
57
+ __version__ = '0.7.0'
58
+
59
+
60
+ T = TypeVar('T')
61
+
62
+
63
+ # arguments that start with __ are considered
64
+ # positional only
65
+ # see https://peps.python.org/pep-0484/#positional-only-arguments
66
+
67
+
68
+ class SupportsGt(Protocol):
69
+ def __gt__(self: T, __other: T) -> bool:
70
+ ...
71
+
72
+
73
+ class SupportsGe(Protocol):
74
+ def __ge__(self: T, __other: T) -> bool:
75
+ ...
76
+
77
+
78
+ class SupportsLt(Protocol):
79
+ def __lt__(self: T, __other: T) -> bool:
80
+ ...
81
+
82
+
83
+ class SupportsLe(Protocol):
84
+ def __le__(self: T, __other: T) -> bool:
85
+ ...
86
+
87
+
88
+ class SupportsMod(Protocol):
89
+ def __mod__(self: T, __other: T) -> T:
90
+ ...
91
+
92
+
93
+ class SupportsDiv(Protocol):
94
+ def __div__(self: T, __other: T) -> T:
95
+ ...
96
+
97
+
98
+ class BaseMetadata:
99
+ """Base class for all metadata.
100
+
101
+ This exists mainly so that implementers
102
+ can do `isinstance(..., BaseMetadata)` while traversing field annotations.
103
+ """
104
+
105
+ __slots__ = ()
106
+
107
+
108
+ @dataclass(frozen=True, **SLOTS)
109
+ class Gt(BaseMetadata):
110
+ """Gt(gt=x) implies that the value must be greater than x.
111
+
112
+ It can be used with any type that supports the ``>`` operator,
113
+ including numbers, dates and times, strings, sets, and so on.
114
+ """
115
+
116
+ gt: SupportsGt
117
+
118
+
119
+ @dataclass(frozen=True, **SLOTS)
120
+ class Ge(BaseMetadata):
121
+ """Ge(ge=x) implies that the value must be greater than or equal to x.
122
+
123
+ It can be used with any type that supports the ``>=`` operator,
124
+ including numbers, dates and times, strings, sets, and so on.
125
+ """
126
+
127
+ ge: SupportsGe
128
+
129
+
130
+ @dataclass(frozen=True, **SLOTS)
131
+ class Lt(BaseMetadata):
132
+ """Lt(lt=x) implies that the value must be less than x.
133
+
134
+ It can be used with any type that supports the ``<`` operator,
135
+ including numbers, dates and times, strings, sets, and so on.
136
+ """
137
+
138
+ lt: SupportsLt
139
+
140
+
141
+ @dataclass(frozen=True, **SLOTS)
142
+ class Le(BaseMetadata):
143
+ """Le(le=x) implies that the value must be less than or equal to x.
144
+
145
+ It can be used with any type that supports the ``<=`` operator,
146
+ including numbers, dates and times, strings, sets, and so on.
147
+ """
148
+
149
+ le: SupportsLe
150
+
151
+
152
+ @runtime_checkable
153
+ class GroupedMetadata(Protocol):
154
+ """A grouping of multiple objects, like typing.Unpack.
155
+
156
+ `GroupedMetadata` on its own is not metadata and has no meaning.
157
+ All of the constraints and metadata should be fully expressable
158
+ in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`.
159
+
160
+ Concrete implementations should override `GroupedMetadata.__iter__()`
161
+ to add their own metadata.
162
+ For example:
163
+
164
+ >>> @dataclass
165
+ >>> class Field(GroupedMetadata):
166
+ >>> gt: float | None = None
167
+ >>> description: str | None = None
168
+ ...
169
+ >>> def __iter__(self) -> Iterable[object]:
170
+ >>> if self.gt is not None:
171
+ >>> yield Gt(self.gt)
172
+ >>> if self.description is not None:
173
+ >>> yield Description(self.gt)
174
+
175
+ Also see the implementation of `Interval` below for an example.
176
+
177
+ Parsers should recognize this and unpack it so that it can be used
178
+ both with and without unpacking:
179
+
180
+ - `Annotated[int, Field(...)]` (parser must unpack Field)
181
+ - `Annotated[int, *Field(...)]` (PEP-646)
182
+ """ # noqa: trailing-whitespace
183
+
184
+ @property
185
+ def __is_annotated_types_grouped_metadata__(self) -> Literal[True]:
186
+ return True
187
+
188
+ def __iter__(self) -> Iterator[object]:
189
+ ...
190
+
191
+ if not TYPE_CHECKING:
192
+ __slots__ = () # allow subclasses to use slots
193
+
194
+ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
195
+ # Basic ABC like functionality without the complexity of an ABC
196
+ super().__init_subclass__(*args, **kwargs)
197
+ if cls.__iter__ is GroupedMetadata.__iter__:
198
+ raise TypeError("Can't subclass GroupedMetadata without implementing __iter__")
199
+
200
+ def __iter__(self) -> Iterator[object]: # noqa: F811
201
+ raise NotImplementedError # more helpful than "None has no attribute..." type errors
202
+
203
+
204
+ @dataclass(frozen=True, **KW_ONLY, **SLOTS)
205
+ class Interval(GroupedMetadata):
206
+ """Interval can express inclusive or exclusive bounds with a single object.
207
+
208
+ It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which
209
+ are interpreted the same way as the single-bound constraints.
210
+ """
211
+
212
+ gt: Union[SupportsGt, None] = None
213
+ ge: Union[SupportsGe, None] = None
214
+ lt: Union[SupportsLt, None] = None
215
+ le: Union[SupportsLe, None] = None
216
+
217
+ def __iter__(self) -> Iterator[BaseMetadata]:
218
+ """Unpack an Interval into zero or more single-bounds."""
219
+ if self.gt is not None:
220
+ yield Gt(self.gt)
221
+ if self.ge is not None:
222
+ yield Ge(self.ge)
223
+ if self.lt is not None:
224
+ yield Lt(self.lt)
225
+ if self.le is not None:
226
+ yield Le(self.le)
227
+
228
+
229
+ @dataclass(frozen=True, **SLOTS)
230
+ class MultipleOf(BaseMetadata):
231
+ """MultipleOf(multiple_of=x) might be interpreted in two ways:
232
+
233
+ 1. Python semantics, implying ``value % multiple_of == 0``, or
234
+ 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of``
235
+
236
+ We encourage users to be aware of these two common interpretations,
237
+ and libraries to carefully document which they implement.
238
+ """
239
+
240
+ multiple_of: Union[SupportsDiv, SupportsMod]
241
+
242
+
243
+ @dataclass(frozen=True, **SLOTS)
244
+ class MinLen(BaseMetadata):
245
+ """
246
+ MinLen() implies minimum inclusive length,
247
+ e.g. ``len(value) >= min_length``.
248
+ """
249
+
250
+ min_length: Annotated[int, Ge(0)]
251
+
252
+
253
+ @dataclass(frozen=True, **SLOTS)
254
+ class MaxLen(BaseMetadata):
255
+ """
256
+ MaxLen() implies maximum inclusive length,
257
+ e.g. ``len(value) <= max_length``.
258
+ """
259
+
260
+ max_length: Annotated[int, Ge(0)]
261
+
262
+
263
+ @dataclass(frozen=True, **SLOTS)
264
+ class Len(GroupedMetadata):
265
+ """
266
+ Len() implies that ``min_length <= len(value) <= max_length``.
267
+
268
+ Upper bound may be omitted or ``None`` to indicate no upper length bound.
269
+ """
270
+
271
+ min_length: Annotated[int, Ge(0)] = 0
272
+ max_length: Optional[Annotated[int, Ge(0)]] = None
273
+
274
+ def __iter__(self) -> Iterator[BaseMetadata]:
275
+ """Unpack a Len into zone or more single-bounds."""
276
+ if self.min_length > 0:
277
+ yield MinLen(self.min_length)
278
+ if self.max_length is not None:
279
+ yield MaxLen(self.max_length)
280
+
281
+
282
+ @dataclass(frozen=True, **SLOTS)
283
+ class Timezone(BaseMetadata):
284
+ """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive).
285
+
286
+ ``Annotated[datetime, Timezone(None)]`` must be a naive datetime.
287
+ ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be
288
+ tz-aware but any timezone is allowed.
289
+
290
+ You may also pass a specific timezone string or tzinfo object such as
291
+ ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that
292
+ you only allow a specific timezone, though we note that this is often
293
+ a symptom of poor design.
294
+ """
295
+
296
+ tz: Union[str, tzinfo, EllipsisType, None]
297
+
298
+
299
+ @dataclass(frozen=True, **SLOTS)
300
+ class Unit(BaseMetadata):
301
+ """Indicates that the value is a physical quantity with the specified unit.
302
+
303
+ It is intended for usage with numeric types, where the value represents the
304
+ magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]``
305
+ or ``speed: Annotated[float, Unit('m/s')]``.
306
+
307
+ Interpretation of the unit string is left to the discretion of the consumer.
308
+ It is suggested to follow conventions established by python libraries that work
309
+ with physical quantities, such as
310
+
311
+ - ``pint`` : <https://pint.readthedocs.io/en/stable/>
312
+ - ``astropy.units``: <https://docs.astropy.org/en/stable/units/>
313
+
314
+ For indicating a quantity with a certain dimensionality but without a specific unit
315
+ it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`.
316
+ Note, however, ``annotated_types`` itself makes no use of the unit string.
317
+ """
318
+
319
+ unit: str
320
+
321
+
322
+ @dataclass(frozen=True, **SLOTS)
323
+ class Predicate(BaseMetadata):
324
+ """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values.
325
+
326
+ Users should prefer statically inspectable metadata, but if you need the full
327
+ power and flexibility of arbitrary runtime predicates... here it is.
328
+
329
+ We provide a few predefined predicates for common string constraints:
330
+ ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and
331
+ ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which
332
+ can be given special handling, and avoid indirection like ``lambda s: s.lower()``.
333
+
334
+ Some libraries might have special logic to handle certain predicates, e.g. by
335
+ checking for `str.isdigit` and using its presence to both call custom logic to
336
+ enforce digit-only strings, and customise some generated external schema.
337
+
338
+ We do not specify what behaviour should be expected for predicates that raise
339
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
340
+ skip invalid constraints, or statically raise an error; or it might try calling it
341
+ and then propagate or discard the resulting exception.
342
+ """
343
+
344
+ func: Callable[[Any], bool]
345
+
346
+ def __repr__(self) -> str:
347
+ if getattr(self.func, "__name__", "<lambda>") == "<lambda>":
348
+ return f"{self.__class__.__name__}({self.func!r})"
349
+ if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and (
350
+ namespace := getattr(self.func.__self__, "__name__", None)
351
+ ):
352
+ return f"{self.__class__.__name__}({namespace}.{self.func.__name__})"
353
+ if isinstance(self.func, type(str.isascii)): # method descriptor
354
+ return f"{self.__class__.__name__}({self.func.__qualname__})"
355
+ return f"{self.__class__.__name__}({self.func.__name__})"
356
+
357
+
358
+ @dataclass
359
+ class Not:
360
+ func: Callable[[Any], bool]
361
+
362
+ def __call__(self, __v: Any) -> bool:
363
+ return not self.func(__v)
364
+
365
+
366
+ _StrType = TypeVar("_StrType", bound=str)
367
+
368
+ LowerCase = Annotated[_StrType, Predicate(str.islower)]
369
+ """
370
+ Return True if the string is a lowercase string, False otherwise.
371
+
372
+ A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
373
+ """ # noqa: E501
374
+ UpperCase = Annotated[_StrType, Predicate(str.isupper)]
375
+ """
376
+ Return True if the string is an uppercase string, False otherwise.
377
+
378
+ A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
379
+ """ # noqa: E501
380
+ IsDigit = Annotated[_StrType, Predicate(str.isdigit)]
381
+ IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63
382
+ """
383
+ Return True if the string is a digit string, False otherwise.
384
+
385
+ A string is a digit string if all characters in the string are digits and there is at least one character in the string.
386
+ """ # noqa: E501
387
+ IsAscii = Annotated[_StrType, Predicate(str.isascii)]
388
+ """
389
+ Return True if all characters in the string are ASCII, False otherwise.
390
+
391
+ ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
392
+ """
393
+
394
+ _NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex])
395
+ IsFinite = Annotated[_NumericType, Predicate(math.isfinite)]
396
+ """Return True if x is neither an infinity nor a NaN, and False otherwise."""
397
+ IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))]
398
+ """Return True if x is one of infinity or NaN, and False otherwise"""
399
+ IsNan = Annotated[_NumericType, Predicate(math.isnan)]
400
+ """Return True if x is a NaN (not a number), and False otherwise."""
401
+ IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))]
402
+ """Return True if x is anything but NaN (not a number), and False otherwise."""
403
+ IsInfinite = Annotated[_NumericType, Predicate(math.isinf)]
404
+ """Return True if x is a positive or negative infinity, and False otherwise."""
405
+ IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))]
406
+ """Return True if x is neither a positive or negative infinity, and False otherwise."""
407
+
408
+ try:
409
+ from typing_extensions import DocInfo, doc # type: ignore [attr-defined]
410
+ except ImportError:
411
+
412
+ @dataclass(frozen=True, **SLOTS)
413
+ class DocInfo: # type: ignore [no-redef]
414
+ """ "
415
+ The return value of doc(), mainly to be used by tools that want to extract the
416
+ Annotated documentation at runtime.
417
+ """
418
+
419
+ documentation: str
420
+ """The documentation string passed to doc()."""
421
+
422
+ def doc(
423
+ documentation: str,
424
+ ) -> DocInfo:
425
+ """
426
+ Add documentation to a type annotation inside of Annotated.
427
+
428
+ For example:
429
+
430
+ >>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ...
431
+ """
432
+ return DocInfo(documentation)
evalkit_internvl/lib/python3.10/site-packages/annotated_types/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (14.6 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/annotated_types/__pycache__/test_cases.cpython-310.pyc ADDED
Binary file (5.63 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/annotated_types/py.typed ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/annotated_types/test_cases.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from datetime import date, datetime, timedelta, timezone
4
+ from decimal import Decimal
5
+ from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple
6
+
7
+ if sys.version_info < (3, 9):
8
+ from typing_extensions import Annotated
9
+ else:
10
+ from typing import Annotated
11
+
12
+ import annotated_types as at
13
+
14
+
15
+ class Case(NamedTuple):
16
+ """
17
+ A test case for `annotated_types`.
18
+ """
19
+
20
+ annotation: Any
21
+ valid_cases: Iterable[Any]
22
+ invalid_cases: Iterable[Any]
23
+
24
+
25
+ def cases() -> Iterable[Case]:
26
+ # Gt, Ge, Lt, Le
27
+ yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1))
28
+ yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1))
29
+ yield Case(
30
+ Annotated[datetime, at.Gt(datetime(2000, 1, 1))],
31
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
32
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
33
+ )
34
+ yield Case(
35
+ Annotated[datetime, at.Gt(date(2000, 1, 1))],
36
+ [date(2000, 1, 2), date(2000, 1, 3)],
37
+ [date(2000, 1, 1), date(1999, 12, 31)],
38
+ )
39
+ yield Case(
40
+ Annotated[datetime, at.Gt(Decimal('1.123'))],
41
+ [Decimal('1.1231'), Decimal('123')],
42
+ [Decimal('1.123'), Decimal('0')],
43
+ )
44
+
45
+ yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1))
46
+ yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1))
47
+ yield Case(
48
+ Annotated[datetime, at.Ge(datetime(2000, 1, 1))],
49
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
50
+ [datetime(1998, 1, 1), datetime(1999, 12, 31)],
51
+ )
52
+
53
+ yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4))
54
+ yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9))
55
+ yield Case(
56
+ Annotated[datetime, at.Lt(datetime(2000, 1, 1))],
57
+ [datetime(1999, 12, 31), datetime(1999, 12, 31)],
58
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
59
+ )
60
+
61
+ yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000))
62
+ yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9))
63
+ yield Case(
64
+ Annotated[datetime, at.Le(datetime(2000, 1, 1))],
65
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
66
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
67
+ )
68
+
69
+ # Interval
70
+ yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1))
71
+ yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1))
72
+ yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1))
73
+ yield Case(
74
+ Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))],
75
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
76
+ [datetime(2000, 1, 1), datetime(2000, 1, 4)],
77
+ )
78
+
79
+ yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4))
80
+ yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1))
81
+
82
+ # lengths
83
+
84
+ yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
85
+ yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
86
+ yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
87
+ yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
88
+
89
+ yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10))
90
+ yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10))
91
+ yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
92
+ yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
93
+
94
+ yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10))
95
+ yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234'))
96
+
97
+ yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}])
98
+ yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4}))
99
+ yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4)))
100
+
101
+ # Timezone
102
+
103
+ yield Case(
104
+ Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)]
105
+ )
106
+ yield Case(
107
+ Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)]
108
+ )
109
+ yield Case(
110
+ Annotated[datetime, at.Timezone(timezone.utc)],
111
+ [datetime(2000, 1, 1, tzinfo=timezone.utc)],
112
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
113
+ )
114
+ yield Case(
115
+ Annotated[datetime, at.Timezone('Europe/London')],
116
+ [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))],
117
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
118
+ )
119
+
120
+ # Quantity
121
+
122
+ yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m'))
123
+
124
+ # predicate types
125
+
126
+ yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom'])
127
+ yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC'])
128
+ yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2'])
129
+ yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀'])
130
+
131
+ yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5])
132
+
133
+ yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf])
134
+ yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23])
135
+ yield Case(at.IsNan[float], [math.nan], [1.23, math.inf])
136
+ yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan])
137
+ yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23])
138
+ yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf])
139
+
140
+ # check stacked predicates
141
+ yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan])
142
+
143
+ # doc
144
+ yield Case(Annotated[int, at.doc("A number")], [1, 2], [])
145
+
146
+ # custom GroupedMetadata
147
+ class MyCustomGroupedMetadata(at.GroupedMetadata):
148
+ def __iter__(self) -> Iterator[at.Predicate]:
149
+ yield at.Predicate(lambda x: float(x).is_integer())
150
+
151
+ yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5])
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/__init__.py ADDED
@@ -0,0 +1,1002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # ***********
16
+ # `huggingface_hub` init has 2 modes:
17
+ # - Normal usage:
18
+ # If imported to use it, all modules and functions are lazy-loaded. This means
19
+ # they exist at top level in module but are imported only the first time they are
20
+ # used. This way, `from huggingface_hub import something` will import `something`
21
+ # quickly without the hassle of importing all the features from `huggingface_hub`.
22
+ # - Static check:
23
+ # If statically analyzed, all modules and functions are loaded normally. This way
24
+ # static typing check works properly as well as autocomplete in text editors and
25
+ # IDEs.
26
+ #
27
+ # The static model imports are done inside the `if TYPE_CHECKING:` statement at
28
+ # the bottom of this file. Since module/functions imports are duplicated, it is
29
+ # mandatory to make sure to add them twice when adding one. This is checked in the
30
+ # `make quality` command.
31
+ #
32
+ # To update the static imports, please run the following command and commit the changes.
33
+ # ```
34
+ # # Use script
35
+ # python utils/check_static_imports.py --update-file
36
+ #
37
+ # # Or run style on codebase
38
+ # make style
39
+ # ```
40
+ #
41
+ # ***********
42
+ # Lazy loader vendored from https://github.com/scientific-python/lazy_loader
43
+ import importlib
44
+ import os
45
+ import sys
46
+ from typing import TYPE_CHECKING
47
+
48
+
49
+ __version__ = "0.26.2"
50
+
51
+ # Alphabetical order of definitions is ensured in tests
52
+ # WARNING: any comment added in this dictionary definition will be lost when
53
+ # re-generating the file !
54
+ _SUBMOD_ATTRS = {
55
+ "_commit_scheduler": [
56
+ "CommitScheduler",
57
+ ],
58
+ "_inference_endpoints": [
59
+ "InferenceEndpoint",
60
+ "InferenceEndpointError",
61
+ "InferenceEndpointStatus",
62
+ "InferenceEndpointTimeoutError",
63
+ "InferenceEndpointType",
64
+ ],
65
+ "_login": [
66
+ "auth_list",
67
+ "auth_switch",
68
+ "interpreter_login",
69
+ "login",
70
+ "logout",
71
+ "notebook_login",
72
+ ],
73
+ "_multi_commits": [
74
+ "MultiCommitException",
75
+ "plan_multi_commits",
76
+ ],
77
+ "_snapshot_download": [
78
+ "snapshot_download",
79
+ ],
80
+ "_space_api": [
81
+ "SpaceHardware",
82
+ "SpaceRuntime",
83
+ "SpaceStage",
84
+ "SpaceStorage",
85
+ "SpaceVariable",
86
+ ],
87
+ "_tensorboard_logger": [
88
+ "HFSummaryWriter",
89
+ ],
90
+ "_webhooks_payload": [
91
+ "WebhookPayload",
92
+ "WebhookPayloadComment",
93
+ "WebhookPayloadDiscussion",
94
+ "WebhookPayloadDiscussionChanges",
95
+ "WebhookPayloadEvent",
96
+ "WebhookPayloadMovedTo",
97
+ "WebhookPayloadRepo",
98
+ "WebhookPayloadUrl",
99
+ "WebhookPayloadWebhook",
100
+ ],
101
+ "_webhooks_server": [
102
+ "WebhooksServer",
103
+ "webhook_endpoint",
104
+ ],
105
+ "community": [
106
+ "Discussion",
107
+ "DiscussionComment",
108
+ "DiscussionCommit",
109
+ "DiscussionEvent",
110
+ "DiscussionStatusChange",
111
+ "DiscussionTitleChange",
112
+ "DiscussionWithDetails",
113
+ ],
114
+ "constants": [
115
+ "CONFIG_NAME",
116
+ "FLAX_WEIGHTS_NAME",
117
+ "HUGGINGFACE_CO_URL_HOME",
118
+ "HUGGINGFACE_CO_URL_TEMPLATE",
119
+ "PYTORCH_WEIGHTS_NAME",
120
+ "REPO_TYPE_DATASET",
121
+ "REPO_TYPE_MODEL",
122
+ "REPO_TYPE_SPACE",
123
+ "TF2_WEIGHTS_NAME",
124
+ "TF_WEIGHTS_NAME",
125
+ ],
126
+ "fastai_utils": [
127
+ "_save_pretrained_fastai",
128
+ "from_pretrained_fastai",
129
+ "push_to_hub_fastai",
130
+ ],
131
+ "file_download": [
132
+ "HfFileMetadata",
133
+ "_CACHED_NO_EXIST",
134
+ "get_hf_file_metadata",
135
+ "hf_hub_download",
136
+ "hf_hub_url",
137
+ "try_to_load_from_cache",
138
+ ],
139
+ "hf_api": [
140
+ "Collection",
141
+ "CollectionItem",
142
+ "CommitInfo",
143
+ "CommitOperation",
144
+ "CommitOperationAdd",
145
+ "CommitOperationCopy",
146
+ "CommitOperationDelete",
147
+ "DatasetInfo",
148
+ "GitCommitInfo",
149
+ "GitRefInfo",
150
+ "GitRefs",
151
+ "HfApi",
152
+ "ModelInfo",
153
+ "RepoUrl",
154
+ "SpaceInfo",
155
+ "User",
156
+ "UserLikes",
157
+ "WebhookInfo",
158
+ "WebhookWatchedItem",
159
+ "accept_access_request",
160
+ "add_collection_item",
161
+ "add_space_secret",
162
+ "add_space_variable",
163
+ "auth_check",
164
+ "cancel_access_request",
165
+ "change_discussion_status",
166
+ "comment_discussion",
167
+ "create_branch",
168
+ "create_collection",
169
+ "create_commit",
170
+ "create_commits_on_pr",
171
+ "create_discussion",
172
+ "create_inference_endpoint",
173
+ "create_pull_request",
174
+ "create_repo",
175
+ "create_tag",
176
+ "create_webhook",
177
+ "dataset_info",
178
+ "delete_branch",
179
+ "delete_collection",
180
+ "delete_collection_item",
181
+ "delete_file",
182
+ "delete_folder",
183
+ "delete_inference_endpoint",
184
+ "delete_repo",
185
+ "delete_space_secret",
186
+ "delete_space_storage",
187
+ "delete_space_variable",
188
+ "delete_tag",
189
+ "delete_webhook",
190
+ "disable_webhook",
191
+ "duplicate_space",
192
+ "edit_discussion_comment",
193
+ "enable_webhook",
194
+ "file_exists",
195
+ "get_collection",
196
+ "get_dataset_tags",
197
+ "get_discussion_details",
198
+ "get_full_repo_name",
199
+ "get_inference_endpoint",
200
+ "get_model_tags",
201
+ "get_paths_info",
202
+ "get_repo_discussions",
203
+ "get_safetensors_metadata",
204
+ "get_space_runtime",
205
+ "get_space_variables",
206
+ "get_token_permission",
207
+ "get_user_overview",
208
+ "get_webhook",
209
+ "grant_access",
210
+ "like",
211
+ "list_accepted_access_requests",
212
+ "list_collections",
213
+ "list_datasets",
214
+ "list_inference_endpoints",
215
+ "list_liked_repos",
216
+ "list_metrics",
217
+ "list_models",
218
+ "list_organization_members",
219
+ "list_papers",
220
+ "list_pending_access_requests",
221
+ "list_rejected_access_requests",
222
+ "list_repo_commits",
223
+ "list_repo_files",
224
+ "list_repo_likers",
225
+ "list_repo_refs",
226
+ "list_repo_tree",
227
+ "list_spaces",
228
+ "list_user_followers",
229
+ "list_user_following",
230
+ "list_webhooks",
231
+ "merge_pull_request",
232
+ "model_info",
233
+ "move_repo",
234
+ "paper_info",
235
+ "parse_safetensors_file_metadata",
236
+ "pause_inference_endpoint",
237
+ "pause_space",
238
+ "preupload_lfs_files",
239
+ "reject_access_request",
240
+ "rename_discussion",
241
+ "repo_exists",
242
+ "repo_info",
243
+ "repo_type_and_id_from_hf_id",
244
+ "request_space_hardware",
245
+ "request_space_storage",
246
+ "restart_space",
247
+ "resume_inference_endpoint",
248
+ "revision_exists",
249
+ "run_as_future",
250
+ "scale_to_zero_inference_endpoint",
251
+ "set_space_sleep_time",
252
+ "space_info",
253
+ "super_squash_history",
254
+ "unlike",
255
+ "update_collection_item",
256
+ "update_collection_metadata",
257
+ "update_inference_endpoint",
258
+ "update_repo_settings",
259
+ "update_repo_visibility",
260
+ "update_webhook",
261
+ "upload_file",
262
+ "upload_folder",
263
+ "upload_large_folder",
264
+ "whoami",
265
+ ],
266
+ "hf_file_system": [
267
+ "HfFileSystem",
268
+ "HfFileSystemFile",
269
+ "HfFileSystemResolvedPath",
270
+ "HfFileSystemStreamFile",
271
+ ],
272
+ "hub_mixin": [
273
+ "ModelHubMixin",
274
+ "PyTorchModelHubMixin",
275
+ ],
276
+ "inference._client": [
277
+ "InferenceClient",
278
+ "InferenceTimeoutError",
279
+ ],
280
+ "inference._generated._async_client": [
281
+ "AsyncInferenceClient",
282
+ ],
283
+ "inference._generated.types": [
284
+ "AudioClassificationInput",
285
+ "AudioClassificationOutputElement",
286
+ "AudioClassificationOutputTransform",
287
+ "AudioClassificationParameters",
288
+ "AudioToAudioInput",
289
+ "AudioToAudioOutputElement",
290
+ "AutomaticSpeechRecognitionEarlyStoppingEnum",
291
+ "AutomaticSpeechRecognitionGenerationParameters",
292
+ "AutomaticSpeechRecognitionInput",
293
+ "AutomaticSpeechRecognitionOutput",
294
+ "AutomaticSpeechRecognitionOutputChunk",
295
+ "AutomaticSpeechRecognitionParameters",
296
+ "ChatCompletionInput",
297
+ "ChatCompletionInputFunctionDefinition",
298
+ "ChatCompletionInputFunctionName",
299
+ "ChatCompletionInputGrammarType",
300
+ "ChatCompletionInputMessage",
301
+ "ChatCompletionInputMessageChunk",
302
+ "ChatCompletionInputStreamOptions",
303
+ "ChatCompletionInputToolType",
304
+ "ChatCompletionInputURL",
305
+ "ChatCompletionOutput",
306
+ "ChatCompletionOutputComplete",
307
+ "ChatCompletionOutputFunctionDefinition",
308
+ "ChatCompletionOutputLogprob",
309
+ "ChatCompletionOutputLogprobs",
310
+ "ChatCompletionOutputMessage",
311
+ "ChatCompletionOutputToolCall",
312
+ "ChatCompletionOutputTopLogprob",
313
+ "ChatCompletionOutputUsage",
314
+ "ChatCompletionStreamOutput",
315
+ "ChatCompletionStreamOutputChoice",
316
+ "ChatCompletionStreamOutputDelta",
317
+ "ChatCompletionStreamOutputDeltaToolCall",
318
+ "ChatCompletionStreamOutputFunction",
319
+ "ChatCompletionStreamOutputLogprob",
320
+ "ChatCompletionStreamOutputLogprobs",
321
+ "ChatCompletionStreamOutputTopLogprob",
322
+ "ChatCompletionStreamOutputUsage",
323
+ "DepthEstimationInput",
324
+ "DepthEstimationOutput",
325
+ "DocumentQuestionAnsweringInput",
326
+ "DocumentQuestionAnsweringInputData",
327
+ "DocumentQuestionAnsweringOutputElement",
328
+ "DocumentQuestionAnsweringParameters",
329
+ "FeatureExtractionInput",
330
+ "FillMaskInput",
331
+ "FillMaskOutputElement",
332
+ "FillMaskParameters",
333
+ "ImageClassificationInput",
334
+ "ImageClassificationOutputElement",
335
+ "ImageClassificationOutputTransform",
336
+ "ImageClassificationParameters",
337
+ "ImageSegmentationInput",
338
+ "ImageSegmentationOutputElement",
339
+ "ImageSegmentationParameters",
340
+ "ImageToImageInput",
341
+ "ImageToImageOutput",
342
+ "ImageToImageParameters",
343
+ "ImageToImageTargetSize",
344
+ "ImageToTextEarlyStoppingEnum",
345
+ "ImageToTextGenerationParameters",
346
+ "ImageToTextInput",
347
+ "ImageToTextOutput",
348
+ "ImageToTextParameters",
349
+ "ObjectDetectionBoundingBox",
350
+ "ObjectDetectionInput",
351
+ "ObjectDetectionOutputElement",
352
+ "ObjectDetectionParameters",
353
+ "QuestionAnsweringInput",
354
+ "QuestionAnsweringInputData",
355
+ "QuestionAnsweringOutputElement",
356
+ "QuestionAnsweringParameters",
357
+ "SentenceSimilarityInput",
358
+ "SentenceSimilarityInputData",
359
+ "SummarizationInput",
360
+ "SummarizationOutput",
361
+ "SummarizationParameters",
362
+ "TableQuestionAnsweringInput",
363
+ "TableQuestionAnsweringInputData",
364
+ "TableQuestionAnsweringOutputElement",
365
+ "Text2TextGenerationInput",
366
+ "Text2TextGenerationOutput",
367
+ "Text2TextGenerationParameters",
368
+ "TextClassificationInput",
369
+ "TextClassificationOutputElement",
370
+ "TextClassificationOutputTransform",
371
+ "TextClassificationParameters",
372
+ "TextGenerationInput",
373
+ "TextGenerationInputGenerateParameters",
374
+ "TextGenerationInputGrammarType",
375
+ "TextGenerationOutput",
376
+ "TextGenerationOutputBestOfSequence",
377
+ "TextGenerationOutputDetails",
378
+ "TextGenerationOutputPrefillToken",
379
+ "TextGenerationOutputToken",
380
+ "TextGenerationStreamOutput",
381
+ "TextGenerationStreamOutputStreamDetails",
382
+ "TextGenerationStreamOutputToken",
383
+ "TextToAudioEarlyStoppingEnum",
384
+ "TextToAudioGenerationParameters",
385
+ "TextToAudioInput",
386
+ "TextToAudioOutput",
387
+ "TextToAudioParameters",
388
+ "TextToImageInput",
389
+ "TextToImageOutput",
390
+ "TextToImageParameters",
391
+ "TextToImageTargetSize",
392
+ "TextToSpeechEarlyStoppingEnum",
393
+ "TextToSpeechGenerationParameters",
394
+ "TextToSpeechInput",
395
+ "TextToSpeechOutput",
396
+ "TextToSpeechParameters",
397
+ "TokenClassificationInput",
398
+ "TokenClassificationOutputElement",
399
+ "TokenClassificationParameters",
400
+ "ToolElement",
401
+ "TranslationInput",
402
+ "TranslationOutput",
403
+ "TranslationParameters",
404
+ "VideoClassificationInput",
405
+ "VideoClassificationOutputElement",
406
+ "VideoClassificationOutputTransform",
407
+ "VideoClassificationParameters",
408
+ "VisualQuestionAnsweringInput",
409
+ "VisualQuestionAnsweringInputData",
410
+ "VisualQuestionAnsweringOutputElement",
411
+ "VisualQuestionAnsweringParameters",
412
+ "ZeroShotClassificationInput",
413
+ "ZeroShotClassificationInputData",
414
+ "ZeroShotClassificationOutputElement",
415
+ "ZeroShotClassificationParameters",
416
+ "ZeroShotImageClassificationInput",
417
+ "ZeroShotImageClassificationInputData",
418
+ "ZeroShotImageClassificationOutputElement",
419
+ "ZeroShotImageClassificationParameters",
420
+ "ZeroShotObjectDetectionBoundingBox",
421
+ "ZeroShotObjectDetectionInput",
422
+ "ZeroShotObjectDetectionInputData",
423
+ "ZeroShotObjectDetectionOutputElement",
424
+ ],
425
+ "inference_api": [
426
+ "InferenceApi",
427
+ ],
428
+ "keras_mixin": [
429
+ "KerasModelHubMixin",
430
+ "from_pretrained_keras",
431
+ "push_to_hub_keras",
432
+ "save_pretrained_keras",
433
+ ],
434
+ "repocard": [
435
+ "DatasetCard",
436
+ "ModelCard",
437
+ "RepoCard",
438
+ "SpaceCard",
439
+ "metadata_eval_result",
440
+ "metadata_load",
441
+ "metadata_save",
442
+ "metadata_update",
443
+ ],
444
+ "repocard_data": [
445
+ "CardData",
446
+ "DatasetCardData",
447
+ "EvalResult",
448
+ "ModelCardData",
449
+ "SpaceCardData",
450
+ ],
451
+ "repository": [
452
+ "Repository",
453
+ ],
454
+ "serialization": [
455
+ "StateDictSplit",
456
+ "get_tf_storage_size",
457
+ "get_torch_storage_id",
458
+ "get_torch_storage_size",
459
+ "save_torch_model",
460
+ "save_torch_state_dict",
461
+ "split_state_dict_into_shards_factory",
462
+ "split_tf_state_dict_into_shards",
463
+ "split_torch_state_dict_into_shards",
464
+ ],
465
+ "utils": [
466
+ "CacheNotFound",
467
+ "CachedFileInfo",
468
+ "CachedRepoInfo",
469
+ "CachedRevisionInfo",
470
+ "CorruptedCacheException",
471
+ "DeleteCacheStrategy",
472
+ "HFCacheInfo",
473
+ "HfFolder",
474
+ "cached_assets_path",
475
+ "configure_http_backend",
476
+ "dump_environment_info",
477
+ "get_session",
478
+ "get_token",
479
+ "logging",
480
+ "scan_cache_dir",
481
+ ],
482
+ }
483
+
484
+
485
+ def _attach(package_name, submodules=None, submod_attrs=None):
486
+ """Attach lazily loaded submodules, functions, or other attributes.
487
+
488
+ Typically, modules import submodules and attributes as follows:
489
+
490
+ ```py
491
+ import mysubmodule
492
+ import anothersubmodule
493
+
494
+ from .foo import someattr
495
+ ```
496
+
497
+ The idea is to replace a package's `__getattr__`, `__dir__`, and
498
+ `__all__`, such that all imports work exactly the way they would
499
+ with normal imports, except that the import occurs upon first use.
500
+
501
+ The typical way to call this function, replacing the above imports, is:
502
+
503
+ ```python
504
+ __getattr__, __dir__, __all__ = lazy.attach(
505
+ __name__,
506
+ ['mysubmodule', 'anothersubmodule'],
507
+ {'foo': ['someattr']}
508
+ )
509
+ ```
510
+ This functionality requires Python 3.7 or higher.
511
+
512
+ Args:
513
+ package_name (`str`):
514
+ Typically use `__name__`.
515
+ submodules (`set`):
516
+ List of submodules to attach.
517
+ submod_attrs (`dict`):
518
+ Dictionary of submodule -> list of attributes / functions.
519
+ These attributes are imported as they are used.
520
+
521
+ Returns:
522
+ __getattr__, __dir__, __all__
523
+
524
+ """
525
+ if submod_attrs is None:
526
+ submod_attrs = {}
527
+
528
+ if submodules is None:
529
+ submodules = set()
530
+ else:
531
+ submodules = set(submodules)
532
+
533
+ attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
534
+
535
+ __all__ = list(submodules | attr_to_modules.keys())
536
+
537
+ def __getattr__(name):
538
+ if name in submodules:
539
+ try:
540
+ return importlib.import_module(f"{package_name}.{name}")
541
+ except Exception as e:
542
+ print(f"Error importing {package_name}.{name}: {e}")
543
+ raise
544
+ elif name in attr_to_modules:
545
+ submod_path = f"{package_name}.{attr_to_modules[name]}"
546
+ try:
547
+ submod = importlib.import_module(submod_path)
548
+ except Exception as e:
549
+ print(f"Error importing {submod_path}: {e}")
550
+ raise
551
+ attr = getattr(submod, name)
552
+
553
+ # If the attribute lives in a file (module) with the same
554
+ # name as the attribute, ensure that the attribute and *not*
555
+ # the module is accessible on the package.
556
+ if name == attr_to_modules[name]:
557
+ pkg = sys.modules[package_name]
558
+ pkg.__dict__[name] = attr
559
+
560
+ return attr
561
+ else:
562
+ raise AttributeError(f"No {package_name} attribute {name}")
563
+
564
+ def __dir__():
565
+ return __all__
566
+
567
+ return __getattr__, __dir__, list(__all__)
568
+
569
+
570
+ __getattr__, __dir__, __all__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
571
+
572
+ if os.environ.get("EAGER_IMPORT", ""):
573
+ for attr in __all__:
574
+ __getattr__(attr)
575
+
576
+ # WARNING: any content below this statement is generated automatically. Any manual edit
577
+ # will be lost when re-generating this file !
578
+ #
579
+ # To update the static imports, please run the following command and commit the changes.
580
+ # ```
581
+ # # Use script
582
+ # python utils/check_static_imports.py --update-file
583
+ #
584
+ # # Or run style on codebase
585
+ # make style
586
+ # ```
587
+ if TYPE_CHECKING: # pragma: no cover
588
+ from ._commit_scheduler import CommitScheduler # noqa: F401
589
+ from ._inference_endpoints import (
590
+ InferenceEndpoint, # noqa: F401
591
+ InferenceEndpointError, # noqa: F401
592
+ InferenceEndpointStatus, # noqa: F401
593
+ InferenceEndpointTimeoutError, # noqa: F401
594
+ InferenceEndpointType, # noqa: F401
595
+ )
596
+ from ._login import (
597
+ auth_list, # noqa: F401
598
+ auth_switch, # noqa: F401
599
+ interpreter_login, # noqa: F401
600
+ login, # noqa: F401
601
+ logout, # noqa: F401
602
+ notebook_login, # noqa: F401
603
+ )
604
+ from ._multi_commits import (
605
+ MultiCommitException, # noqa: F401
606
+ plan_multi_commits, # noqa: F401
607
+ )
608
+ from ._snapshot_download import snapshot_download # noqa: F401
609
+ from ._space_api import (
610
+ SpaceHardware, # noqa: F401
611
+ SpaceRuntime, # noqa: F401
612
+ SpaceStage, # noqa: F401
613
+ SpaceStorage, # noqa: F401
614
+ SpaceVariable, # noqa: F401
615
+ )
616
+ from ._tensorboard_logger import HFSummaryWriter # noqa: F401
617
+ from ._webhooks_payload import (
618
+ WebhookPayload, # noqa: F401
619
+ WebhookPayloadComment, # noqa: F401
620
+ WebhookPayloadDiscussion, # noqa: F401
621
+ WebhookPayloadDiscussionChanges, # noqa: F401
622
+ WebhookPayloadEvent, # noqa: F401
623
+ WebhookPayloadMovedTo, # noqa: F401
624
+ WebhookPayloadRepo, # noqa: F401
625
+ WebhookPayloadUrl, # noqa: F401
626
+ WebhookPayloadWebhook, # noqa: F401
627
+ )
628
+ from ._webhooks_server import (
629
+ WebhooksServer, # noqa: F401
630
+ webhook_endpoint, # noqa: F401
631
+ )
632
+ from .community import (
633
+ Discussion, # noqa: F401
634
+ DiscussionComment, # noqa: F401
635
+ DiscussionCommit, # noqa: F401
636
+ DiscussionEvent, # noqa: F401
637
+ DiscussionStatusChange, # noqa: F401
638
+ DiscussionTitleChange, # noqa: F401
639
+ DiscussionWithDetails, # noqa: F401
640
+ )
641
+ from .constants import (
642
+ CONFIG_NAME, # noqa: F401
643
+ FLAX_WEIGHTS_NAME, # noqa: F401
644
+ HUGGINGFACE_CO_URL_HOME, # noqa: F401
645
+ HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
646
+ PYTORCH_WEIGHTS_NAME, # noqa: F401
647
+ REPO_TYPE_DATASET, # noqa: F401
648
+ REPO_TYPE_MODEL, # noqa: F401
649
+ REPO_TYPE_SPACE, # noqa: F401
650
+ TF2_WEIGHTS_NAME, # noqa: F401
651
+ TF_WEIGHTS_NAME, # noqa: F401
652
+ )
653
+ from .fastai_utils import (
654
+ _save_pretrained_fastai, # noqa: F401
655
+ from_pretrained_fastai, # noqa: F401
656
+ push_to_hub_fastai, # noqa: F401
657
+ )
658
+ from .file_download import (
659
+ _CACHED_NO_EXIST, # noqa: F401
660
+ HfFileMetadata, # noqa: F401
661
+ get_hf_file_metadata, # noqa: F401
662
+ hf_hub_download, # noqa: F401
663
+ hf_hub_url, # noqa: F401
664
+ try_to_load_from_cache, # noqa: F401
665
+ )
666
+ from .hf_api import (
667
+ Collection, # noqa: F401
668
+ CollectionItem, # noqa: F401
669
+ CommitInfo, # noqa: F401
670
+ CommitOperation, # noqa: F401
671
+ CommitOperationAdd, # noqa: F401
672
+ CommitOperationCopy, # noqa: F401
673
+ CommitOperationDelete, # noqa: F401
674
+ DatasetInfo, # noqa: F401
675
+ GitCommitInfo, # noqa: F401
676
+ GitRefInfo, # noqa: F401
677
+ GitRefs, # noqa: F401
678
+ HfApi, # noqa: F401
679
+ ModelInfo, # noqa: F401
680
+ RepoUrl, # noqa: F401
681
+ SpaceInfo, # noqa: F401
682
+ User, # noqa: F401
683
+ UserLikes, # noqa: F401
684
+ WebhookInfo, # noqa: F401
685
+ WebhookWatchedItem, # noqa: F401
686
+ accept_access_request, # noqa: F401
687
+ add_collection_item, # noqa: F401
688
+ add_space_secret, # noqa: F401
689
+ add_space_variable, # noqa: F401
690
+ auth_check, # noqa: F401
691
+ cancel_access_request, # noqa: F401
692
+ change_discussion_status, # noqa: F401
693
+ comment_discussion, # noqa: F401
694
+ create_branch, # noqa: F401
695
+ create_collection, # noqa: F401
696
+ create_commit, # noqa: F401
697
+ create_commits_on_pr, # noqa: F401
698
+ create_discussion, # noqa: F401
699
+ create_inference_endpoint, # noqa: F401
700
+ create_pull_request, # noqa: F401
701
+ create_repo, # noqa: F401
702
+ create_tag, # noqa: F401
703
+ create_webhook, # noqa: F401
704
+ dataset_info, # noqa: F401
705
+ delete_branch, # noqa: F401
706
+ delete_collection, # noqa: F401
707
+ delete_collection_item, # noqa: F401
708
+ delete_file, # noqa: F401
709
+ delete_folder, # noqa: F401
710
+ delete_inference_endpoint, # noqa: F401
711
+ delete_repo, # noqa: F401
712
+ delete_space_secret, # noqa: F401
713
+ delete_space_storage, # noqa: F401
714
+ delete_space_variable, # noqa: F401
715
+ delete_tag, # noqa: F401
716
+ delete_webhook, # noqa: F401
717
+ disable_webhook, # noqa: F401
718
+ duplicate_space, # noqa: F401
719
+ edit_discussion_comment, # noqa: F401
720
+ enable_webhook, # noqa: F401
721
+ file_exists, # noqa: F401
722
+ get_collection, # noqa: F401
723
+ get_dataset_tags, # noqa: F401
724
+ get_discussion_details, # noqa: F401
725
+ get_full_repo_name, # noqa: F401
726
+ get_inference_endpoint, # noqa: F401
727
+ get_model_tags, # noqa: F401
728
+ get_paths_info, # noqa: F401
729
+ get_repo_discussions, # noqa: F401
730
+ get_safetensors_metadata, # noqa: F401
731
+ get_space_runtime, # noqa: F401
732
+ get_space_variables, # noqa: F401
733
+ get_token_permission, # noqa: F401
734
+ get_user_overview, # noqa: F401
735
+ get_webhook, # noqa: F401
736
+ grant_access, # noqa: F401
737
+ like, # noqa: F401
738
+ list_accepted_access_requests, # noqa: F401
739
+ list_collections, # noqa: F401
740
+ list_datasets, # noqa: F401
741
+ list_inference_endpoints, # noqa: F401
742
+ list_liked_repos, # noqa: F401
743
+ list_metrics, # noqa: F401
744
+ list_models, # noqa: F401
745
+ list_organization_members, # noqa: F401
746
+ list_papers, # noqa: F401
747
+ list_pending_access_requests, # noqa: F401
748
+ list_rejected_access_requests, # noqa: F401
749
+ list_repo_commits, # noqa: F401
750
+ list_repo_files, # noqa: F401
751
+ list_repo_likers, # noqa: F401
752
+ list_repo_refs, # noqa: F401
753
+ list_repo_tree, # noqa: F401
754
+ list_spaces, # noqa: F401
755
+ list_user_followers, # noqa: F401
756
+ list_user_following, # noqa: F401
757
+ list_webhooks, # noqa: F401
758
+ merge_pull_request, # noqa: F401
759
+ model_info, # noqa: F401
760
+ move_repo, # noqa: F401
761
+ paper_info, # noqa: F401
762
+ parse_safetensors_file_metadata, # noqa: F401
763
+ pause_inference_endpoint, # noqa: F401
764
+ pause_space, # noqa: F401
765
+ preupload_lfs_files, # noqa: F401
766
+ reject_access_request, # noqa: F401
767
+ rename_discussion, # noqa: F401
768
+ repo_exists, # noqa: F401
769
+ repo_info, # noqa: F401
770
+ repo_type_and_id_from_hf_id, # noqa: F401
771
+ request_space_hardware, # noqa: F401
772
+ request_space_storage, # noqa: F401
773
+ restart_space, # noqa: F401
774
+ resume_inference_endpoint, # noqa: F401
775
+ revision_exists, # noqa: F401
776
+ run_as_future, # noqa: F401
777
+ scale_to_zero_inference_endpoint, # noqa: F401
778
+ set_space_sleep_time, # noqa: F401
779
+ space_info, # noqa: F401
780
+ super_squash_history, # noqa: F401
781
+ unlike, # noqa: F401
782
+ update_collection_item, # noqa: F401
783
+ update_collection_metadata, # noqa: F401
784
+ update_inference_endpoint, # noqa: F401
785
+ update_repo_settings, # noqa: F401
786
+ update_repo_visibility, # noqa: F401
787
+ update_webhook, # noqa: F401
788
+ upload_file, # noqa: F401
789
+ upload_folder, # noqa: F401
790
+ upload_large_folder, # noqa: F401
791
+ whoami, # noqa: F401
792
+ )
793
+ from .hf_file_system import (
794
+ HfFileSystem, # noqa: F401
795
+ HfFileSystemFile, # noqa: F401
796
+ HfFileSystemResolvedPath, # noqa: F401
797
+ HfFileSystemStreamFile, # noqa: F401
798
+ )
799
+ from .hub_mixin import (
800
+ ModelHubMixin, # noqa: F401
801
+ PyTorchModelHubMixin, # noqa: F401
802
+ )
803
+ from .inference._client import (
804
+ InferenceClient, # noqa: F401
805
+ InferenceTimeoutError, # noqa: F401
806
+ )
807
+ from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
808
+ from .inference._generated.types import (
809
+ AudioClassificationInput, # noqa: F401
810
+ AudioClassificationOutputElement, # noqa: F401
811
+ AudioClassificationOutputTransform, # noqa: F401
812
+ AudioClassificationParameters, # noqa: F401
813
+ AudioToAudioInput, # noqa: F401
814
+ AudioToAudioOutputElement, # noqa: F401
815
+ AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401
816
+ AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
817
+ AutomaticSpeechRecognitionInput, # noqa: F401
818
+ AutomaticSpeechRecognitionOutput, # noqa: F401
819
+ AutomaticSpeechRecognitionOutputChunk, # noqa: F401
820
+ AutomaticSpeechRecognitionParameters, # noqa: F401
821
+ ChatCompletionInput, # noqa: F401
822
+ ChatCompletionInputFunctionDefinition, # noqa: F401
823
+ ChatCompletionInputFunctionName, # noqa: F401
824
+ ChatCompletionInputGrammarType, # noqa: F401
825
+ ChatCompletionInputMessage, # noqa: F401
826
+ ChatCompletionInputMessageChunk, # noqa: F401
827
+ ChatCompletionInputStreamOptions, # noqa: F401
828
+ ChatCompletionInputToolType, # noqa: F401
829
+ ChatCompletionInputURL, # noqa: F401
830
+ ChatCompletionOutput, # noqa: F401
831
+ ChatCompletionOutputComplete, # noqa: F401
832
+ ChatCompletionOutputFunctionDefinition, # noqa: F401
833
+ ChatCompletionOutputLogprob, # noqa: F401
834
+ ChatCompletionOutputLogprobs, # noqa: F401
835
+ ChatCompletionOutputMessage, # noqa: F401
836
+ ChatCompletionOutputToolCall, # noqa: F401
837
+ ChatCompletionOutputTopLogprob, # noqa: F401
838
+ ChatCompletionOutputUsage, # noqa: F401
839
+ ChatCompletionStreamOutput, # noqa: F401
840
+ ChatCompletionStreamOutputChoice, # noqa: F401
841
+ ChatCompletionStreamOutputDelta, # noqa: F401
842
+ ChatCompletionStreamOutputDeltaToolCall, # noqa: F401
843
+ ChatCompletionStreamOutputFunction, # noqa: F401
844
+ ChatCompletionStreamOutputLogprob, # noqa: F401
845
+ ChatCompletionStreamOutputLogprobs, # noqa: F401
846
+ ChatCompletionStreamOutputTopLogprob, # noqa: F401
847
+ ChatCompletionStreamOutputUsage, # noqa: F401
848
+ DepthEstimationInput, # noqa: F401
849
+ DepthEstimationOutput, # noqa: F401
850
+ DocumentQuestionAnsweringInput, # noqa: F401
851
+ DocumentQuestionAnsweringInputData, # noqa: F401
852
+ DocumentQuestionAnsweringOutputElement, # noqa: F401
853
+ DocumentQuestionAnsweringParameters, # noqa: F401
854
+ FeatureExtractionInput, # noqa: F401
855
+ FillMaskInput, # noqa: F401
856
+ FillMaskOutputElement, # noqa: F401
857
+ FillMaskParameters, # noqa: F401
858
+ ImageClassificationInput, # noqa: F401
859
+ ImageClassificationOutputElement, # noqa: F401
860
+ ImageClassificationOutputTransform, # noqa: F401
861
+ ImageClassificationParameters, # noqa: F401
862
+ ImageSegmentationInput, # noqa: F401
863
+ ImageSegmentationOutputElement, # noqa: F401
864
+ ImageSegmentationParameters, # noqa: F401
865
+ ImageToImageInput, # noqa: F401
866
+ ImageToImageOutput, # noqa: F401
867
+ ImageToImageParameters, # noqa: F401
868
+ ImageToImageTargetSize, # noqa: F401
869
+ ImageToTextEarlyStoppingEnum, # noqa: F401
870
+ ImageToTextGenerationParameters, # noqa: F401
871
+ ImageToTextInput, # noqa: F401
872
+ ImageToTextOutput, # noqa: F401
873
+ ImageToTextParameters, # noqa: F401
874
+ ObjectDetectionBoundingBox, # noqa: F401
875
+ ObjectDetectionInput, # noqa: F401
876
+ ObjectDetectionOutputElement, # noqa: F401
877
+ ObjectDetectionParameters, # noqa: F401
878
+ QuestionAnsweringInput, # noqa: F401
879
+ QuestionAnsweringInputData, # noqa: F401
880
+ QuestionAnsweringOutputElement, # noqa: F401
881
+ QuestionAnsweringParameters, # noqa: F401
882
+ SentenceSimilarityInput, # noqa: F401
883
+ SentenceSimilarityInputData, # noqa: F401
884
+ SummarizationInput, # noqa: F401
885
+ SummarizationOutput, # noqa: F401
886
+ SummarizationParameters, # noqa: F401
887
+ TableQuestionAnsweringInput, # noqa: F401
888
+ TableQuestionAnsweringInputData, # noqa: F401
889
+ TableQuestionAnsweringOutputElement, # noqa: F401
890
+ Text2TextGenerationInput, # noqa: F401
891
+ Text2TextGenerationOutput, # noqa: F401
892
+ Text2TextGenerationParameters, # noqa: F401
893
+ TextClassificationInput, # noqa: F401
894
+ TextClassificationOutputElement, # noqa: F401
895
+ TextClassificationOutputTransform, # noqa: F401
896
+ TextClassificationParameters, # noqa: F401
897
+ TextGenerationInput, # noqa: F401
898
+ TextGenerationInputGenerateParameters, # noqa: F401
899
+ TextGenerationInputGrammarType, # noqa: F401
900
+ TextGenerationOutput, # noqa: F401
901
+ TextGenerationOutputBestOfSequence, # noqa: F401
902
+ TextGenerationOutputDetails, # noqa: F401
903
+ TextGenerationOutputPrefillToken, # noqa: F401
904
+ TextGenerationOutputToken, # noqa: F401
905
+ TextGenerationStreamOutput, # noqa: F401
906
+ TextGenerationStreamOutputStreamDetails, # noqa: F401
907
+ TextGenerationStreamOutputToken, # noqa: F401
908
+ TextToAudioEarlyStoppingEnum, # noqa: F401
909
+ TextToAudioGenerationParameters, # noqa: F401
910
+ TextToAudioInput, # noqa: F401
911
+ TextToAudioOutput, # noqa: F401
912
+ TextToAudioParameters, # noqa: F401
913
+ TextToImageInput, # noqa: F401
914
+ TextToImageOutput, # noqa: F401
915
+ TextToImageParameters, # noqa: F401
916
+ TextToImageTargetSize, # noqa: F401
917
+ TextToSpeechEarlyStoppingEnum, # noqa: F401
918
+ TextToSpeechGenerationParameters, # noqa: F401
919
+ TextToSpeechInput, # noqa: F401
920
+ TextToSpeechOutput, # noqa: F401
921
+ TextToSpeechParameters, # noqa: F401
922
+ TokenClassificationInput, # noqa: F401
923
+ TokenClassificationOutputElement, # noqa: F401
924
+ TokenClassificationParameters, # noqa: F401
925
+ ToolElement, # noqa: F401
926
+ TranslationInput, # noqa: F401
927
+ TranslationOutput, # noqa: F401
928
+ TranslationParameters, # noqa: F401
929
+ VideoClassificationInput, # noqa: F401
930
+ VideoClassificationOutputElement, # noqa: F401
931
+ VideoClassificationOutputTransform, # noqa: F401
932
+ VideoClassificationParameters, # noqa: F401
933
+ VisualQuestionAnsweringInput, # noqa: F401
934
+ VisualQuestionAnsweringInputData, # noqa: F401
935
+ VisualQuestionAnsweringOutputElement, # noqa: F401
936
+ VisualQuestionAnsweringParameters, # noqa: F401
937
+ ZeroShotClassificationInput, # noqa: F401
938
+ ZeroShotClassificationInputData, # noqa: F401
939
+ ZeroShotClassificationOutputElement, # noqa: F401
940
+ ZeroShotClassificationParameters, # noqa: F401
941
+ ZeroShotImageClassificationInput, # noqa: F401
942
+ ZeroShotImageClassificationInputData, # noqa: F401
943
+ ZeroShotImageClassificationOutputElement, # noqa: F401
944
+ ZeroShotImageClassificationParameters, # noqa: F401
945
+ ZeroShotObjectDetectionBoundingBox, # noqa: F401
946
+ ZeroShotObjectDetectionInput, # noqa: F401
947
+ ZeroShotObjectDetectionInputData, # noqa: F401
948
+ ZeroShotObjectDetectionOutputElement, # noqa: F401
949
+ )
950
+ from .inference_api import InferenceApi # noqa: F401
951
+ from .keras_mixin import (
952
+ KerasModelHubMixin, # noqa: F401
953
+ from_pretrained_keras, # noqa: F401
954
+ push_to_hub_keras, # noqa: F401
955
+ save_pretrained_keras, # noqa: F401
956
+ )
957
+ from .repocard import (
958
+ DatasetCard, # noqa: F401
959
+ ModelCard, # noqa: F401
960
+ RepoCard, # noqa: F401
961
+ SpaceCard, # noqa: F401
962
+ metadata_eval_result, # noqa: F401
963
+ metadata_load, # noqa: F401
964
+ metadata_save, # noqa: F401
965
+ metadata_update, # noqa: F401
966
+ )
967
+ from .repocard_data import (
968
+ CardData, # noqa: F401
969
+ DatasetCardData, # noqa: F401
970
+ EvalResult, # noqa: F401
971
+ ModelCardData, # noqa: F401
972
+ SpaceCardData, # noqa: F401
973
+ )
974
+ from .repository import Repository # noqa: F401
975
+ from .serialization import (
976
+ StateDictSplit, # noqa: F401
977
+ get_tf_storage_size, # noqa: F401
978
+ get_torch_storage_id, # noqa: F401
979
+ get_torch_storage_size, # noqa: F401
980
+ save_torch_model, # noqa: F401
981
+ save_torch_state_dict, # noqa: F401
982
+ split_state_dict_into_shards_factory, # noqa: F401
983
+ split_tf_state_dict_into_shards, # noqa: F401
984
+ split_torch_state_dict_into_shards, # noqa: F401
985
+ )
986
+ from .utils import (
987
+ CachedFileInfo, # noqa: F401
988
+ CachedRepoInfo, # noqa: F401
989
+ CachedRevisionInfo, # noqa: F401
990
+ CacheNotFound, # noqa: F401
991
+ CorruptedCacheException, # noqa: F401
992
+ DeleteCacheStrategy, # noqa: F401
993
+ HFCacheInfo, # noqa: F401
994
+ HfFolder, # noqa: F401
995
+ cached_assets_path, # noqa: F401
996
+ configure_http_backend, # noqa: F401
997
+ dump_environment_info, # noqa: F401
998
+ get_session, # noqa: F401
999
+ get_token, # noqa: F401
1000
+ logging, # noqa: F401
1001
+ scan_cache_dir, # noqa: F401
1002
+ )
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_commit_scheduler.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import logging
3
+ import os
4
+ import time
5
+ from concurrent.futures import Future
6
+ from dataclasses import dataclass
7
+ from io import SEEK_END, SEEK_SET, BytesIO
8
+ from pathlib import Path
9
+ from threading import Lock, Thread
10
+ from typing import Dict, List, Optional, Union
11
+
12
+ from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApi
13
+ from .utils import filter_repo_objects
14
+
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class _FileToUpload:
21
+ """Temporary dataclass to store info about files to upload. Not meant to be used directly."""
22
+
23
+ local_path: Path
24
+ path_in_repo: str
25
+ size_limit: int
26
+ last_modified: float
27
+
28
+
29
+ class CommitScheduler:
30
+ """
31
+ Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
32
+
33
+ The scheduler is started when instantiated and run indefinitely. At the end of your script, a last commit is
34
+ triggered. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
35
+ to learn more about how to use it.
36
+
37
+ Args:
38
+ repo_id (`str`):
39
+ The id of the repo to commit to.
40
+ folder_path (`str` or `Path`):
41
+ Path to the local folder to upload regularly.
42
+ every (`int` or `float`, *optional*):
43
+ The number of minutes between each commit. Defaults to 5 minutes.
44
+ path_in_repo (`str`, *optional*):
45
+ Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
46
+ of the repository.
47
+ repo_type (`str`, *optional*):
48
+ The type of the repo to commit to. Defaults to `model`.
49
+ revision (`str`, *optional*):
50
+ The revision of the repo to commit to. Defaults to `main`.
51
+ private (`bool`, *optional*):
52
+ Whether to make the repo private. Defaults to `False`. This value is ignored if the repo already exist.
53
+ token (`str`, *optional*):
54
+ The token to use to commit to the repo. Defaults to the token saved on the machine.
55
+ allow_patterns (`List[str]` or `str`, *optional*):
56
+ If provided, only files matching at least one pattern are uploaded.
57
+ ignore_patterns (`List[str]` or `str`, *optional*):
58
+ If provided, files matching any of the patterns are not uploaded.
59
+ squash_history (`bool`, *optional*):
60
+ Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
61
+ useful to avoid degraded performances on the repo when it grows too large.
62
+ hf_api (`HfApi`, *optional*):
63
+ The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
64
+
65
+ Example:
66
+ ```py
67
+ >>> from pathlib import Path
68
+ >>> from huggingface_hub import CommitScheduler
69
+
70
+ # Scheduler uploads every 10 minutes
71
+ >>> csv_path = Path("watched_folder/data.csv")
72
+ >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
73
+
74
+ >>> with csv_path.open("a") as f:
75
+ ... f.write("first line")
76
+
77
+ # Some time later (...)
78
+ >>> with csv_path.open("a") as f:
79
+ ... f.write("second line")
80
+ ```
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ *,
86
+ repo_id: str,
87
+ folder_path: Union[str, Path],
88
+ every: Union[int, float] = 5,
89
+ path_in_repo: Optional[str] = None,
90
+ repo_type: Optional[str] = None,
91
+ revision: Optional[str] = None,
92
+ private: bool = False,
93
+ token: Optional[str] = None,
94
+ allow_patterns: Optional[Union[List[str], str]] = None,
95
+ ignore_patterns: Optional[Union[List[str], str]] = None,
96
+ squash_history: bool = False,
97
+ hf_api: Optional["HfApi"] = None,
98
+ ) -> None:
99
+ self.api = hf_api or HfApi(token=token)
100
+
101
+ # Folder
102
+ self.folder_path = Path(folder_path).expanduser().resolve()
103
+ self.path_in_repo = path_in_repo or ""
104
+ self.allow_patterns = allow_patterns
105
+
106
+ if ignore_patterns is None:
107
+ ignore_patterns = []
108
+ elif isinstance(ignore_patterns, str):
109
+ ignore_patterns = [ignore_patterns]
110
+ self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
111
+
112
+ if self.folder_path.is_file():
113
+ raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.")
114
+ self.folder_path.mkdir(parents=True, exist_ok=True)
115
+
116
+ # Repository
117
+ repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True)
118
+ self.repo_id = repo_url.repo_id
119
+ self.repo_type = repo_type
120
+ self.revision = revision
121
+ self.token = token
122
+
123
+ # Keep track of already uploaded files
124
+ self.last_uploaded: Dict[Path, float] = {} # key is local path, value is timestamp
125
+
126
+ # Scheduler
127
+ if not every > 0:
128
+ raise ValueError(f"'every' must be a positive integer, not '{every}'.")
129
+ self.lock = Lock()
130
+ self.every = every
131
+ self.squash_history = squash_history
132
+
133
+ logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.")
134
+ self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
135
+ self._scheduler_thread.start()
136
+ atexit.register(self._push_to_hub)
137
+
138
+ self.__stopped = False
139
+
140
+ def stop(self) -> None:
141
+ """Stop the scheduler.
142
+
143
+ A stopped scheduler cannot be restarted. Mostly for tests purposes.
144
+ """
145
+ self.__stopped = True
146
+
147
+ def _run_scheduler(self) -> None:
148
+ """Dumb thread waiting between each scheduled push to Hub."""
149
+ while True:
150
+ self.last_future = self.trigger()
151
+ time.sleep(self.every * 60)
152
+ if self.__stopped:
153
+ break
154
+
155
+ def trigger(self) -> Future:
156
+ """Trigger a `push_to_hub` and return a future.
157
+
158
+ This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
159
+ immediately, without waiting for the next scheduled commit.
160
+ """
161
+ return self.api.run_as_future(self._push_to_hub)
162
+
163
+ def _push_to_hub(self) -> Optional[CommitInfo]:
164
+ if self.__stopped: # If stopped, already scheduled commits are ignored
165
+ return None
166
+
167
+ logger.info("(Background) scheduled commit triggered.")
168
+ try:
169
+ value = self.push_to_hub()
170
+ if self.squash_history:
171
+ logger.info("(Background) squashing repo history.")
172
+ self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision)
173
+ return value
174
+ except Exception as e:
175
+ logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced
176
+ raise
177
+
178
+ def push_to_hub(self) -> Optional[CommitInfo]:
179
+ """
180
+ Push folder to the Hub and return the commit info.
181
+
182
+ <Tip warning={true}>
183
+
184
+ This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
185
+ queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
186
+ issues.
187
+
188
+ </Tip>
189
+
190
+ The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
191
+ uploads only changed files. If no changes are found, the method returns without committing anything. If you want
192
+ to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
193
+ for example to compress data together in a single file before committing. For more details and examples, check
194
+ out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
195
+ """
196
+ # Check files to upload (with lock)
197
+ with self.lock:
198
+ logger.debug("Listing files to upload for scheduled commit.")
199
+
200
+ # List files from folder (taken from `_prepare_upload_folder_additions`)
201
+ relpath_to_abspath = {
202
+ path.relative_to(self.folder_path).as_posix(): path
203
+ for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic
204
+ if path.is_file()
205
+ }
206
+ prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
207
+
208
+ # Filter with pattern + filter out unchanged files + retrieve current file size
209
+ files_to_upload: List[_FileToUpload] = []
210
+ for relpath in filter_repo_objects(
211
+ relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns
212
+ ):
213
+ local_path = relpath_to_abspath[relpath]
214
+ stat = local_path.stat()
215
+ if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime:
216
+ files_to_upload.append(
217
+ _FileToUpload(
218
+ local_path=local_path,
219
+ path_in_repo=prefix + relpath,
220
+ size_limit=stat.st_size,
221
+ last_modified=stat.st_mtime,
222
+ )
223
+ )
224
+
225
+ # Return if nothing to upload
226
+ if len(files_to_upload) == 0:
227
+ logger.debug("Dropping schedule commit: no changed file to upload.")
228
+ return None
229
+
230
+ # Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
231
+ logger.debug("Removing unchanged files since previous scheduled commit.")
232
+ add_operations = [
233
+ CommitOperationAdd(
234
+ # Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
235
+ path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit),
236
+ path_in_repo=file_to_upload.path_in_repo,
237
+ )
238
+ for file_to_upload in files_to_upload
239
+ ]
240
+
241
+ # Upload files (append mode expected - no need for lock)
242
+ logger.debug("Uploading files for scheduled commit.")
243
+ commit_info = self.api.create_commit(
244
+ repo_id=self.repo_id,
245
+ repo_type=self.repo_type,
246
+ operations=add_operations,
247
+ commit_message="Scheduled Commit",
248
+ revision=self.revision,
249
+ )
250
+
251
+ # Successful commit: keep track of the latest "last_modified" for each file
252
+ for file in files_to_upload:
253
+ self.last_uploaded[file.local_path] = file.last_modified
254
+ return commit_info
255
+
256
+
257
+ class PartialFileIO(BytesIO):
258
+ """A file-like object that reads only the first part of a file.
259
+
260
+ Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
261
+ file is uploaded (i.e. the part that was available when the filesystem was first scanned).
262
+
263
+ In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
264
+ disturbance for the user. The object is passed to `CommitOperationAdd`.
265
+
266
+ Only supports `read`, `tell` and `seek` methods.
267
+
268
+ Args:
269
+ file_path (`str` or `Path`):
270
+ Path to the file to read.
271
+ size_limit (`int`):
272
+ The maximum number of bytes to read from the file. If the file is larger than this, only the first part
273
+ will be read (and uploaded).
274
+ """
275
+
276
+ def __init__(self, file_path: Union[str, Path], size_limit: int) -> None:
277
+ self._file_path = Path(file_path)
278
+ self._file = self._file_path.open("rb")
279
+ self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
280
+
281
+ def __del__(self) -> None:
282
+ self._file.close()
283
+ return super().__del__()
284
+
285
+ def __repr__(self) -> str:
286
+ return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
287
+
288
+ def __len__(self) -> int:
289
+ return self._size_limit
290
+
291
+ def __getattribute__(self, name: str):
292
+ if name.startswith("_") or name in ("read", "tell", "seek"): # only 3 public methods supported
293
+ return super().__getattribute__(name)
294
+ raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
295
+
296
+ def tell(self) -> int:
297
+ """Return the current file position."""
298
+ return self._file.tell()
299
+
300
+ def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
301
+ """Change the stream position to the given offset.
302
+
303
+ Behavior is the same as a regular file, except that the position is capped to the size limit.
304
+ """
305
+ if __whence == SEEK_END:
306
+ # SEEK_END => set from the truncated end
307
+ __offset = len(self) + __offset
308
+ __whence = SEEK_SET
309
+
310
+ pos = self._file.seek(__offset, __whence)
311
+ if pos > self._size_limit:
312
+ return self._file.seek(self._size_limit)
313
+ return pos
314
+
315
+ def read(self, __size: Optional[int] = -1) -> bytes:
316
+ """Read at most `__size` bytes from the file.
317
+
318
+ Behavior is the same as a regular file, except that it is capped to the size limit.
319
+ """
320
+ current = self._file.tell()
321
+ if __size is None or __size < 0:
322
+ # Read until file limit
323
+ truncated_size = self._size_limit - current
324
+ else:
325
+ # Read until file limit or __size
326
+ truncated_size = min(__size, self._size_limit - current)
327
+ return self._file.read(truncated_size)
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_inference_endpoints.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from dataclasses import dataclass, field
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ from typing import TYPE_CHECKING, Dict, Optional, Union
6
+
7
+ from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError
8
+
9
+ from .inference._client import InferenceClient
10
+ from .inference._generated._async_client import AsyncInferenceClient
11
+ from .utils import get_session, logging, parse_datetime
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from .hf_api import HfApi
16
+
17
+
18
+ logger = logging.get_logger(__name__)
19
+
20
+
21
+ class InferenceEndpointStatus(str, Enum):
22
+ PENDING = "pending"
23
+ INITIALIZING = "initializing"
24
+ UPDATING = "updating"
25
+ UPDATE_FAILED = "updateFailed"
26
+ RUNNING = "running"
27
+ PAUSED = "paused"
28
+ FAILED = "failed"
29
+ SCALED_TO_ZERO = "scaledToZero"
30
+
31
+
32
+ class InferenceEndpointType(str, Enum):
33
+ PUBlIC = "public"
34
+ PROTECTED = "protected"
35
+ PRIVATE = "private"
36
+
37
+
38
+ @dataclass
39
+ class InferenceEndpoint:
40
+ """
41
+ Contains information about a deployed Inference Endpoint.
42
+
43
+ Args:
44
+ name (`str`):
45
+ The unique name of the Inference Endpoint.
46
+ namespace (`str`):
47
+ The namespace where the Inference Endpoint is located.
48
+ repository (`str`):
49
+ The name of the model repository deployed on this Inference Endpoint.
50
+ status ([`InferenceEndpointStatus`]):
51
+ The current status of the Inference Endpoint.
52
+ url (`str`, *optional*):
53
+ The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
54
+ framework (`str`):
55
+ The machine learning framework used for the model.
56
+ revision (`str`):
57
+ The specific model revision deployed on the Inference Endpoint.
58
+ task (`str`):
59
+ The task associated with the deployed model.
60
+ created_at (`datetime.datetime`):
61
+ The timestamp when the Inference Endpoint was created.
62
+ updated_at (`datetime.datetime`):
63
+ The timestamp of the last update of the Inference Endpoint.
64
+ type ([`InferenceEndpointType`]):
65
+ The type of the Inference Endpoint (public, protected, private).
66
+ raw (`Dict`):
67
+ The raw dictionary data returned from the API.
68
+ token (`str` or `bool`, *optional*):
69
+ Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
70
+ locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
71
+
72
+ Example:
73
+ ```python
74
+ >>> from huggingface_hub import get_inference_endpoint
75
+ >>> endpoint = get_inference_endpoint("my-text-to-image")
76
+ >>> endpoint
77
+ InferenceEndpoint(name='my-text-to-image', ...)
78
+
79
+ # Get status
80
+ >>> endpoint.status
81
+ 'running'
82
+ >>> endpoint.url
83
+ 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
84
+
85
+ # Run inference
86
+ >>> endpoint.client.text_to_image(...)
87
+
88
+ # Pause endpoint to save $$$
89
+ >>> endpoint.pause()
90
+
91
+ # ...
92
+ # Resume and wait for deployment
93
+ >>> endpoint.resume()
94
+ >>> endpoint.wait()
95
+ >>> endpoint.client.text_to_image(...)
96
+ ```
97
+ """
98
+
99
+ # Field in __repr__
100
+ name: str = field(init=False)
101
+ namespace: str
102
+ repository: str = field(init=False)
103
+ status: InferenceEndpointStatus = field(init=False)
104
+ url: Optional[str] = field(init=False)
105
+
106
+ # Other fields
107
+ framework: str = field(repr=False, init=False)
108
+ revision: str = field(repr=False, init=False)
109
+ task: str = field(repr=False, init=False)
110
+ created_at: datetime = field(repr=False, init=False)
111
+ updated_at: datetime = field(repr=False, init=False)
112
+ type: InferenceEndpointType = field(repr=False, init=False)
113
+
114
+ # Raw dict from the API
115
+ raw: Dict = field(repr=False)
116
+
117
+ # Internal fields
118
+ _token: Union[str, bool, None] = field(repr=False, compare=False)
119
+ _api: "HfApi" = field(repr=False, compare=False)
120
+
121
+ @classmethod
122
+ def from_raw(
123
+ cls, raw: Dict, namespace: str, token: Union[str, bool, None] = None, api: Optional["HfApi"] = None
124
+ ) -> "InferenceEndpoint":
125
+ """Initialize object from raw dictionary."""
126
+ if api is None:
127
+ from .hf_api import HfApi
128
+
129
+ api = HfApi()
130
+ if token is None:
131
+ token = api.token
132
+
133
+ # All other fields are populated in __post_init__
134
+ return cls(raw=raw, namespace=namespace, _token=token, _api=api)
135
+
136
+ def __post_init__(self) -> None:
137
+ """Populate fields from raw dictionary."""
138
+ self._populate_from_raw()
139
+
140
+ @property
141
+ def client(self) -> InferenceClient:
142
+ """Returns a client to make predictions on this Inference Endpoint.
143
+
144
+ Returns:
145
+ [`InferenceClient`]: an inference client pointing to the deployed endpoint.
146
+
147
+ Raises:
148
+ [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
149
+ """
150
+ if self.url is None:
151
+ raise InferenceEndpointError(
152
+ "Cannot create a client for this Inference Endpoint as it is not yet deployed. "
153
+ "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
154
+ )
155
+ return InferenceClient(model=self.url, token=self._token)
156
+
157
+ @property
158
+ def async_client(self) -> AsyncInferenceClient:
159
+ """Returns a client to make predictions on this Inference Endpoint.
160
+
161
+ Returns:
162
+ [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
163
+
164
+ Raises:
165
+ [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
166
+ """
167
+ if self.url is None:
168
+ raise InferenceEndpointError(
169
+ "Cannot create a client for this Inference Endpoint as it is not yet deployed. "
170
+ "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
171
+ )
172
+ return AsyncInferenceClient(model=self.url, token=self._token)
173
+
174
+ def wait(self, timeout: Optional[int] = None, refresh_every: int = 5) -> "InferenceEndpoint":
175
+ """Wait for the Inference Endpoint to be deployed.
176
+
177
+ Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
178
+ seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
179
+ data.
180
+
181
+ Args:
182
+ timeout (`int`, *optional*):
183
+ The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
184
+ indefinitely.
185
+ refresh_every (`int`, *optional*):
186
+ The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
187
+
188
+ Returns:
189
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
190
+
191
+ Raises:
192
+ [`InferenceEndpointError`]
193
+ If the Inference Endpoint ended up in a failed state.
194
+ [`InferenceEndpointTimeoutError`]
195
+ If the Inference Endpoint is not deployed after `timeout` seconds.
196
+ """
197
+ if timeout is not None and timeout < 0:
198
+ raise ValueError("`timeout` cannot be negative.")
199
+ if refresh_every <= 0:
200
+ raise ValueError("`refresh_every` must be positive.")
201
+
202
+ start = time.time()
203
+ while True:
204
+ if self.url is not None:
205
+ # Means the URL is provisioned => check if the endpoint is reachable
206
+ response = get_session().get(self.url, headers=self._api._build_hf_headers(token=self._token))
207
+ if response.status_code == 200:
208
+ logger.info("Inference Endpoint is ready to be used.")
209
+ return self
210
+ if self.status == InferenceEndpointStatus.FAILED:
211
+ raise InferenceEndpointError(
212
+ f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information."
213
+ )
214
+ if timeout is not None:
215
+ if time.time() - start > timeout:
216
+ raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.")
217
+ logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...")
218
+ time.sleep(refresh_every)
219
+ self.fetch()
220
+
221
+ def fetch(self) -> "InferenceEndpoint":
222
+ """Fetch latest information about the Inference Endpoint.
223
+
224
+ Returns:
225
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
226
+ """
227
+ obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
228
+ self.raw = obj.raw
229
+ self._populate_from_raw()
230
+ return self
231
+
232
+ def update(
233
+ self,
234
+ *,
235
+ # Compute update
236
+ accelerator: Optional[str] = None,
237
+ instance_size: Optional[str] = None,
238
+ instance_type: Optional[str] = None,
239
+ min_replica: Optional[int] = None,
240
+ max_replica: Optional[int] = None,
241
+ scale_to_zero_timeout: Optional[int] = None,
242
+ # Model update
243
+ repository: Optional[str] = None,
244
+ framework: Optional[str] = None,
245
+ revision: Optional[str] = None,
246
+ task: Optional[str] = None,
247
+ custom_image: Optional[Dict] = None,
248
+ secrets: Optional[Dict[str, str]] = None,
249
+ ) -> "InferenceEndpoint":
250
+ """Update the Inference Endpoint.
251
+
252
+ This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
253
+ optional but at least one must be provided.
254
+
255
+ This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
256
+ latest data from the server.
257
+
258
+ Args:
259
+ accelerator (`str`, *optional*):
260
+ The hardware accelerator to be used for inference (e.g. `"cpu"`).
261
+ instance_size (`str`, *optional*):
262
+ The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
263
+ instance_type (`str`, *optional*):
264
+ The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
265
+ min_replica (`int`, *optional*):
266
+ The minimum number of replicas (instances) to keep running for the Inference Endpoint.
267
+ max_replica (`int`, *optional*):
268
+ The maximum number of replicas (instances) to scale to for the Inference Endpoint.
269
+ scale_to_zero_timeout (`int`, *optional*):
270
+ The duration in minutes before an inactive endpoint is scaled to zero.
271
+
272
+ repository (`str`, *optional*):
273
+ The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
274
+ framework (`str`, *optional*):
275
+ The machine learning framework used for the model (e.g. `"custom"`).
276
+ revision (`str`, *optional*):
277
+ The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
278
+ task (`str`, *optional*):
279
+ The task on which to deploy the model (e.g. `"text-classification"`).
280
+ custom_image (`Dict`, *optional*):
281
+ A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
282
+ Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
283
+ secrets (`Dict[str, str]`, *optional*):
284
+ Secret values to inject in the container environment.
285
+ Returns:
286
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
287
+ """
288
+ # Make API call
289
+ obj = self._api.update_inference_endpoint(
290
+ name=self.name,
291
+ namespace=self.namespace,
292
+ accelerator=accelerator,
293
+ instance_size=instance_size,
294
+ instance_type=instance_type,
295
+ min_replica=min_replica,
296
+ max_replica=max_replica,
297
+ scale_to_zero_timeout=scale_to_zero_timeout,
298
+ repository=repository,
299
+ framework=framework,
300
+ revision=revision,
301
+ task=task,
302
+ custom_image=custom_image,
303
+ secrets=secrets,
304
+ token=self._token, # type: ignore [arg-type]
305
+ )
306
+
307
+ # Mutate current object
308
+ self.raw = obj.raw
309
+ self._populate_from_raw()
310
+ return self
311
+
312
+ def pause(self) -> "InferenceEndpoint":
313
+ """Pause the Inference Endpoint.
314
+
315
+ A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
316
+ This is different than scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
317
+ would be automatically restarted when a request is made to it.
318
+
319
+ This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
320
+ latest data from the server.
321
+
322
+ Returns:
323
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
324
+ """
325
+ obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
326
+ self.raw = obj.raw
327
+ self._populate_from_raw()
328
+ return self
329
+
330
+ def resume(self, running_ok: bool = True) -> "InferenceEndpoint":
331
+ """Resume the Inference Endpoint.
332
+
333
+ This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
334
+ latest data from the server.
335
+
336
+ Args:
337
+ running_ok (`bool`, *optional*):
338
+ If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
339
+ `True`.
340
+
341
+ Returns:
342
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
343
+ """
344
+ obj = self._api.resume_inference_endpoint(
345
+ name=self.name, namespace=self.namespace, running_ok=running_ok, token=self._token
346
+ ) # type: ignore [arg-type]
347
+ self.raw = obj.raw
348
+ self._populate_from_raw()
349
+ return self
350
+
351
+ def scale_to_zero(self) -> "InferenceEndpoint":
352
+ """Scale Inference Endpoint to zero.
353
+
354
+ An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a
355
+ cold start delay. This is different than pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
356
+ would require a manual resume with [`InferenceEndpoint.resume`].
357
+
358
+ This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
359
+ latest data from the server.
360
+
361
+ Returns:
362
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
363
+ """
364
+ obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
365
+ self.raw = obj.raw
366
+ self._populate_from_raw()
367
+ return self
368
+
369
+ def delete(self) -> None:
370
+ """Delete the Inference Endpoint.
371
+
372
+ This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
373
+ to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
374
+
375
+ This is an alias for [`HfApi.delete_inference_endpoint`].
376
+ """
377
+ self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
378
+
379
+ def _populate_from_raw(self) -> None:
380
+ """Populate fields from raw dictionary.
381
+
382
+ Called in __post_init__ + each time the Inference Endpoint is updated.
383
+ """
384
+ # Repr fields
385
+ self.name = self.raw["name"]
386
+ self.repository = self.raw["model"]["repository"]
387
+ self.status = self.raw["status"]["state"]
388
+ self.url = self.raw["status"].get("url")
389
+
390
+ # Other fields
391
+ self.framework = self.raw["model"]["framework"]
392
+ self.revision = self.raw["model"]["revision"]
393
+ self.task = self.raw["model"]["task"]
394
+ self.created_at = parse_datetime(self.raw["status"]["createdAt"])
395
+ self.updated_at = parse_datetime(self.raw["status"]["updatedAt"])
396
+ self.type = self.raw["type"]
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_local_folder.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle the `../.cache/huggingface` folder in local directories.
16
+
17
+ First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to store
18
+ download metadata when downloading files from the hub to a local directory (without
19
+ using the cache).
20
+
21
+ ./.cache/huggingface folder structure:
22
+ [4.0K] data
23
+ ├── [4.0K] .cache
24
+ │ └── [4.0K] huggingface
25
+ │ └── [4.0K] download
26
+ │ ├── [ 16] file.parquet.metadata
27
+ │ ├── [ 16] file.txt.metadata
28
+ │ └── [4.0K] folder
29
+ │ └── [ 16] file.parquet.metadata
30
+
31
+ ├── [6.5G] file.parquet
32
+ ├── [1.5K] file.txt
33
+ └── [4.0K] folder
34
+ └── [ 16] file.parquet
35
+
36
+
37
+ Download metadata file structure:
38
+ ```
39
+ # file.txt.metadata
40
+ 11c5a3d5811f50298f278a704980280950aedb10
41
+ a16a55fda99d2f2e7b69cce5cf93ff4ad3049930
42
+ 1712656091.123
43
+
44
+ # file.parquet.metadata
45
+ 11c5a3d5811f50298f278a704980280950aedb10
46
+ 7c5d3f4b8b76583b422fcb9189ad6c89d5d97a094541ce8932dce3ecabde1421
47
+ 1712656091.123
48
+ }
49
+ ```
50
+ """
51
+
52
+ import logging
53
+ import os
54
+ import time
55
+ from dataclasses import dataclass
56
+ from functools import lru_cache
57
+ from pathlib import Path
58
+ from typing import Optional
59
+
60
+ from .utils import WeakFileLock
61
+
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+
66
+ @dataclass
67
+ class LocalDownloadFilePaths:
68
+ """
69
+ Paths to the files related to a download process in a local dir.
70
+
71
+ Returned by [`get_local_download_paths`].
72
+
73
+ Attributes:
74
+ file_path (`Path`):
75
+ Path where the file will be saved.
76
+ lock_path (`Path`):
77
+ Path to the lock file used to ensure atomicity when reading/writing metadata.
78
+ metadata_path (`Path`):
79
+ Path to the metadata file.
80
+ """
81
+
82
+ file_path: Path
83
+ lock_path: Path
84
+ metadata_path: Path
85
+
86
+ def incomplete_path(self, etag: str) -> Path:
87
+ """Return the path where a file will be temporarily downloaded before being moved to `file_path`."""
88
+ return self.metadata_path.with_suffix(f".{etag}.incomplete")
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class LocalUploadFilePaths:
93
+ """
94
+ Paths to the files related to an upload process in a local dir.
95
+
96
+ Returned by [`get_local_upload_paths`].
97
+
98
+ Attributes:
99
+ path_in_repo (`str`):
100
+ Path of the file in the repo.
101
+ file_path (`Path`):
102
+ Path where the file will be saved.
103
+ lock_path (`Path`):
104
+ Path to the lock file used to ensure atomicity when reading/writing metadata.
105
+ metadata_path (`Path`):
106
+ Path to the metadata file.
107
+ """
108
+
109
+ path_in_repo: str
110
+ file_path: Path
111
+ lock_path: Path
112
+ metadata_path: Path
113
+
114
+
115
+ @dataclass
116
+ class LocalDownloadFileMetadata:
117
+ """
118
+ Metadata about a file in the local directory related to a download process.
119
+
120
+ Attributes:
121
+ filename (`str`):
122
+ Path of the file in the repo.
123
+ commit_hash (`str`):
124
+ Commit hash of the file in the repo.
125
+ etag (`str`):
126
+ ETag of the file in the repo. Used to check if the file has changed.
127
+ For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash.
128
+ timestamp (`int`):
129
+ Unix timestamp of when the metadata was saved i.e. when the metadata was accurate.
130
+ """
131
+
132
+ filename: str
133
+ commit_hash: str
134
+ etag: str
135
+ timestamp: float
136
+
137
+
138
+ @dataclass
139
+ class LocalUploadFileMetadata:
140
+ """
141
+ Metadata about a file in the local directory related to an upload process.
142
+ """
143
+
144
+ size: int
145
+
146
+ # Default values correspond to "we don't know yet"
147
+ timestamp: Optional[float] = None
148
+ should_ignore: Optional[bool] = None
149
+ sha256: Optional[str] = None
150
+ upload_mode: Optional[str] = None
151
+ is_uploaded: bool = False
152
+ is_committed: bool = False
153
+
154
+ def save(self, paths: LocalUploadFilePaths) -> None:
155
+ """Save the metadata to disk."""
156
+ with WeakFileLock(paths.lock_path):
157
+ with paths.metadata_path.open("w") as f:
158
+ new_timestamp = time.time()
159
+ f.write(str(new_timestamp) + "\n")
160
+
161
+ f.write(str(self.size)) # never None
162
+ f.write("\n")
163
+
164
+ if self.should_ignore is not None:
165
+ f.write(str(int(self.should_ignore)))
166
+ f.write("\n")
167
+
168
+ if self.sha256 is not None:
169
+ f.write(self.sha256)
170
+ f.write("\n")
171
+
172
+ if self.upload_mode is not None:
173
+ f.write(self.upload_mode)
174
+ f.write("\n")
175
+
176
+ f.write(str(int(self.is_uploaded)) + "\n")
177
+ f.write(str(int(self.is_committed)) + "\n")
178
+
179
+ self.timestamp = new_timestamp
180
+
181
+
182
+ @lru_cache(maxsize=128) # ensure singleton
183
+ def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths:
184
+ """Compute paths to the files related to a download process.
185
+
186
+ Folders containing the paths are all guaranteed to exist.
187
+
188
+ Args:
189
+ local_dir (`Path`):
190
+ Path to the local directory in which files are downloaded.
191
+ filename (`str`):
192
+ Path of the file in the repo.
193
+
194
+ Return:
195
+ [`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path).
196
+ """
197
+ # filename is the path in the Hub repository (separated by '/')
198
+ # make sure to have a cross platform transcription
199
+ sanitized_filename = os.path.join(*filename.split("/"))
200
+ if os.name == "nt":
201
+ if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
202
+ raise ValueError(
203
+ f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
204
+ " owner to rename this file."
205
+ )
206
+ file_path = local_dir / sanitized_filename
207
+ metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata"
208
+ lock_path = metadata_path.with_suffix(".lock")
209
+
210
+ # Some Windows versions do not allow for paths longer than 255 characters.
211
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix
212
+ if os.name == "nt":
213
+ if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
214
+ file_path = Path("\\\\?\\" + os.path.abspath(file_path))
215
+ lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
216
+ metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
217
+
218
+ file_path.parent.mkdir(parents=True, exist_ok=True)
219
+ metadata_path.parent.mkdir(parents=True, exist_ok=True)
220
+ return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path)
221
+
222
+
223
+ @lru_cache(maxsize=128) # ensure singleton
224
+ def get_local_upload_paths(local_dir: Path, filename: str) -> LocalUploadFilePaths:
225
+ """Compute paths to the files related to an upload process.
226
+
227
+ Folders containing the paths are all guaranteed to exist.
228
+
229
+ Args:
230
+ local_dir (`Path`):
231
+ Path to the local directory that is uploaded.
232
+ filename (`str`):
233
+ Path of the file in the repo.
234
+
235
+ Return:
236
+ [`LocalUploadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path).
237
+ """
238
+ # filename is the path in the Hub repository (separated by '/')
239
+ # make sure to have a cross platform transcription
240
+ sanitized_filename = os.path.join(*filename.split("/"))
241
+ if os.name == "nt":
242
+ if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
243
+ raise ValueError(
244
+ f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
245
+ " owner to rename this file."
246
+ )
247
+ file_path = local_dir / sanitized_filename
248
+ metadata_path = _huggingface_dir(local_dir) / "upload" / f"{sanitized_filename}.metadata"
249
+ lock_path = metadata_path.with_suffix(".lock")
250
+
251
+ # Some Windows versions do not allow for paths longer than 255 characters.
252
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix
253
+ if os.name == "nt":
254
+ if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
255
+ file_path = Path("\\\\?\\" + os.path.abspath(file_path))
256
+ lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
257
+ metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
258
+
259
+ file_path.parent.mkdir(parents=True, exist_ok=True)
260
+ metadata_path.parent.mkdir(parents=True, exist_ok=True)
261
+ return LocalUploadFilePaths(
262
+ path_in_repo=filename, file_path=file_path, lock_path=lock_path, metadata_path=metadata_path
263
+ )
264
+
265
+
266
+ def read_download_metadata(local_dir: Path, filename: str) -> Optional[LocalDownloadFileMetadata]:
267
+ """Read metadata about a file in the local directory related to a download process.
268
+
269
+ Args:
270
+ local_dir (`Path`):
271
+ Path to the local directory in which files are downloaded.
272
+ filename (`str`):
273
+ Path of the file in the repo.
274
+
275
+ Return:
276
+ `[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
277
+ """
278
+ paths = get_local_download_paths(local_dir, filename)
279
+ with WeakFileLock(paths.lock_path):
280
+ if paths.metadata_path.exists():
281
+ try:
282
+ with paths.metadata_path.open() as f:
283
+ commit_hash = f.readline().strip()
284
+ etag = f.readline().strip()
285
+ timestamp = float(f.readline().strip())
286
+ metadata = LocalDownloadFileMetadata(
287
+ filename=filename,
288
+ commit_hash=commit_hash,
289
+ etag=etag,
290
+ timestamp=timestamp,
291
+ )
292
+ except Exception as e:
293
+ # remove the metadata file if it is corrupted / not the right format
294
+ logger.warning(
295
+ f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
296
+ )
297
+ try:
298
+ paths.metadata_path.unlink()
299
+ except Exception as e:
300
+ logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
301
+
302
+ try:
303
+ # check if the file exists and hasn't been modified since the metadata was saved
304
+ stat = paths.file_path.stat()
305
+ if (
306
+ stat.st_mtime - 1 <= metadata.timestamp
307
+ ): # allow 1s difference as stat.st_mtime might not be precise
308
+ return metadata
309
+ logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
310
+ except FileNotFoundError:
311
+ # file does not exist => metadata is outdated
312
+ return None
313
+ return None
314
+
315
+
316
+ def read_upload_metadata(local_dir: Path, filename: str) -> LocalUploadFileMetadata:
317
+ """Read metadata about a file in the local directory related to an upload process.
318
+
319
+ TODO: factorize logic with `read_download_metadata`.
320
+
321
+ Args:
322
+ local_dir (`Path`):
323
+ Path to the local directory in which files are downloaded.
324
+ filename (`str`):
325
+ Path of the file in the repo.
326
+
327
+ Return:
328
+ `[LocalUploadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
329
+ """
330
+ paths = get_local_upload_paths(local_dir, filename)
331
+ with WeakFileLock(paths.lock_path):
332
+ if paths.metadata_path.exists():
333
+ try:
334
+ with paths.metadata_path.open() as f:
335
+ timestamp = float(f.readline().strip())
336
+
337
+ size = int(f.readline().strip()) # never None
338
+
339
+ _should_ignore = f.readline().strip()
340
+ should_ignore = None if _should_ignore == "" else bool(int(_should_ignore))
341
+
342
+ _sha256 = f.readline().strip()
343
+ sha256 = None if _sha256 == "" else _sha256
344
+
345
+ _upload_mode = f.readline().strip()
346
+ upload_mode = None if _upload_mode == "" else _upload_mode
347
+ if upload_mode not in (None, "regular", "lfs"):
348
+ raise ValueError(f"Invalid upload mode in metadata {paths.path_in_repo}: {upload_mode}")
349
+
350
+ is_uploaded = bool(int(f.readline().strip()))
351
+ is_committed = bool(int(f.readline().strip()))
352
+
353
+ metadata = LocalUploadFileMetadata(
354
+ timestamp=timestamp,
355
+ size=size,
356
+ should_ignore=should_ignore,
357
+ sha256=sha256,
358
+ upload_mode=upload_mode,
359
+ is_uploaded=is_uploaded,
360
+ is_committed=is_committed,
361
+ )
362
+ except Exception as e:
363
+ # remove the metadata file if it is corrupted / not the right format
364
+ logger.warning(
365
+ f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
366
+ )
367
+ try:
368
+ paths.metadata_path.unlink()
369
+ except Exception as e:
370
+ logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
371
+
372
+ # TODO: can we do better?
373
+ if (
374
+ metadata.timestamp is not None
375
+ and metadata.is_uploaded # file was uploaded
376
+ and not metadata.is_committed # but not committed
377
+ and time.time() - metadata.timestamp > 20 * 3600 # and it's been more than 20 hours
378
+ ): # => we consider it as garbage-collected by S3
379
+ metadata.is_uploaded = False
380
+
381
+ # check if the file exists and hasn't been modified since the metadata was saved
382
+ try:
383
+ if metadata.timestamp is not None and paths.file_path.stat().st_mtime <= metadata.timestamp:
384
+ return metadata
385
+ logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
386
+ except FileNotFoundError:
387
+ # file does not exist => metadata is outdated
388
+ pass
389
+
390
+ # empty metadata => we don't know anything expect its size
391
+ return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
392
+
393
+
394
+ def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None:
395
+ """Write metadata about a file in the local directory related to a download process.
396
+
397
+ Args:
398
+ local_dir (`Path`):
399
+ Path to the local directory in which files are downloaded.
400
+ """
401
+ paths = get_local_download_paths(local_dir, filename)
402
+ with WeakFileLock(paths.lock_path):
403
+ with paths.metadata_path.open("w") as f:
404
+ f.write(f"{commit_hash}\n{etag}\n{time.time()}\n")
405
+
406
+
407
+ @lru_cache()
408
+ def _huggingface_dir(local_dir: Path) -> Path:
409
+ """Return the path to the `.cache/huggingface` directory in a local directory."""
410
+ # Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times
411
+ path = local_dir / ".cache" / "huggingface"
412
+ path.mkdir(exist_ok=True, parents=True)
413
+
414
+ # Create a .gitignore file in the .cache/huggingface directory if it doesn't exist
415
+ # Should be thread-safe enough like this.
416
+ gitignore = path / ".gitignore"
417
+ gitignore_lock = path / ".gitignore.lock"
418
+ if not gitignore.exists():
419
+ try:
420
+ with WeakFileLock(gitignore_lock):
421
+ gitignore.write_text("*")
422
+ gitignore_lock.unlink()
423
+ except OSError: # FileNotFoundError, PermissionError, etc.
424
+ pass
425
+ return path
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_login.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains methods to log in to the Hub."""
15
+
16
+ import os
17
+ import subprocess
18
+ from functools import partial
19
+ from getpass import getpass
20
+ from pathlib import Path
21
+ from typing import Optional
22
+
23
+ from . import constants
24
+ from .commands._cli_utils import ANSI
25
+ from .utils import (
26
+ capture_output,
27
+ get_token,
28
+ is_google_colab,
29
+ is_notebook,
30
+ list_credential_helpers,
31
+ logging,
32
+ run_subprocess,
33
+ set_git_credential,
34
+ unset_git_credential,
35
+ )
36
+ from .utils._auth import (
37
+ _get_token_by_name,
38
+ _get_token_from_environment,
39
+ _get_token_from_file,
40
+ _get_token_from_google_colab,
41
+ _save_stored_tokens,
42
+ _save_token,
43
+ get_stored_tokens,
44
+ )
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _HF_LOGO_ASCII = """
50
+ _| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|
51
+ _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
52
+ _|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|
53
+ _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
54
+ _| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|
55
+ """
56
+
57
+
58
+ def login(
59
+ token: Optional[str] = None,
60
+ add_to_git_credential: bool = False,
61
+ new_session: bool = True,
62
+ write_permission: bool = False,
63
+ ) -> None:
64
+ """Login the machine to access the Hub.
65
+
66
+ The `token` is persisted in cache and set as a git credential. Once done, the machine
67
+ is logged in and the access token will be available across all `huggingface_hub`
68
+ components. If `token` is not provided, it will be prompted to the user either with
69
+ a widget (in a notebook) or via the terminal.
70
+
71
+ To log in from outside of a script, one can also use `huggingface-cli login` which is
72
+ a cli command that wraps [`login`].
73
+
74
+ <Tip>
75
+
76
+ [`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and
77
+ extends its capabilities.
78
+
79
+ </Tip>
80
+
81
+ <Tip>
82
+
83
+ When the token is not passed, [`login`] will automatically detect if the script runs
84
+ in a notebook or not. However, this detection might not be accurate due to the
85
+ variety of notebooks that exists nowadays. If that is the case, you can always force
86
+ the UI by using [`notebook_login`] or [`interpreter_login`].
87
+
88
+ </Tip>
89
+
90
+ Args:
91
+ token (`str`, *optional*):
92
+ User access token to generate from https://huggingface.co/settings/token.
93
+ add_to_git_credential (`bool`, defaults to `False`):
94
+ If `True`, token will be set as git credential. If no git credential helper
95
+ is configured, a warning will be displayed to the user. If `token` is `None`,
96
+ the value of `add_to_git_credential` is ignored and will be prompted again
97
+ to the end user.
98
+ new_session (`bool`, defaults to `True`):
99
+ If `True`, will request a token even if one is already saved on the machine.
100
+ write_permission (`bool`, defaults to `False`):
101
+ If `True`, requires a token with write permission.
102
+ Raises:
103
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
104
+ If an organization token is passed. Only personal account tokens are valid
105
+ to log in.
106
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
107
+ If token is invalid.
108
+ [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
109
+ If running in a notebook but `ipywidgets` is not installed.
110
+ """
111
+ if token is not None:
112
+ if not add_to_git_credential:
113
+ logger.info(
114
+ "The token has not been saved to the git credentials helper. Pass "
115
+ "`add_to_git_credential=True` in this function directly or "
116
+ "`--add-to-git-credential` if using via `huggingface-cli` if "
117
+ "you want to set the git credential as well."
118
+ )
119
+ _login(token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
120
+ elif is_notebook():
121
+ notebook_login(new_session=new_session, write_permission=write_permission)
122
+ else:
123
+ interpreter_login(new_session=new_session, write_permission=write_permission)
124
+
125
+
126
+ def logout(token_name: Optional[str] = None) -> None:
127
+ """Logout the machine from the Hub.
128
+
129
+ Token is deleted from the machine and removed from git credential.
130
+
131
+ Args:
132
+ token_name (`str`, *optional*):
133
+ Name of the access token to logout from. If `None`, will logout from all saved access tokens.
134
+ Raises:
135
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
136
+ If the access token name is not found.
137
+ """
138
+ if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens
139
+ logger.warning("Not logged in!")
140
+ return
141
+ if not token_name:
142
+ # Delete all saved access tokens and token
143
+ for file_path in (constants.HF_TOKEN_PATH, constants.HF_STORED_TOKENS_PATH):
144
+ try:
145
+ Path(file_path).unlink()
146
+ except FileNotFoundError:
147
+ pass
148
+ logger.info("Successfully logged out from all access tokens.")
149
+ else:
150
+ _logout_from_token(token_name)
151
+ logger.info(f"Successfully logged out from access token: {token_name}.")
152
+
153
+ unset_git_credential()
154
+
155
+ # Check if still logged in
156
+ if _get_token_from_google_colab() is not None:
157
+ raise EnvironmentError(
158
+ "You are automatically logged in using a Google Colab secret.\n"
159
+ "To log out, you must unset the `HF_TOKEN` secret in your Colab settings."
160
+ )
161
+ if _get_token_from_environment() is not None:
162
+ raise EnvironmentError(
163
+ "Token has been deleted from your machine but you are still logged in.\n"
164
+ "To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables."
165
+ )
166
+
167
+
168
+ def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None:
169
+ """Switch to a different access token.
170
+
171
+ Args:
172
+ token_name (`str`):
173
+ Name of the access token to switch to.
174
+ add_to_git_credential (`bool`, defaults to `False`):
175
+ If `True`, token will be set as git credential. If no git credential helper
176
+ is configured, a warning will be displayed to the user. If `token` is `None`,
177
+ the value of `add_to_git_credential` is ignored and will be prompted again
178
+ to the end user.
179
+
180
+ Raises:
181
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
182
+ If the access token name is not found.
183
+ """
184
+ token = _get_token_by_name(token_name)
185
+ if not token:
186
+ raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
187
+ # Write token to HF_TOKEN_PATH
188
+ _set_active_token(token_name, add_to_git_credential)
189
+ logger.info(f"The current active token is: {token_name}")
190
+ token_from_environment = _get_token_from_environment()
191
+ if token_from_environment is not None and token_from_environment != token:
192
+ logger.warning(
193
+ "The environment variable `HF_TOKEN` is set and will override the access token you've just switched to."
194
+ )
195
+
196
+
197
+ def auth_list() -> None:
198
+ """List all stored access tokens."""
199
+ tokens = get_stored_tokens()
200
+
201
+ if not tokens:
202
+ logger.info("No access tokens found.")
203
+ return
204
+ # Find current token
205
+ current_token = get_token()
206
+ current_token_name = None
207
+ for token_name in tokens:
208
+ if tokens.get(token_name) == current_token:
209
+ current_token_name = token_name
210
+ # Print header
211
+ max_offset = max(len("token"), max(len(token) for token in tokens)) + 2
212
+ print(f" {{:<{max_offset}}}| {{:<15}}".format("name", "token"))
213
+ print("-" * (max_offset + 2) + "|" + "-" * 15)
214
+
215
+ # Print saved access tokens
216
+ for token_name in tokens:
217
+ token = tokens.get(token_name, "<not set>")
218
+ masked_token = f"{token[:3]}****{token[-4:]}" if token != "<not set>" else token
219
+ is_current = "*" if token == current_token else " "
220
+
221
+ print(f"{is_current} {{:<{max_offset}}}| {{:<15}}".format(token_name, masked_token))
222
+
223
+ if _get_token_from_environment():
224
+ logger.warning(
225
+ "\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above."
226
+ )
227
+ elif current_token_name is None:
228
+ logger.warning(
229
+ "\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `huggingface-cli login` to log in."
230
+ )
231
+
232
+
233
+ ###
234
+ # Interpreter-based login (text)
235
+ ###
236
+
237
+
238
+ def interpreter_login(new_session: bool = True, write_permission: bool = False) -> None:
239
+ """
240
+ Displays a prompt to log in to the HF website and store the token.
241
+
242
+ This is equivalent to [`login`] without passing a token when not run in a notebook.
243
+ [`interpreter_login`] is useful if you want to force the use of the terminal prompt
244
+ instead of a notebook widget.
245
+
246
+ For more details, see [`login`].
247
+
248
+ Args:
249
+ new_session (`bool`, defaults to `True`):
250
+ If `True`, will request a token even if one is already saved on the machine.
251
+ write_permission (`bool`, defaults to `False`):
252
+ If `True`, requires a token with write permission.
253
+
254
+ """
255
+ if not new_session and _current_token_okay(write_permission=write_permission):
256
+ logger.info("User is already logged in.")
257
+ return
258
+
259
+ from .commands.delete_cache import _ask_for_confirmation_no_tui
260
+
261
+ print(_HF_LOGO_ASCII)
262
+ if get_token() is not None:
263
+ logger.info(
264
+ " A token is already saved on your machine. Run `huggingface-cli"
265
+ " whoami` to get more information or `huggingface-cli logout` if you want"
266
+ " to log out."
267
+ )
268
+ logger.info(" Setting a new token will erase the existing one.")
269
+
270
+ logger.info(
271
+ " To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ."
272
+ )
273
+ if os.name == "nt":
274
+ logger.info("Token can be pasted using 'Right-Click'.")
275
+ token = getpass("Enter your token (input will not be visible): ")
276
+ add_to_git_credential = _ask_for_confirmation_no_tui("Add token as git credential?")
277
+
278
+ _login(
279
+ token=token,
280
+ add_to_git_credential=add_to_git_credential,
281
+ write_permission=write_permission,
282
+ )
283
+
284
+
285
+ ###
286
+ # Notebook-based login (widget)
287
+ ###
288
+
289
+ NOTEBOOK_LOGIN_PASSWORD_HTML = """<center> <img
290
+ src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
291
+ alt='Hugging Face'> <br> Immediately click login after typing your password or
292
+ it might be stored in plain text in this notebook file. </center>"""
293
+
294
+
295
+ NOTEBOOK_LOGIN_TOKEN_HTML_START = """<center> <img
296
+ src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
297
+ alt='Hugging Face'> <br> Copy a token from <a
298
+ href="https://huggingface.co/settings/tokens" target="_blank">your Hugging Face
299
+ tokens page</a> and paste it below. <br> Immediately click login after copying
300
+ your token or it might be stored in plain text in this notebook file. </center>"""
301
+
302
+
303
+ NOTEBOOK_LOGIN_TOKEN_HTML_END = """
304
+ <b>Pro Tip:</b> If you don't already have one, you can create a dedicated
305
+ 'notebooks' token with 'write' access, that you can then easily reuse for all
306
+ notebooks. </center>"""
307
+
308
+
309
+ def notebook_login(new_session: bool = True, write_permission: bool = False) -> None:
310
+ """
311
+ Displays a widget to log in to the HF website and store the token.
312
+
313
+ This is equivalent to [`login`] without passing a token when run in a notebook.
314
+ [`notebook_login`] is useful if you want to force the use of the notebook widget
315
+ instead of a prompt in the terminal.
316
+
317
+ For more details, see [`login`].
318
+
319
+ Args:
320
+ new_session (`bool`, defaults to `True`):
321
+ If `True`, will request a token even if one is already saved on the machine.
322
+ write_permission (`bool`, defaults to `False`):
323
+ If `True`, requires a token with write permission.
324
+ """
325
+ try:
326
+ import ipywidgets.widgets as widgets # type: ignore
327
+ from IPython.display import display # type: ignore
328
+ except ImportError:
329
+ raise ImportError(
330
+ "The `notebook_login` function can only be used in a notebook (Jupyter or"
331
+ " Colab) and you need the `ipywidgets` module: `pip install ipywidgets`."
332
+ )
333
+ if not new_session and _current_token_okay(write_permission=write_permission):
334
+ logger.info("User is already logged in.")
335
+ return
336
+
337
+ box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
338
+
339
+ token_widget = widgets.Password(description="Token:")
340
+ git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?")
341
+ token_finish_button = widgets.Button(description="Login")
342
+
343
+ login_token_widget = widgets.VBox(
344
+ [
345
+ widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START),
346
+ token_widget,
347
+ git_checkbox_widget,
348
+ token_finish_button,
349
+ widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END),
350
+ ],
351
+ layout=box_layout,
352
+ )
353
+ display(login_token_widget)
354
+
355
+ # On click events
356
+ def login_token_event(t, write_permission: bool = False):
357
+ """
358
+ Event handler for the login button.
359
+
360
+ Args:
361
+ write_permission (`bool`, defaults to `False`):
362
+ If `True`, requires a token with write permission.
363
+ """
364
+ token = token_widget.value
365
+ add_to_git_credential = git_checkbox_widget.value
366
+ # Erase token and clear value to make sure it's not saved in the notebook.
367
+ token_widget.value = ""
368
+ # Hide inputs
369
+ login_token_widget.children = [widgets.Label("Connecting...")]
370
+ try:
371
+ with capture_output() as captured:
372
+ _login(token, add_to_git_credential=add_to_git_credential, write_permission=write_permission)
373
+ message = captured.getvalue()
374
+ except Exception as error:
375
+ message = str(error)
376
+ # Print result (success message or error)
377
+ login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()]
378
+
379
+ token_finish_button.on_click(partial(login_token_event, write_permission=write_permission))
380
+
381
+
382
+ ###
383
+ # Login private helpers
384
+ ###
385
+
386
+
387
+ def _login(
388
+ token: str,
389
+ add_to_git_credential: bool,
390
+ write_permission: bool = False,
391
+ ) -> None:
392
+ from .hf_api import whoami # avoid circular import
393
+
394
+ if token.startswith("api_org"):
395
+ raise ValueError("You must use your personal account token, not an organization token.")
396
+
397
+ token_info = whoami(token)
398
+ permission = token_info["auth"]["accessToken"]["role"]
399
+ if write_permission and permission != "write":
400
+ raise ValueError(
401
+ "Token is valid but is 'read-only' and a 'write' token is required.\nPlease provide a new token with"
402
+ " correct permission."
403
+ )
404
+ logger.info(f"Token is valid (permission: {permission}).")
405
+
406
+ token_name = token_info["auth"]["accessToken"]["displayName"]
407
+ # Store token locally
408
+ _save_token(token=token, token_name=token_name)
409
+ # Set active token
410
+ _set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential)
411
+ logger.info("Login successful.")
412
+ if _get_token_from_environment():
413
+ logger.warning(
414
+ "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured."
415
+ )
416
+ else:
417
+ logger.info(f"The current active token is: `{token_name}`")
418
+
419
+
420
+ def _logout_from_token(token_name: str) -> None:
421
+ """Logout from a specific access token.
422
+
423
+ Args:
424
+ token_name (`str`):
425
+ The name of the access token to logout from.
426
+ Raises:
427
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
428
+ If the access token name is not found.
429
+ """
430
+ stored_tokens = get_stored_tokens()
431
+ # If there is no access tokens saved or the access token name is not found, do nothing
432
+ if not stored_tokens or token_name not in stored_tokens:
433
+ return
434
+
435
+ token = stored_tokens.pop(token_name)
436
+ _save_stored_tokens(stored_tokens)
437
+
438
+ if token == _get_token_from_file():
439
+ logger.warning(f"Active token '{token_name}' has been deleted.")
440
+ Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True)
441
+
442
+
443
+ def _set_active_token(
444
+ token_name: str,
445
+ add_to_git_credential: bool,
446
+ ) -> None:
447
+ """Set the active access token.
448
+
449
+ Args:
450
+ token_name (`str`):
451
+ The name of the token to set as active.
452
+ """
453
+ token = _get_token_by_name(token_name)
454
+ if not token:
455
+ raise ValueError(f"Token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
456
+ if add_to_git_credential:
457
+ if _is_git_credential_helper_configured():
458
+ set_git_credential(token)
459
+ logger.info(
460
+ "Your token has been saved in your configured git credential helpers"
461
+ + f" ({','.join(list_credential_helpers())})."
462
+ )
463
+ else:
464
+ logger.warning("Token has not been saved to git credential helper.")
465
+ # Write token to HF_TOKEN_PATH
466
+ path = Path(constants.HF_TOKEN_PATH)
467
+ path.parent.mkdir(parents=True, exist_ok=True)
468
+ path.write_text(token)
469
+ logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
470
+
471
+
472
+ def _current_token_okay(write_permission: bool = False):
473
+ """Check if the current token is valid.
474
+
475
+ Args:
476
+ write_permission (`bool`, defaults to `False`):
477
+ If `True`, requires a token with write permission.
478
+
479
+ Returns:
480
+ `bool`: `True` if the current token is valid, `False` otherwise.
481
+ """
482
+ from .hf_api import get_token_permission # avoid circular import
483
+
484
+ permission = get_token_permission()
485
+ if permission is None or (write_permission and permission != "write"):
486
+ return False
487
+ return True
488
+
489
+
490
+ def _is_git_credential_helper_configured() -> bool:
491
+ """Check if a git credential helper is configured.
492
+
493
+ Warns user if not the case (except for Google Colab where "store" is set by default
494
+ by `huggingface_hub`).
495
+ """
496
+ helpers = list_credential_helpers()
497
+ if len(helpers) > 0:
498
+ return True # Do not warn: at least 1 helper is set
499
+
500
+ # Only in Google Colab to avoid the warning message
501
+ # See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710
502
+ if is_google_colab():
503
+ _set_store_as_git_credential_helper_globally()
504
+ return True # Do not warn: "store" is used by default in Google Colab
505
+
506
+ # Otherwise, warn user
507
+ print(
508
+ ANSI.red(
509
+ "Cannot authenticate through git-credential as no helper is defined on your"
510
+ " machine.\nYou might have to re-authenticate when pushing to the Hugging"
511
+ " Face Hub.\nRun the following command in your terminal in case you want to"
512
+ " set the 'store' credential helper as default.\n\ngit config --global"
513
+ " credential.helper store\n\nRead"
514
+ " https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more"
515
+ " details."
516
+ )
517
+ )
518
+ return False
519
+
520
+
521
+ def _set_store_as_git_credential_helper_globally() -> None:
522
+ """Set globally the credential.helper to `store`.
523
+
524
+ To be used only in Google Colab as we assume the user doesn't care about the git
525
+ credential config. It is the only particular case where we don't want to display the
526
+ warning message in [`notebook_login()`].
527
+
528
+ Related:
529
+ - https://github.com/huggingface/huggingface_hub/issues/1043
530
+ - https://github.com/huggingface/huggingface_hub/issues/1051
531
+ - https://git-scm.com/docs/git-credential-store
532
+ """
533
+ try:
534
+ run_subprocess("git config --global credential.helper store")
535
+ except subprocess.CalledProcessError as exc:
536
+ raise EnvironmentError(exc.stderr)
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_multi_commits.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to multi-commits (i.e. push changes iteratively on a PR)."""
16
+
17
+ import re
18
+ from dataclasses import dataclass, field
19
+ from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Union
20
+
21
+ from ._commit_api import CommitOperationAdd, CommitOperationDelete
22
+ from .community import DiscussionWithDetails
23
+ from .utils import experimental
24
+ from .utils._cache_manager import _format_size
25
+ from .utils.insecure_hashlib import sha256
26
+
27
+
28
+ if TYPE_CHECKING:
29
+ from .hf_api import HfApi
30
+
31
+
32
+ class MultiCommitException(Exception):
33
+ """Base exception for any exception happening while doing a multi-commit."""
34
+
35
+
36
+ MULTI_COMMIT_PR_DESCRIPTION_TEMPLATE = """
37
+ ## {commit_message}
38
+
39
+ {commit_description}
40
+
41
+ **Multi commit ID:** {multi_commit_id}
42
+
43
+ Scheduled commits:
44
+
45
+ {multi_commit_strategy}
46
+
47
+ _This is a PR opened using the `huggingface_hub` library in the context of a multi-commit. PR can be commented as a usual PR. However, please be aware that manually updating the PR description, changing the PR status, or pushing new commits, is not recommended as it might corrupt the commit process. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
48
+ """
49
+
50
+ MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE = """
51
+ Multi-commit is now completed! You can ping the repo owner to review the changes. This PR can now be commented or modified without risking to corrupt it.
52
+
53
+ _This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
54
+ """
55
+
56
+ MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE = """
57
+ `create_pr=False` has been passed so PR is automatically merged.
58
+
59
+ _This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
60
+ """
61
+
62
+ MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE = """
63
+ Cannot merge Pull Requests as no changes are associated. This PR will be closed automatically.
64
+
65
+ _This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
66
+ """
67
+
68
+ MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE = """
69
+ An error occurred while trying to merge the Pull Request: `{error_message}`.
70
+
71
+ _This is a comment posted using the `huggingface_hub` library in the context of a multi-commit. Learn more about multi-commits [in this guide](https://huggingface.co/docs/huggingface_hub/main/guides/upload)._
72
+ """
73
+
74
+
75
+ STEP_ID_REGEX = re.compile(r"- \[(?P<completed>[ |x])\].*(?P<step_id>[a-fA-F0-9]{64})", flags=re.MULTILINE)
76
+
77
+
78
+ @experimental
79
+ def plan_multi_commits(
80
+ operations: Iterable[Union[CommitOperationAdd, CommitOperationDelete]],
81
+ max_operations_per_commit: int = 50,
82
+ max_upload_size_per_commit: int = 2 * 1024 * 1024 * 1024,
83
+ ) -> Tuple[List[List[CommitOperationAdd]], List[List[CommitOperationDelete]]]:
84
+ """Split a list of operations in a list of commits to perform.
85
+
86
+ Implementation follows a sub-optimal (yet simple) algorithm:
87
+ 1. Delete operations are grouped together by commits of maximum `max_operations_per_commits` operations.
88
+ 2. All additions exceeding `max_upload_size_per_commit` are committed 1 by 1.
89
+ 3. All remaining additions are grouped together and split each time the `max_operations_per_commit` or the
90
+ `max_upload_size_per_commit` limit is reached.
91
+
92
+ We do not try to optimize the splitting to get the lowest number of commits as this is a NP-hard problem (see
93
+ [bin packing problem](https://en.wikipedia.org/wiki/Bin_packing_problem)). For our use case, it is not problematic
94
+ to use a sub-optimal solution so we favored an easy-to-explain implementation.
95
+
96
+ Args:
97
+ operations (`List` of [`~hf_api.CommitOperation`]):
98
+ The list of operations to split into commits.
99
+ max_operations_per_commit (`int`):
100
+ Maximum number of operations in a single commit. Defaults to 50.
101
+ max_upload_size_per_commit (`int`):
102
+ Maximum size to upload (in bytes) in a single commit. Defaults to 2GB. Files bigger than this limit are
103
+ uploaded, 1 per commit.
104
+
105
+ Returns:
106
+ `Tuple[List[List[CommitOperationAdd]], List[List[CommitOperationDelete]]]`: a tuple. First item is a list of
107
+ lists of [`CommitOperationAdd`] representing the addition commits to push. The second item is a list of lists
108
+ of [`CommitOperationDelete`] representing the deletion commits.
109
+
110
+ <Tip warning={true}>
111
+
112
+ `plan_multi_commits` is experimental. Its API and behavior is subject to change in the future without prior notice.
113
+
114
+ </Tip>
115
+
116
+ Example:
117
+ ```python
118
+ >>> from huggingface_hub import HfApi, plan_multi_commits
119
+ >>> addition_commits, deletion_commits = plan_multi_commits(
120
+ ... operations=[
121
+ ... CommitOperationAdd(...),
122
+ ... CommitOperationAdd(...),
123
+ ... CommitOperationDelete(...),
124
+ ... CommitOperationDelete(...),
125
+ ... CommitOperationAdd(...),
126
+ ... ],
127
+ ... )
128
+ >>> HfApi().create_commits_on_pr(
129
+ ... repo_id="my-cool-model",
130
+ ... addition_commits=addition_commits,
131
+ ... deletion_commits=deletion_commits,
132
+ ... (...)
133
+ ... verbose=True,
134
+ ... )
135
+ ```
136
+
137
+ <Tip warning={true}>
138
+
139
+ The initial order of the operations is not guaranteed! All deletions will be performed before additions. If you are
140
+ not updating multiple times the same file, you are fine.
141
+
142
+ </Tip>
143
+ """
144
+ addition_commits: List[List[CommitOperationAdd]] = []
145
+ deletion_commits: List[List[CommitOperationDelete]] = []
146
+
147
+ additions: List[CommitOperationAdd] = []
148
+ additions_size = 0
149
+ deletions: List[CommitOperationDelete] = []
150
+ for op in operations:
151
+ if isinstance(op, CommitOperationDelete):
152
+ # Group delete operations together
153
+ deletions.append(op)
154
+ if len(deletions) >= max_operations_per_commit:
155
+ deletion_commits.append(deletions)
156
+ deletions = []
157
+
158
+ elif op.upload_info.size >= max_upload_size_per_commit:
159
+ # Upload huge files 1 by 1
160
+ addition_commits.append([op])
161
+
162
+ elif additions_size + op.upload_info.size < max_upload_size_per_commit:
163
+ # Group other additions and split if size limit is reached (either max_nb_files or max_upload_size)
164
+ additions.append(op)
165
+ additions_size += op.upload_info.size
166
+
167
+ else:
168
+ addition_commits.append(additions)
169
+ additions = [op]
170
+ additions_size = op.upload_info.size
171
+
172
+ if len(additions) >= max_operations_per_commit:
173
+ addition_commits.append(additions)
174
+ additions = []
175
+ additions_size = 0
176
+
177
+ if len(additions) > 0:
178
+ addition_commits.append(additions)
179
+ if len(deletions) > 0:
180
+ deletion_commits.append(deletions)
181
+
182
+ return addition_commits, deletion_commits
183
+
184
+
185
+ @dataclass
186
+ class MultiCommitStep:
187
+ """Dataclass containing a list of CommitOperation to commit at once.
188
+
189
+ A [`MultiCommitStep`] is one atomic part of a [`MultiCommitStrategy`]. Each step is identified by its own
190
+ deterministic ID based on the list of commit operations (hexadecimal sha256). ID is persistent between re-runs if
191
+ the list of commits is kept the same.
192
+ """
193
+
194
+ operations: List[Union[CommitOperationAdd, CommitOperationDelete]]
195
+
196
+ id: str = field(init=False)
197
+ completed: bool = False
198
+
199
+ def __post_init__(self) -> None:
200
+ if len(self.operations) == 0:
201
+ raise ValueError("A MultiCommitStep must have at least 1 commit operation, got 0.")
202
+
203
+ # Generate commit id
204
+ sha = sha256()
205
+ for op in self.operations:
206
+ if isinstance(op, CommitOperationAdd):
207
+ sha.update(b"ADD")
208
+ sha.update(op.path_in_repo.encode())
209
+ sha.update(op.upload_info.sha256)
210
+ elif isinstance(op, CommitOperationDelete):
211
+ sha.update(b"DELETE")
212
+ sha.update(op.path_in_repo.encode())
213
+ sha.update(str(op.is_folder).encode())
214
+ else:
215
+ NotImplementedError()
216
+ self.id = sha.hexdigest()
217
+
218
+ def __str__(self) -> str:
219
+ """Format a step for PR description.
220
+
221
+ Formatting can be changed in the future as long as it is single line, starts with `- [ ]`/`- [x]` and contains
222
+ `self.id`. Must be able to match `STEP_ID_REGEX`.
223
+ """
224
+ additions = [op for op in self.operations if isinstance(op, CommitOperationAdd)]
225
+ file_deletions = [op for op in self.operations if isinstance(op, CommitOperationDelete) and not op.is_folder]
226
+ folder_deletions = [op for op in self.operations if isinstance(op, CommitOperationDelete) and op.is_folder]
227
+ if len(additions) > 0:
228
+ return (
229
+ f"- [{'x' if self.completed else ' '}] Upload {len(additions)} file(s) "
230
+ f"totalling {_format_size(sum(add.upload_info.size for add in additions))}"
231
+ f" ({self.id})"
232
+ )
233
+ else:
234
+ return (
235
+ f"- [{'x' if self.completed else ' '}] Delete {len(file_deletions)} file(s) and"
236
+ f" {len(folder_deletions)} folder(s) ({self.id})"
237
+ )
238
+
239
+
240
+ @dataclass
241
+ class MultiCommitStrategy:
242
+ """Dataclass containing a list of [`MultiCommitStep`] to commit iteratively.
243
+
244
+ A strategy is identified by its own deterministic ID based on the list of its steps (hexadecimal sha256). ID is
245
+ persistent between re-runs if the list of commits is kept the same.
246
+ """
247
+
248
+ addition_commits: List[MultiCommitStep]
249
+ deletion_commits: List[MultiCommitStep]
250
+
251
+ id: str = field(init=False)
252
+ all_steps: Set[str] = field(init=False)
253
+
254
+ def __post_init__(self) -> None:
255
+ self.all_steps = {step.id for step in self.addition_commits + self.deletion_commits}
256
+ if len(self.all_steps) < len(self.addition_commits) + len(self.deletion_commits):
257
+ raise ValueError("Got duplicate commits in MultiCommitStrategy. All commits must be unique.")
258
+
259
+ if len(self.all_steps) == 0:
260
+ raise ValueError("A MultiCommitStrategy must have at least 1 commit, got 0.")
261
+
262
+ # Generate strategy id
263
+ sha = sha256()
264
+ for step in self.addition_commits + self.deletion_commits:
265
+ sha.update("new step".encode())
266
+ sha.update(step.id.encode())
267
+ self.id = sha.hexdigest()
268
+
269
+
270
+ def multi_commit_create_pull_request(
271
+ api: "HfApi",
272
+ repo_id: str,
273
+ commit_message: str,
274
+ commit_description: Optional[str],
275
+ strategy: MultiCommitStrategy,
276
+ repo_type: Optional[str],
277
+ token: Union[str, bool, None] = None,
278
+ ) -> DiscussionWithDetails:
279
+ return api.create_pull_request(
280
+ repo_id=repo_id,
281
+ title=f"[WIP] {commit_message} (multi-commit {strategy.id})",
282
+ description=multi_commit_generate_comment(
283
+ commit_message=commit_message, commit_description=commit_description, strategy=strategy
284
+ ),
285
+ token=token,
286
+ repo_type=repo_type,
287
+ )
288
+
289
+
290
+ def multi_commit_generate_comment(
291
+ commit_message: str,
292
+ commit_description: Optional[str],
293
+ strategy: MultiCommitStrategy,
294
+ ) -> str:
295
+ return MULTI_COMMIT_PR_DESCRIPTION_TEMPLATE.format(
296
+ commit_message=commit_message,
297
+ commit_description=commit_description or "",
298
+ multi_commit_id=strategy.id,
299
+ multi_commit_strategy="\n".join(
300
+ str(commit) for commit in strategy.deletion_commits + strategy.addition_commits
301
+ ),
302
+ )
303
+
304
+
305
+ def multi_commit_parse_pr_description(description: str) -> Set[str]:
306
+ return {match[1] for match in STEP_ID_REGEX.findall(description)}
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_snapshot_download.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Dict, List, Literal, Optional, Union
4
+
5
+ import requests
6
+ from tqdm.auto import tqdm as base_tqdm
7
+ from tqdm.contrib.concurrent import thread_map
8
+
9
+ from . import constants
10
+ from .errors import GatedRepoError, LocalEntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
11
+ from .file_download import REGEX_COMMIT_HASH, hf_hub_download, repo_folder_name
12
+ from .hf_api import DatasetInfo, HfApi, ModelInfo, SpaceInfo
13
+ from .utils import OfflineModeIsEnabled, filter_repo_objects, logging, validate_hf_hub_args
14
+ from .utils import tqdm as hf_tqdm
15
+
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ @validate_hf_hub_args
21
+ def snapshot_download(
22
+ repo_id: str,
23
+ *,
24
+ repo_type: Optional[str] = None,
25
+ revision: Optional[str] = None,
26
+ cache_dir: Union[str, Path, None] = None,
27
+ local_dir: Union[str, Path, None] = None,
28
+ library_name: Optional[str] = None,
29
+ library_version: Optional[str] = None,
30
+ user_agent: Optional[Union[Dict, str]] = None,
31
+ proxies: Optional[Dict] = None,
32
+ etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
33
+ force_download: bool = False,
34
+ token: Optional[Union[bool, str]] = None,
35
+ local_files_only: bool = False,
36
+ allow_patterns: Optional[Union[List[str], str]] = None,
37
+ ignore_patterns: Optional[Union[List[str], str]] = None,
38
+ max_workers: int = 8,
39
+ tqdm_class: Optional[base_tqdm] = None,
40
+ headers: Optional[Dict[str, str]] = None,
41
+ endpoint: Optional[str] = None,
42
+ # Deprecated args
43
+ local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
44
+ resume_download: Optional[bool] = None,
45
+ ) -> str:
46
+ """Download repo files.
47
+
48
+ Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
49
+ a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
50
+ to keep their actual filename relative to that folder. You can also filter which files to download using
51
+ `allow_patterns` and `ignore_patterns`.
52
+
53
+ If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
54
+ option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
55
+ to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
56
+ cache-system, it's optimized for regularly pulling the latest version of a repository.
57
+
58
+ An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
59
+ configured. It is also not possible to filter which files to download when cloning a repository using git.
60
+
61
+ Args:
62
+ repo_id (`str`):
63
+ A user or an organization name and a repo name separated by a `/`.
64
+ repo_type (`str`, *optional*):
65
+ Set to `"dataset"` or `"space"` if downloading from a dataset or space,
66
+ `None` or `"model"` if downloading from a model. Default is `None`.
67
+ revision (`str`, *optional*):
68
+ An optional Git revision id which can be a branch name, a tag, or a
69
+ commit hash.
70
+ cache_dir (`str`, `Path`, *optional*):
71
+ Path to the folder where cached files are stored.
72
+ local_dir (`str` or `Path`, *optional*):
73
+ If provided, the downloaded files will be placed under this directory.
74
+ library_name (`str`, *optional*):
75
+ The name of the library to which the object corresponds.
76
+ library_version (`str`, *optional*):
77
+ The version of the library.
78
+ user_agent (`str`, `dict`, *optional*):
79
+ The user-agent info in the form of a dictionary or a string.
80
+ proxies (`dict`, *optional*):
81
+ Dictionary mapping protocol to the URL of the proxy passed to
82
+ `requests.request`.
83
+ etag_timeout (`float`, *optional*, defaults to `10`):
84
+ When fetching ETag, how many seconds to wait for the server to send
85
+ data before giving up which is passed to `requests.request`.
86
+ force_download (`bool`, *optional*, defaults to `False`):
87
+ Whether the file should be downloaded even if it already exists in the local cache.
88
+ token (`str`, `bool`, *optional*):
89
+ A token to be used for the download.
90
+ - If `True`, the token is read from the HuggingFace config
91
+ folder.
92
+ - If a string, it's used as the authentication token.
93
+ headers (`dict`, *optional*):
94
+ Additional headers to include in the request. Those headers take precedence over the others.
95
+ local_files_only (`bool`, *optional*, defaults to `False`):
96
+ If `True`, avoid downloading the file and return the path to the
97
+ local cached file if it exists.
98
+ allow_patterns (`List[str]` or `str`, *optional*):
99
+ If provided, only files matching at least one pattern are downloaded.
100
+ ignore_patterns (`List[str]` or `str`, *optional*):
101
+ If provided, files matching any of the patterns are not downloaded.
102
+ max_workers (`int`, *optional*):
103
+ Number of concurrent threads to download files (1 thread = 1 file download).
104
+ Defaults to 8.
105
+ tqdm_class (`tqdm`, *optional*):
106
+ If provided, overwrites the default behavior for the progress bar. Passed
107
+ argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
108
+ Note that the `tqdm_class` is not passed to each individual download.
109
+ Defaults to the custom HF progress bar that can be disabled by setting
110
+ `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
111
+
112
+ Returns:
113
+ `str`: folder path of the repo snapshot.
114
+
115
+ Raises:
116
+ [`~utils.RepositoryNotFoundError`]
117
+ If the repository to download from cannot be found. This may be because it doesn't exist,
118
+ or because it is set to `private` and you do not have access.
119
+ [`~utils.RevisionNotFoundError`]
120
+ If the revision to download from cannot be found.
121
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
122
+ If `token=True` and the token cannot be found.
123
+ [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
124
+ ETag cannot be determined.
125
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
126
+ if some parameter value is invalid.
127
+ """
128
+ if cache_dir is None:
129
+ cache_dir = constants.HF_HUB_CACHE
130
+ if revision is None:
131
+ revision = constants.DEFAULT_REVISION
132
+ if isinstance(cache_dir, Path):
133
+ cache_dir = str(cache_dir)
134
+
135
+ if repo_type is None:
136
+ repo_type = "model"
137
+ if repo_type not in constants.REPO_TYPES:
138
+ raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES)}")
139
+
140
+ storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
141
+
142
+ repo_info: Union[ModelInfo, DatasetInfo, SpaceInfo, None] = None
143
+ api_call_error: Optional[Exception] = None
144
+ if not local_files_only:
145
+ # try/except logic to handle different errors => taken from `hf_hub_download`
146
+ try:
147
+ # if we have internet connection we want to list files to download
148
+ api = HfApi(
149
+ library_name=library_name,
150
+ library_version=library_version,
151
+ user_agent=user_agent,
152
+ endpoint=endpoint,
153
+ headers=headers,
154
+ )
155
+ repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision, token=token)
156
+ except (requests.exceptions.SSLError, requests.exceptions.ProxyError):
157
+ # Actually raise for those subclasses of ConnectionError
158
+ raise
159
+ except (
160
+ requests.exceptions.ConnectionError,
161
+ requests.exceptions.Timeout,
162
+ OfflineModeIsEnabled,
163
+ ) as error:
164
+ # Internet connection is down
165
+ # => will try to use local files only
166
+ api_call_error = error
167
+ pass
168
+ except RevisionNotFoundError:
169
+ # The repo was found but the revision doesn't exist on the Hub (never existed or got deleted)
170
+ raise
171
+ except requests.HTTPError as error:
172
+ # Multiple reasons for an http error:
173
+ # - Repository is private and invalid/missing token sent
174
+ # - Repository is gated and invalid/missing token sent
175
+ # - Hub is down (error 500 or 504)
176
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
177
+ # (if it's not the case, the error will be re-raised)
178
+ api_call_error = error
179
+ pass
180
+
181
+ # At this stage, if `repo_info` is None it means either:
182
+ # - internet connection is down
183
+ # - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True)
184
+ # - repo is private/gated and invalid/missing token sent
185
+ # - Hub is down
186
+ # => let's look if we can find the appropriate folder in the cache:
187
+ # - if the specified revision is a commit hash, look inside "snapshots".
188
+ # - f the specified revision is a branch or tag, look inside "refs".
189
+ # => if local_dir is not None, we will return the path to the local folder if it exists.
190
+ if repo_info is None:
191
+ # Try to get which commit hash corresponds to the specified revision
192
+ commit_hash = None
193
+ if REGEX_COMMIT_HASH.match(revision):
194
+ commit_hash = revision
195
+ else:
196
+ ref_path = os.path.join(storage_folder, "refs", revision)
197
+ if os.path.exists(ref_path):
198
+ # retrieve commit_hash from refs file
199
+ with open(ref_path) as f:
200
+ commit_hash = f.read()
201
+
202
+ # Try to locate snapshot folder for this commit hash
203
+ if commit_hash is not None:
204
+ snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
205
+ if os.path.exists(snapshot_folder):
206
+ # Snapshot folder exists => let's return it
207
+ # (but we can't check if all the files are actually there)
208
+ return snapshot_folder
209
+ # If local_dir is not None, return it if it exists and is not empty
210
+ if local_dir is not None:
211
+ local_dir = Path(local_dir)
212
+ if local_dir.is_dir() and any(local_dir.iterdir()):
213
+ logger.warning(
214
+ f"Returning existing local_dir `{local_dir}` as remote repo cannot be accessed in `snapshot_download` ({api_call_error})."
215
+ )
216
+ return str(local_dir.resolve())
217
+ # If we couldn't find the appropriate folder on disk, raise an error.
218
+ if local_files_only:
219
+ raise LocalEntryNotFoundError(
220
+ "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
221
+ "outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass "
222
+ "'local_files_only=False' as input."
223
+ )
224
+ elif isinstance(api_call_error, OfflineModeIsEnabled):
225
+ raise LocalEntryNotFoundError(
226
+ "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
227
+ "outgoing traffic has been disabled. To enable repo look-ups and downloads online, set "
228
+ "'HF_HUB_OFFLINE=0' as environment variable."
229
+ ) from api_call_error
230
+ elif isinstance(api_call_error, RepositoryNotFoundError) or isinstance(api_call_error, GatedRepoError):
231
+ # Repo not found => let's raise the actual error
232
+ raise api_call_error
233
+ else:
234
+ # Otherwise: most likely a connection issue or Hub downtime => let's warn the user
235
+ raise LocalEntryNotFoundError(
236
+ "An error happened while trying to locate the files on the Hub and we cannot find the appropriate"
237
+ " snapshot folder for the specified revision on the local disk. Please check your internet connection"
238
+ " and try again."
239
+ ) from api_call_error
240
+
241
+ # At this stage, internet connection is up and running
242
+ # => let's download the files!
243
+ assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
244
+ assert repo_info.siblings is not None, "Repo info returned from server must have a siblings list."
245
+ filtered_repo_files = list(
246
+ filter_repo_objects(
247
+ items=[f.rfilename for f in repo_info.siblings],
248
+ allow_patterns=allow_patterns,
249
+ ignore_patterns=ignore_patterns,
250
+ )
251
+ )
252
+ commit_hash = repo_info.sha
253
+ snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
254
+ # if passed revision is not identical to commit_hash
255
+ # then revision has to be a branch name or tag name.
256
+ # In that case store a ref.
257
+ if revision != commit_hash:
258
+ ref_path = os.path.join(storage_folder, "refs", revision)
259
+ os.makedirs(os.path.dirname(ref_path), exist_ok=True)
260
+ with open(ref_path, "w") as f:
261
+ f.write(commit_hash)
262
+
263
+ # we pass the commit_hash to hf_hub_download
264
+ # so no network call happens if we already
265
+ # have the file locally.
266
+ def _inner_hf_hub_download(repo_file: str):
267
+ return hf_hub_download(
268
+ repo_id,
269
+ filename=repo_file,
270
+ repo_type=repo_type,
271
+ revision=commit_hash,
272
+ endpoint=endpoint,
273
+ cache_dir=cache_dir,
274
+ local_dir=local_dir,
275
+ local_dir_use_symlinks=local_dir_use_symlinks,
276
+ library_name=library_name,
277
+ library_version=library_version,
278
+ user_agent=user_agent,
279
+ proxies=proxies,
280
+ etag_timeout=etag_timeout,
281
+ resume_download=resume_download,
282
+ force_download=force_download,
283
+ token=token,
284
+ headers=headers,
285
+ )
286
+
287
+ if constants.HF_HUB_ENABLE_HF_TRANSFER:
288
+ # when using hf_transfer we don't want extra parallelism
289
+ # from the one hf_transfer provides
290
+ for file in filtered_repo_files:
291
+ _inner_hf_hub_download(file)
292
+ else:
293
+ thread_map(
294
+ _inner_hf_hub_download,
295
+ filtered_repo_files,
296
+ desc=f"Fetching {len(filtered_repo_files)} files",
297
+ max_workers=max_workers,
298
+ # User can use its own tqdm class or the default one from `huggingface_hub.utils`
299
+ tqdm_class=tqdm_class or hf_tqdm,
300
+ )
301
+
302
+ if local_dir is not None:
303
+ return str(os.path.realpath(local_dir))
304
+ return snapshot_folder
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_space_api.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from dataclasses import dataclass
16
+ from datetime import datetime
17
+ from enum import Enum
18
+ from typing import Dict, Optional
19
+
20
+ from huggingface_hub.utils import parse_datetime
21
+
22
+
23
+ class SpaceStage(str, Enum):
24
+ """
25
+ Enumeration of possible stage of a Space on the Hub.
26
+
27
+ Value can be compared to a string:
28
+ ```py
29
+ assert SpaceStage.BUILDING == "BUILDING"
30
+ ```
31
+
32
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url).
33
+ """
34
+
35
+ # Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo)
36
+ NO_APP_FILE = "NO_APP_FILE"
37
+ CONFIG_ERROR = "CONFIG_ERROR"
38
+ BUILDING = "BUILDING"
39
+ BUILD_ERROR = "BUILD_ERROR"
40
+ RUNNING = "RUNNING"
41
+ RUNNING_BUILDING = "RUNNING_BUILDING"
42
+ RUNTIME_ERROR = "RUNTIME_ERROR"
43
+ DELETING = "DELETING"
44
+ STOPPED = "STOPPED"
45
+ PAUSED = "PAUSED"
46
+
47
+
48
+ class SpaceHardware(str, Enum):
49
+ """
50
+ Enumeration of hardwares available to run your Space on the Hub.
51
+
52
+ Value can be compared to a string:
53
+ ```py
54
+ assert SpaceHardware.CPU_BASIC == "cpu-basic"
55
+ ```
56
+
57
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L73 (private url).
58
+ """
59
+
60
+ CPU_BASIC = "cpu-basic"
61
+ CPU_UPGRADE = "cpu-upgrade"
62
+ T4_SMALL = "t4-small"
63
+ T4_MEDIUM = "t4-medium"
64
+ L4X1 = "l4x1"
65
+ L4X4 = "l4x4"
66
+ ZERO_A10G = "zero-a10g"
67
+ A10G_SMALL = "a10g-small"
68
+ A10G_LARGE = "a10g-large"
69
+ A10G_LARGEX2 = "a10g-largex2"
70
+ A10G_LARGEX4 = "a10g-largex4"
71
+ A100_LARGE = "a100-large"
72
+ V5E_1X1 = "v5e-1x1"
73
+ V5E_2X2 = "v5e-2x2"
74
+ V5E_2X4 = "v5e-2x4"
75
+
76
+
77
+ class SpaceStorage(str, Enum):
78
+ """
79
+ Enumeration of persistent storage available for your Space on the Hub.
80
+
81
+ Value can be compared to a string:
82
+ ```py
83
+ assert SpaceStorage.SMALL == "small"
84
+ ```
85
+
86
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url).
87
+ """
88
+
89
+ SMALL = "small"
90
+ MEDIUM = "medium"
91
+ LARGE = "large"
92
+
93
+
94
+ @dataclass
95
+ class SpaceRuntime:
96
+ """
97
+ Contains information about the current runtime of a Space.
98
+
99
+ Args:
100
+ stage (`str`):
101
+ Current stage of the space. Example: RUNNING.
102
+ hardware (`str` or `None`):
103
+ Current hardware of the space. Example: "cpu-basic". Can be `None` if Space
104
+ is `BUILDING` for the first time.
105
+ requested_hardware (`str` or `None`):
106
+ Requested hardware. Can be different than `hardware` especially if the request
107
+ has just been made. Example: "t4-medium". Can be `None` if no hardware has
108
+ been requested yet.
109
+ sleep_time (`int` or `None`):
110
+ Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the
111
+ Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48
112
+ hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
113
+ raw (`dict`):
114
+ Raw response from the server. Contains more information about the Space
115
+ runtime like number of replicas, number of cpu, memory size,...
116
+ """
117
+
118
+ stage: SpaceStage
119
+ hardware: Optional[SpaceHardware]
120
+ requested_hardware: Optional[SpaceHardware]
121
+ sleep_time: Optional[int]
122
+ storage: Optional[SpaceStorage]
123
+ raw: Dict
124
+
125
+ def __init__(self, data: Dict) -> None:
126
+ self.stage = data["stage"]
127
+ self.hardware = data.get("hardware", {}).get("current")
128
+ self.requested_hardware = data.get("hardware", {}).get("requested")
129
+ self.sleep_time = data.get("gcTimeout")
130
+ self.storage = data.get("storage")
131
+ self.raw = data
132
+
133
+
134
+ @dataclass
135
+ class SpaceVariable:
136
+ """
137
+ Contains information about the current variables of a Space.
138
+
139
+ Args:
140
+ key (`str`):
141
+ Variable key. Example: `"MODEL_REPO_ID"`
142
+ value (`str`):
143
+ Variable value. Example: `"the_model_repo_id"`.
144
+ description (`str` or None):
145
+ Description of the variable. Example: `"Model Repo ID of the implemented model"`.
146
+ updatedAt (`datetime` or None):
147
+ datetime of the last update of the variable (if the variable has been updated at least once).
148
+ """
149
+
150
+ key: str
151
+ value: str
152
+ description: Optional[str]
153
+ updated_at: Optional[datetime]
154
+
155
+ def __init__(self, key: str, values: Dict) -> None:
156
+ self.key = key
157
+ self.value = values["value"]
158
+ self.description = values.get("description")
159
+ updated_at = values.get("updatedAt")
160
+ self.updated_at = parse_datetime(updated_at) if updated_at is not None else None
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_upload_large_folder.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import enum
16
+ import logging
17
+ import os
18
+ import queue
19
+ import shutil
20
+ import sys
21
+ import threading
22
+ import time
23
+ import traceback
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+ from threading import Lock
27
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
28
+
29
+ from . import constants
30
+ from ._commit_api import CommitOperationAdd, UploadInfo, _fetch_upload_modes
31
+ from ._local_folder import LocalUploadFileMetadata, LocalUploadFilePaths, get_local_upload_paths, read_upload_metadata
32
+ from .constants import DEFAULT_REVISION, REPO_TYPES
33
+ from .utils import DEFAULT_IGNORE_PATTERNS, filter_repo_objects, tqdm
34
+ from .utils._cache_manager import _format_size
35
+ from .utils.sha import sha_fileobj
36
+
37
+
38
+ if TYPE_CHECKING:
39
+ from .hf_api import HfApi
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ WAITING_TIME_IF_NO_TASKS = 10 # seconds
44
+ MAX_NB_REGULAR_FILES_PER_COMMIT = 75
45
+ MAX_NB_LFS_FILES_PER_COMMIT = 150
46
+
47
+
48
+ def upload_large_folder_internal(
49
+ api: "HfApi",
50
+ repo_id: str,
51
+ folder_path: Union[str, Path],
52
+ *,
53
+ repo_type: str, # Repo type is required!
54
+ revision: Optional[str] = None,
55
+ private: bool = False,
56
+ allow_patterns: Optional[Union[List[str], str]] = None,
57
+ ignore_patterns: Optional[Union[List[str], str]] = None,
58
+ num_workers: Optional[int] = None,
59
+ print_report: bool = True,
60
+ print_report_every: int = 60,
61
+ ):
62
+ """Upload a large folder to the Hub in the most resilient way possible.
63
+
64
+ See [`HfApi.upload_large_folder`] for the full documentation.
65
+ """
66
+ # 1. Check args and setup
67
+ if repo_type is None:
68
+ raise ValueError(
69
+ "For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`."
70
+ " If you are using the CLI, pass it as `--repo-type=model`."
71
+ )
72
+ if repo_type not in REPO_TYPES:
73
+ raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
74
+ if revision is None:
75
+ revision = DEFAULT_REVISION
76
+
77
+ folder_path = Path(folder_path).expanduser().resolve()
78
+ if not folder_path.is_dir():
79
+ raise ValueError(f"Provided path: '{folder_path}' is not a directory")
80
+
81
+ if ignore_patterns is None:
82
+ ignore_patterns = []
83
+ elif isinstance(ignore_patterns, str):
84
+ ignore_patterns = [ignore_patterns]
85
+ ignore_patterns += DEFAULT_IGNORE_PATTERNS
86
+
87
+ if num_workers is None:
88
+ nb_cores = os.cpu_count() or 1
89
+ num_workers = max(nb_cores - 2, 2) # Use all but 2 cores, or at least 2 cores
90
+
91
+ # 2. Create repo if missing
92
+ repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True)
93
+ logger.info(f"Repo created: {repo_url}")
94
+ repo_id = repo_url.repo_id
95
+
96
+ # 3. List files to upload
97
+ filtered_paths_list = filter_repo_objects(
98
+ (path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()),
99
+ allow_patterns=allow_patterns,
100
+ ignore_patterns=ignore_patterns,
101
+ )
102
+ paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list]
103
+ logger.info(f"Found {len(paths_list)} candidate files to upload")
104
+
105
+ # Read metadata for each file
106
+ items = [
107
+ (paths, read_upload_metadata(folder_path, paths.path_in_repo))
108
+ for paths in tqdm(paths_list, desc="Recovering from metadata files")
109
+ ]
110
+
111
+ # 4. Start workers
112
+ status = LargeUploadStatus(items)
113
+ threads = [
114
+ threading.Thread(
115
+ target=_worker_job,
116
+ kwargs={
117
+ "status": status,
118
+ "api": api,
119
+ "repo_id": repo_id,
120
+ "repo_type": repo_type,
121
+ "revision": revision,
122
+ },
123
+ )
124
+ for _ in range(num_workers)
125
+ ]
126
+
127
+ for thread in threads:
128
+ thread.start()
129
+
130
+ # 5. Print regular reports
131
+ if print_report:
132
+ print("\n\n" + status.current_report())
133
+ last_report_ts = time.time()
134
+ while True:
135
+ time.sleep(1)
136
+ if time.time() - last_report_ts >= print_report_every:
137
+ if print_report:
138
+ _print_overwrite(status.current_report())
139
+ last_report_ts = time.time()
140
+ if status.is_done():
141
+ logging.info("Is done: exiting main loop")
142
+ break
143
+
144
+ for thread in threads:
145
+ thread.join()
146
+
147
+ logger.info(status.current_report())
148
+ logging.info("Upload is complete!")
149
+
150
+
151
+ ####################
152
+ # Logic to manage workers and synchronize tasks
153
+ ####################
154
+
155
+
156
+ class WorkerJob(enum.Enum):
157
+ SHA256 = enum.auto()
158
+ GET_UPLOAD_MODE = enum.auto()
159
+ PREUPLOAD_LFS = enum.auto()
160
+ COMMIT = enum.auto()
161
+ WAIT = enum.auto() # if no tasks are available but we don't want to exit
162
+
163
+
164
+ JOB_ITEM_T = Tuple[LocalUploadFilePaths, LocalUploadFileMetadata]
165
+
166
+
167
+ class LargeUploadStatus:
168
+ """Contains information, queues and tasks for a large upload process."""
169
+
170
+ def __init__(self, items: List[JOB_ITEM_T]):
171
+ self.items = items
172
+ self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
173
+ self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
174
+ self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
175
+ self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
176
+ self.lock = Lock()
177
+
178
+ self.nb_workers_sha256: int = 0
179
+ self.nb_workers_get_upload_mode: int = 0
180
+ self.nb_workers_preupload_lfs: int = 0
181
+ self.nb_workers_commit: int = 0
182
+ self.nb_workers_waiting: int = 0
183
+ self.last_commit_attempt: Optional[float] = None
184
+
185
+ self._started_at = datetime.now()
186
+
187
+ # Setup queues
188
+ for item in self.items:
189
+ paths, metadata = item
190
+ if metadata.sha256 is None:
191
+ self.queue_sha256.put(item)
192
+ elif metadata.upload_mode is None:
193
+ self.queue_get_upload_mode.put(item)
194
+ elif metadata.upload_mode == "lfs" and not metadata.is_uploaded:
195
+ self.queue_preupload_lfs.put(item)
196
+ elif not metadata.is_committed:
197
+ self.queue_commit.put(item)
198
+ else:
199
+ logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)")
200
+
201
+ def current_report(self) -> str:
202
+ """Generate a report of the current status of the large upload."""
203
+ nb_hashed = 0
204
+ size_hashed = 0
205
+ nb_preuploaded = 0
206
+ nb_lfs = 0
207
+ nb_lfs_unsure = 0
208
+ size_preuploaded = 0
209
+ nb_committed = 0
210
+ size_committed = 0
211
+ total_size = 0
212
+ ignored_files = 0
213
+ total_files = 0
214
+
215
+ with self.lock:
216
+ for _, metadata in self.items:
217
+ if metadata.should_ignore:
218
+ ignored_files += 1
219
+ continue
220
+ total_size += metadata.size
221
+ total_files += 1
222
+ if metadata.sha256 is not None:
223
+ nb_hashed += 1
224
+ size_hashed += metadata.size
225
+ if metadata.upload_mode == "lfs":
226
+ nb_lfs += 1
227
+ if metadata.upload_mode is None:
228
+ nb_lfs_unsure += 1
229
+ if metadata.is_uploaded:
230
+ nb_preuploaded += 1
231
+ size_preuploaded += metadata.size
232
+ if metadata.is_committed:
233
+ nb_committed += 1
234
+ size_committed += metadata.size
235
+ total_size_str = _format_size(total_size)
236
+
237
+ now = datetime.now()
238
+ now_str = now.strftime("%Y-%m-%d %H:%M:%S")
239
+ elapsed = now - self._started_at
240
+ elapsed_str = str(elapsed).split(".")[0] # remove milliseconds
241
+
242
+ message = "\n" + "-" * 10
243
+ message += f" {now_str} ({elapsed_str}) "
244
+ message += "-" * 10 + "\n"
245
+
246
+ message += "Files: "
247
+ message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | "
248
+ message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})"
249
+ if nb_lfs_unsure > 0:
250
+ message += f" (+{nb_lfs_unsure} unsure)"
251
+ message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})"
252
+ message += f" | ignored: {ignored_files}\n"
253
+
254
+ message += "Workers: "
255
+ message += f"hashing: {self.nb_workers_sha256} | "
256
+ message += f"get upload mode: {self.nb_workers_get_upload_mode} | "
257
+ message += f"pre-uploading: {self.nb_workers_preupload_lfs} | "
258
+ message += f"committing: {self.nb_workers_commit} | "
259
+ message += f"waiting: {self.nb_workers_waiting}\n"
260
+ message += "-" * 51
261
+
262
+ return message
263
+
264
+ def is_done(self) -> bool:
265
+ with self.lock:
266
+ return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items)
267
+
268
+
269
+ def _worker_job(
270
+ status: LargeUploadStatus,
271
+ api: "HfApi",
272
+ repo_id: str,
273
+ repo_type: str,
274
+ revision: str,
275
+ ):
276
+ """
277
+ Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded
278
+ and committed. If no tasks are available, the worker will wait for 10 seconds before checking again.
279
+
280
+ If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up.
281
+
282
+ Read `upload_large_folder` docstring for more information on how tasks are prioritized.
283
+ """
284
+ while True:
285
+ next_job: Optional[Tuple[WorkerJob, List[JOB_ITEM_T]]] = None
286
+
287
+ # Determine next task
288
+ next_job = _determine_next_job(status)
289
+ if next_job is None:
290
+ return
291
+ job, items = next_job
292
+
293
+ # Perform task
294
+ if job == WorkerJob.SHA256:
295
+ item = items[0] # single item
296
+ try:
297
+ _compute_sha256(item)
298
+ status.queue_get_upload_mode.put(item)
299
+ except KeyboardInterrupt:
300
+ raise
301
+ except Exception as e:
302
+ logger.error(f"Failed to compute sha256: {e}")
303
+ traceback.format_exc()
304
+ status.queue_sha256.put(item)
305
+
306
+ with status.lock:
307
+ status.nb_workers_sha256 -= 1
308
+
309
+ elif job == WorkerJob.GET_UPLOAD_MODE:
310
+ try:
311
+ _get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
312
+ except KeyboardInterrupt:
313
+ raise
314
+ except Exception as e:
315
+ logger.error(f"Failed to get upload mode: {e}")
316
+ traceback.format_exc()
317
+
318
+ # Items are either:
319
+ # - dropped (if should_ignore)
320
+ # - put in LFS queue (if LFS)
321
+ # - put in commit queue (if regular)
322
+ # - or put back (if error occurred).
323
+ for item in items:
324
+ _, metadata = item
325
+ if metadata.should_ignore:
326
+ continue
327
+ if metadata.upload_mode == "lfs":
328
+ status.queue_preupload_lfs.put(item)
329
+ elif metadata.upload_mode == "regular":
330
+ status.queue_commit.put(item)
331
+ else:
332
+ status.queue_get_upload_mode.put(item)
333
+
334
+ with status.lock:
335
+ status.nb_workers_get_upload_mode -= 1
336
+
337
+ elif job == WorkerJob.PREUPLOAD_LFS:
338
+ item = items[0] # single item
339
+ try:
340
+ _preupload_lfs(item, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
341
+ status.queue_commit.put(item)
342
+ except KeyboardInterrupt:
343
+ raise
344
+ except Exception as e:
345
+ logger.error(f"Failed to preupload LFS: {e}")
346
+ traceback.format_exc()
347
+ status.queue_preupload_lfs.put(item)
348
+
349
+ with status.lock:
350
+ status.nb_workers_preupload_lfs -= 1
351
+
352
+ elif job == WorkerJob.COMMIT:
353
+ try:
354
+ _commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
355
+ except KeyboardInterrupt:
356
+ raise
357
+ except Exception as e:
358
+ logger.error(f"Failed to commit: {e}")
359
+ traceback.format_exc()
360
+ for item in items:
361
+ status.queue_commit.put(item)
362
+ with status.lock:
363
+ status.last_commit_attempt = time.time()
364
+ status.nb_workers_commit -= 1
365
+
366
+ elif job == WorkerJob.WAIT:
367
+ time.sleep(WAITING_TIME_IF_NO_TASKS)
368
+ with status.lock:
369
+ status.nb_workers_waiting -= 1
370
+
371
+
372
+ def _determine_next_job(status: LargeUploadStatus) -> Optional[Tuple[WorkerJob, List[JOB_ITEM_T]]]:
373
+ with status.lock:
374
+ # 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file)
375
+ if (
376
+ status.nb_workers_commit == 0
377
+ and status.queue_commit.qsize() > 0
378
+ and status.last_commit_attempt is not None
379
+ and time.time() - status.last_commit_attempt > 5 * 60
380
+ ):
381
+ status.nb_workers_commit += 1
382
+ logger.debug("Job: commit (more than 5 minutes since last commit attempt)")
383
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
384
+
385
+ # 2. Commit if at least 100 files are ready to commit
386
+ elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150:
387
+ status.nb_workers_commit += 1
388
+ logger.debug("Job: commit (>100 files ready)")
389
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
390
+
391
+ # 3. Get upload mode if at least 10 files
392
+ elif status.queue_get_upload_mode.qsize() >= 10:
393
+ status.nb_workers_get_upload_mode += 1
394
+ logger.debug("Job: get upload mode (>10 files ready)")
395
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, 50))
396
+
397
+ # 4. Preupload LFS file if at least 1 file and no worker is preuploading LFS
398
+ elif status.queue_preupload_lfs.qsize() > 0 and status.nb_workers_preupload_lfs == 0:
399
+ status.nb_workers_preupload_lfs += 1
400
+ logger.debug("Job: preupload LFS (no other worker preuploading LFS)")
401
+ return (WorkerJob.PREUPLOAD_LFS, _get_one(status.queue_preupload_lfs))
402
+
403
+ # 5. Compute sha256 if at least 1 file and no worker is computing sha256
404
+ elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0:
405
+ status.nb_workers_sha256 += 1
406
+ logger.debug("Job: sha256 (no other worker computing sha256)")
407
+ return (WorkerJob.SHA256, _get_one(status.queue_sha256))
408
+
409
+ # 6. Get upload mode if at least 1 file and no worker is getting upload mode
410
+ elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0:
411
+ status.nb_workers_get_upload_mode += 1
412
+ logger.debug("Job: get upload mode (no other worker getting upload mode)")
413
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, 50))
414
+
415
+ # 7. Preupload LFS file if at least 1 file
416
+ # Skip if hf_transfer is enabled and there is already a worker preuploading LFS
417
+ elif status.queue_preupload_lfs.qsize() > 0 and (
418
+ status.nb_workers_preupload_lfs == 0 or not constants.HF_HUB_ENABLE_HF_TRANSFER
419
+ ):
420
+ status.nb_workers_preupload_lfs += 1
421
+ logger.debug("Job: preupload LFS")
422
+ return (WorkerJob.PREUPLOAD_LFS, _get_one(status.queue_preupload_lfs))
423
+
424
+ # 8. Compute sha256 if at least 1 file
425
+ elif status.queue_sha256.qsize() > 0:
426
+ status.nb_workers_sha256 += 1
427
+ logger.debug("Job: sha256")
428
+ return (WorkerJob.SHA256, _get_one(status.queue_sha256))
429
+
430
+ # 9. Get upload mode if at least 1 file
431
+ elif status.queue_get_upload_mode.qsize() > 0:
432
+ status.nb_workers_get_upload_mode += 1
433
+ logger.debug("Job: get upload mode")
434
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, 50))
435
+
436
+ # 10. Commit if at least 1 file and 1 min since last commit attempt
437
+ elif (
438
+ status.nb_workers_commit == 0
439
+ and status.queue_commit.qsize() > 0
440
+ and status.last_commit_attempt is not None
441
+ and time.time() - status.last_commit_attempt > 1 * 60
442
+ ):
443
+ status.nb_workers_commit += 1
444
+ logger.debug("Job: commit (1 min since last commit attempt)")
445
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
446
+
447
+ # 11. Commit if at least 1 file all other queues are empty and all workers are waiting
448
+ # e.g. when it's the last commit
449
+ elif (
450
+ status.nb_workers_commit == 0
451
+ and status.queue_commit.qsize() > 0
452
+ and status.queue_sha256.qsize() == 0
453
+ and status.queue_get_upload_mode.qsize() == 0
454
+ and status.queue_preupload_lfs.qsize() == 0
455
+ and status.nb_workers_sha256 == 0
456
+ and status.nb_workers_get_upload_mode == 0
457
+ and status.nb_workers_preupload_lfs == 0
458
+ ):
459
+ status.nb_workers_commit += 1
460
+ logger.debug("Job: commit")
461
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
462
+
463
+ # 12. If all queues are empty, exit
464
+ elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items):
465
+ logger.info("All files have been processed! Exiting worker.")
466
+ return None
467
+
468
+ # 13. If no task is available, wait
469
+ else:
470
+ status.nb_workers_waiting += 1
471
+ logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)")
472
+ return (WorkerJob.WAIT, [])
473
+
474
+
475
+ ####################
476
+ # Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit)
477
+ ####################
478
+
479
+
480
+ def _compute_sha256(item: JOB_ITEM_T) -> None:
481
+ """Compute sha256 of a file and save it in metadata."""
482
+ paths, metadata = item
483
+ if metadata.sha256 is None:
484
+ with paths.file_path.open("rb") as f:
485
+ metadata.sha256 = sha_fileobj(f).hex()
486
+ metadata.save(paths)
487
+
488
+
489
+ def _get_upload_mode(items: List[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
490
+ """Get upload mode for each file and update metadata.
491
+
492
+ Also receive info if the file should be ignored.
493
+ """
494
+ additions = [_build_hacky_operation(item) for item in items]
495
+ _fetch_upload_modes(
496
+ additions=additions,
497
+ repo_type=repo_type,
498
+ repo_id=repo_id,
499
+ headers=api._build_hf_headers(),
500
+ revision=revision,
501
+ )
502
+ for item, addition in zip(items, additions):
503
+ paths, metadata = item
504
+ metadata.upload_mode = addition._upload_mode
505
+ metadata.should_ignore = addition._should_ignore
506
+ metadata.save(paths)
507
+
508
+
509
+ def _preupload_lfs(item: JOB_ITEM_T, api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
510
+ """Preupload LFS file and update metadata."""
511
+ paths, metadata = item
512
+ addition = _build_hacky_operation(item)
513
+ api.preupload_lfs_files(
514
+ repo_id=repo_id,
515
+ repo_type=repo_type,
516
+ revision=revision,
517
+ additions=[addition],
518
+ )
519
+
520
+ metadata.is_uploaded = True
521
+ metadata.save(paths)
522
+
523
+
524
+ def _commit(items: List[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
525
+ """Commit files to the repo."""
526
+ additions = [_build_hacky_operation(item) for item in items]
527
+ api.create_commit(
528
+ repo_id=repo_id,
529
+ repo_type=repo_type,
530
+ revision=revision,
531
+ operations=additions,
532
+ commit_message="Add files using upload-large-folder tool",
533
+ )
534
+ for paths, metadata in items:
535
+ metadata.is_committed = True
536
+ metadata.save(paths)
537
+
538
+
539
+ ####################
540
+ # Hacks with CommitOperationAdd to bypass checks/sha256 calculation
541
+ ####################
542
+
543
+
544
+ class HackyCommitOperationAdd(CommitOperationAdd):
545
+ def __post_init__(self) -> None:
546
+ if isinstance(self.path_or_fileobj, Path):
547
+ self.path_or_fileobj = str(self.path_or_fileobj)
548
+
549
+
550
+ def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd:
551
+ paths, metadata = item
552
+ operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path)
553
+ with paths.file_path.open("rb") as file:
554
+ sample = file.peek(512)[:512]
555
+ if metadata.sha256 is None:
556
+ raise ValueError("sha256 must have been computed by now!")
557
+ operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample)
558
+ return operation
559
+
560
+
561
+ ####################
562
+ # Misc helpers
563
+ ####################
564
+
565
+
566
+ def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> List[JOB_ITEM_T]:
567
+ return [queue.get()]
568
+
569
+
570
+ def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> List[JOB_ITEM_T]:
571
+ return [queue.get() for _ in range(min(queue.qsize(), n))]
572
+
573
+
574
+ def _get_items_to_commit(queue: "queue.Queue[JOB_ITEM_T]") -> List[JOB_ITEM_T]:
575
+ """Special case for commit job: the number of items to commit depends on the type of files."""
576
+ # Can take at most 50 regular files and/or 100 LFS files in a single commit
577
+ items: List[JOB_ITEM_T] = []
578
+ nb_lfs, nb_regular = 0, 0
579
+ while True:
580
+ # If empty queue => commit everything
581
+ if queue.qsize() == 0:
582
+ return items
583
+
584
+ # If we have enough items => commit them
585
+ if nb_lfs >= MAX_NB_LFS_FILES_PER_COMMIT or nb_regular >= MAX_NB_REGULAR_FILES_PER_COMMIT:
586
+ return items
587
+
588
+ # Else, get a new item and increase counter
589
+ item = queue.get()
590
+ items.append(item)
591
+ _, metadata = item
592
+ if metadata.upload_mode == "lfs":
593
+ nb_lfs += 1
594
+ else:
595
+ nb_regular += 1
596
+
597
+
598
+ def _print_overwrite(report: str) -> None:
599
+ """Print a report, overwriting the previous lines.
600
+
601
+ Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout`
602
+ to print the report.
603
+
604
+ Note: works well only if no other process is writing to `sys.stdout`!
605
+ """
606
+ report += "\n"
607
+ # Get terminal width
608
+ terminal_width = shutil.get_terminal_size().columns
609
+
610
+ # Count number of lines that should be cleared
611
+ nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines())
612
+
613
+ # Clear previous lines based on the number of lines in the report
614
+ for _ in range(nb_lines):
615
+ sys.stdout.write("\r\033[K") # Clear line
616
+ sys.stdout.write("\033[F") # Move cursor up one line
617
+
618
+ # Print the new report, filling remaining space with whitespace
619
+ sys.stdout.write(report)
620
+ sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1])))
621
+ sys.stdout.flush()
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_webhooks_payload.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains data structures to parse the webhooks payload."""
16
+
17
+ from typing import List, Literal, Optional
18
+
19
+ from .utils import is_pydantic_available
20
+
21
+
22
+ if is_pydantic_available():
23
+ from pydantic import BaseModel
24
+ else:
25
+ # Define a dummy BaseModel to avoid import errors when pydantic is not installed
26
+ # Import error will be raised when trying to use the class
27
+
28
+ class BaseModel: # type: ignore [no-redef]
29
+ def __init__(self, *args, **kwargs) -> None:
30
+ raise ImportError(
31
+ "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that"
32
+ " should be installed separately. Please run `pip install --upgrade pydantic` and retry."
33
+ )
34
+
35
+
36
+ # This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they
37
+ # are not in used anymore. To keep in sync when format is updated in
38
+ # https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link).
39
+
40
+
41
+ WebhookEvent_T = Literal[
42
+ "create",
43
+ "delete",
44
+ "move",
45
+ "update",
46
+ ]
47
+ RepoChangeEvent_T = Literal[
48
+ "add",
49
+ "move",
50
+ "remove",
51
+ "update",
52
+ ]
53
+ RepoType_T = Literal[
54
+ "dataset",
55
+ "model",
56
+ "space",
57
+ ]
58
+ DiscussionStatus_T = Literal[
59
+ "closed",
60
+ "draft",
61
+ "open",
62
+ "merged",
63
+ ]
64
+ SupportedWebhookVersion = Literal[3]
65
+
66
+
67
+ class ObjectId(BaseModel):
68
+ id: str
69
+
70
+
71
+ class WebhookPayloadUrl(BaseModel):
72
+ web: str
73
+ api: Optional[str] = None
74
+
75
+
76
+ class WebhookPayloadMovedTo(BaseModel):
77
+ name: str
78
+ owner: ObjectId
79
+
80
+
81
+ class WebhookPayloadWebhook(ObjectId):
82
+ version: SupportedWebhookVersion
83
+
84
+
85
+ class WebhookPayloadEvent(BaseModel):
86
+ action: WebhookEvent_T
87
+ scope: str
88
+
89
+
90
+ class WebhookPayloadDiscussionChanges(BaseModel):
91
+ base: str
92
+ mergeCommitId: Optional[str] = None
93
+
94
+
95
+ class WebhookPayloadComment(ObjectId):
96
+ author: ObjectId
97
+ hidden: bool
98
+ content: Optional[str] = None
99
+ url: WebhookPayloadUrl
100
+
101
+
102
+ class WebhookPayloadDiscussion(ObjectId):
103
+ num: int
104
+ author: ObjectId
105
+ url: WebhookPayloadUrl
106
+ title: str
107
+ isPullRequest: bool
108
+ status: DiscussionStatus_T
109
+ changes: Optional[WebhookPayloadDiscussionChanges] = None
110
+ pinned: Optional[bool] = None
111
+
112
+
113
+ class WebhookPayloadRepo(ObjectId):
114
+ owner: ObjectId
115
+ head_sha: Optional[str] = None
116
+ name: str
117
+ private: bool
118
+ subdomain: Optional[str] = None
119
+ tags: Optional[List[str]] = None
120
+ type: Literal["dataset", "model", "space"]
121
+ url: WebhookPayloadUrl
122
+
123
+
124
+ class WebhookPayloadUpdatedRef(BaseModel):
125
+ ref: str
126
+ oldSha: Optional[str] = None
127
+ newSha: Optional[str] = None
128
+
129
+
130
+ class WebhookPayload(BaseModel):
131
+ event: WebhookPayloadEvent
132
+ repo: WebhookPayloadRepo
133
+ discussion: Optional[WebhookPayloadDiscussion] = None
134
+ comment: Optional[WebhookPayloadComment] = None
135
+ webhook: WebhookPayloadWebhook
136
+ movedTo: Optional[WebhookPayloadMovedTo] = None
137
+ updatedRefs: Optional[List[WebhookPayloadUpdatedRef]] = None
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/_webhooks_server.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains `WebhooksServer` and `webhook_endpoint` to create a webhook server easily."""
16
+
17
+ import atexit
18
+ import inspect
19
+ import os
20
+ from functools import wraps
21
+ from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
22
+
23
+ from .utils import experimental, is_fastapi_available, is_gradio_available
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ import gradio as gr
28
+ from fastapi import Request
29
+
30
+ if is_fastapi_available():
31
+ from fastapi import FastAPI, Request
32
+ from fastapi.responses import JSONResponse
33
+ else:
34
+ # Will fail at runtime if FastAPI is not available
35
+ FastAPI = Request = JSONResponse = None # type: ignore [misc, assignment]
36
+
37
+
38
+ _global_app: Optional["WebhooksServer"] = None
39
+ _is_local = os.environ.get("SPACE_ID") is None
40
+
41
+
42
+ @experimental
43
+ class WebhooksServer:
44
+ """
45
+ The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks.
46
+ These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to
47
+ the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `launch` method has to be
48
+ called to start the app.
49
+
50
+ It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic
51
+ model that contains all the information about the webhook event. The data will be parsed automatically for you.
52
+
53
+ Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to setup your
54
+ WebhooksServer and deploy it on a Space.
55
+
56
+ <Tip warning={true}>
57
+
58
+ `WebhooksServer` is experimental. Its API is subject to change in the future.
59
+
60
+ </Tip>
61
+
62
+ <Tip warning={true}>
63
+
64
+ You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
65
+
66
+ </Tip>
67
+
68
+ Args:
69
+ ui (`gradio.Blocks`, optional):
70
+ A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions
71
+ about the configured webhooks is created.
72
+ webhook_secret (`str`, optional):
73
+ A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as
74
+ you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You
75
+ can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the
76
+ webhook endpoints are opened without any security.
77
+
78
+ Example:
79
+
80
+ ```python
81
+ import gradio as gr
82
+ from huggingface_hub import WebhooksServer, WebhookPayload
83
+
84
+ with gr.Blocks() as ui:
85
+ ...
86
+
87
+ app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
88
+
89
+ @app.add_webhook("/say_hello")
90
+ async def hello(payload: WebhookPayload):
91
+ return {"message": "hello"}
92
+
93
+ app.launch()
94
+ ```
95
+ """
96
+
97
+ def __new__(cls, *args, **kwargs) -> "WebhooksServer":
98
+ if not is_gradio_available():
99
+ raise ImportError(
100
+ "You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`"
101
+ " first."
102
+ )
103
+ if not is_fastapi_available():
104
+ raise ImportError(
105
+ "You must have `fastapi` installed to use `WebhooksServer`. Please run `pip install --upgrade fastapi`"
106
+ " first."
107
+ )
108
+ return super().__new__(cls)
109
+
110
+ def __init__(
111
+ self,
112
+ ui: Optional["gr.Blocks"] = None,
113
+ webhook_secret: Optional[str] = None,
114
+ ) -> None:
115
+ self._ui = ui
116
+
117
+ self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET")
118
+ self.registered_webhooks: Dict[str, Callable] = {}
119
+ _warn_on_empty_secret(self.webhook_secret)
120
+
121
+ def add_webhook(self, path: Optional[str] = None) -> Callable:
122
+ """
123
+ Decorator to add a webhook to the [`WebhooksServer`] server.
124
+
125
+ Args:
126
+ path (`str`, optional):
127
+ The URL path to register the webhook function. If not provided, the function name will be used as the
128
+ path. In any case, all webhooks are registered under `/webhooks`.
129
+
130
+ Raises:
131
+ ValueError: If the provided path is already registered as a webhook.
132
+
133
+ Example:
134
+ ```python
135
+ from huggingface_hub import WebhooksServer, WebhookPayload
136
+
137
+ app = WebhooksServer()
138
+
139
+ @app.add_webhook
140
+ async def trigger_training(payload: WebhookPayload):
141
+ if payload.repo.type == "dataset" and payload.event.action == "update":
142
+ # Trigger a training job if a dataset is updated
143
+ ...
144
+
145
+ app.launch()
146
+ ```
147
+ """
148
+ # Usage: directly as decorator. Example: `@app.add_webhook`
149
+ if callable(path):
150
+ # If path is a function, it means it was used as a decorator without arguments
151
+ return self.add_webhook()(path)
152
+
153
+ # Usage: provide a path. Example: `@app.add_webhook(...)`
154
+ @wraps(FastAPI.post)
155
+ def _inner_post(*args, **kwargs):
156
+ func = args[0]
157
+ abs_path = f"/webhooks/{(path or func.__name__).strip('/')}"
158
+ if abs_path in self.registered_webhooks:
159
+ raise ValueError(f"Webhook {abs_path} already exists.")
160
+ self.registered_webhooks[abs_path] = func
161
+
162
+ return _inner_post
163
+
164
+ def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None:
165
+ """Launch the Gradio app and register webhooks to the underlying FastAPI server.
166
+
167
+ Input parameters are forwarded to Gradio when launching the app.
168
+ """
169
+ ui = self._ui or self._get_default_ui()
170
+
171
+ # Start Gradio App
172
+ # - as non-blocking so that webhooks can be added afterwards
173
+ # - as shared if launch locally (to debug webhooks)
174
+ launch_kwargs.setdefault("share", _is_local)
175
+ self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs)
176
+
177
+ # Register webhooks to FastAPI app
178
+ for path, func in self.registered_webhooks.items():
179
+ # Add secret check if required
180
+ if self.webhook_secret is not None:
181
+ func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret)
182
+
183
+ # Add route to FastAPI app
184
+ self.fastapi_app.post(path)(func)
185
+
186
+ # Print instructions and block main thread
187
+ space_host = os.environ.get("SPACE_HOST")
188
+ url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url)
189
+ url = url.strip("/")
190
+ message = "\nWebhooks are correctly setup and ready to use:"
191
+ message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks)
192
+ message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks."
193
+ print(message)
194
+
195
+ if not prevent_thread_lock:
196
+ ui.block_thread()
197
+
198
+ def _get_default_ui(self) -> "gr.Blocks":
199
+ """Default UI if not provided (lists webhooks and provides basic instructions)."""
200
+ import gradio as gr
201
+
202
+ with gr.Blocks() as ui:
203
+ gr.Markdown("# This is an app to process 🤗 Webhooks")
204
+ gr.Markdown(
205
+ "Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on"
206
+ " specific repos or to all repos belonging to particular set of users/organizations (not just your"
207
+ " repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to"
208
+ " know more about webhooks on the Huggingface Hub."
209
+ )
210
+ gr.Markdown(
211
+ f"{len(self.registered_webhooks)} webhook(s) are registered:"
212
+ + "\n\n"
213
+ + "\n ".join(
214
+ f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})"
215
+ for webhook_path, webhook in self.registered_webhooks.items()
216
+ )
217
+ )
218
+ gr.Markdown(
219
+ "Go to https://huggingface.co/settings/webhooks to setup your webhooks."
220
+ + "\nYou app is running locally. Please look at the logs to check the full URL you need to set."
221
+ if _is_local
222
+ else (
223
+ "\nThis app is running on a Space. You can find the corresponding URL in the options menu"
224
+ " (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'."
225
+ )
226
+ )
227
+ return ui
228
+
229
+
230
+ @experimental
231
+ def webhook_endpoint(path: Optional[str] = None) -> Callable:
232
+ """Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
233
+
234
+ This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret),
235
+ you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using
236
+ this decorator multiple times.
237
+
238
+ Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to setup your
239
+ server and deploy it on a Space.
240
+
241
+ <Tip warning={true}>
242
+
243
+ `webhook_endpoint` is experimental. Its API is subject to change in the future.
244
+
245
+ </Tip>
246
+
247
+ <Tip warning={true}>
248
+
249
+ You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
250
+
251
+ </Tip>
252
+
253
+ Args:
254
+ path (`str`, optional):
255
+ The URL path to register the webhook function. If not provided, the function name will be used as the path.
256
+ In any case, all webhooks are registered under `/webhooks`.
257
+
258
+ Examples:
259
+ The default usage is to register a function as a webhook endpoint. The function name will be used as the path.
260
+ The server will be started automatically at exit (i.e. at the end of the script).
261
+
262
+ ```python
263
+ from huggingface_hub import webhook_endpoint, WebhookPayload
264
+
265
+ @webhook_endpoint
266
+ async def trigger_training(payload: WebhookPayload):
267
+ if payload.repo.type == "dataset" and payload.event.action == "update":
268
+ # Trigger a training job if a dataset is updated
269
+ ...
270
+
271
+ # Server is automatically started at the end of the script.
272
+ ```
273
+
274
+ Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you
275
+ are running it in a notebook.
276
+
277
+ ```python
278
+ from huggingface_hub import webhook_endpoint, WebhookPayload
279
+
280
+ @webhook_endpoint
281
+ async def trigger_training(payload: WebhookPayload):
282
+ if payload.repo.type == "dataset" and payload.event.action == "update":
283
+ # Trigger a training job if a dataset is updated
284
+ ...
285
+
286
+ # Start the server manually
287
+ trigger_training.launch()
288
+ ```
289
+ """
290
+ if callable(path):
291
+ # If path is a function, it means it was used as a decorator without arguments
292
+ return webhook_endpoint()(path)
293
+
294
+ @wraps(WebhooksServer.add_webhook)
295
+ def _inner(func: Callable) -> Callable:
296
+ app = _get_global_app()
297
+ app.add_webhook(path)(func)
298
+ if len(app.registered_webhooks) == 1:
299
+ # Register `app.launch` to run at exit (only once)
300
+ atexit.register(app.launch)
301
+
302
+ @wraps(app.launch)
303
+ def _launch_now():
304
+ # Run the app directly (without waiting atexit)
305
+ atexit.unregister(app.launch)
306
+ app.launch()
307
+
308
+ func.launch = _launch_now # type: ignore
309
+ return func
310
+
311
+ return _inner
312
+
313
+
314
+ def _get_global_app() -> WebhooksServer:
315
+ global _global_app
316
+ if _global_app is None:
317
+ _global_app = WebhooksServer()
318
+ return _global_app
319
+
320
+
321
+ def _warn_on_empty_secret(webhook_secret: Optional[str]) -> None:
322
+ if webhook_secret is None:
323
+ print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.")
324
+ print(
325
+ "To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: "
326
+ "\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`"
327
+ )
328
+ print(
329
+ "For more details about webhook secrets, please refer to"
330
+ " https://huggingface.co/docs/hub/webhooks#webhook-secret."
331
+ )
332
+ else:
333
+ print("Webhook secret is correctly defined.")
334
+
335
+
336
+ def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str:
337
+ """Returns the anchor to a given webhook in the docs (experimental)"""
338
+ return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post"
339
+
340
+
341
+ def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable:
342
+ """Wraps a webhook function to check the webhook secret before calling the function.
343
+
344
+ This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route
345
+ parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request`
346
+ object (and hence the headers). A far cleaner solution would be to use a middleware. However, since
347
+ `fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by
348
+ Gradio internals (and not by us), we cannot add a middleware.
349
+
350
+ This method is called only when a secret has been defined by the user. If a request is sent without the
351
+ "x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect,
352
+ the function will return a 403 error (forbidden).
353
+
354
+ Inspired by https://stackoverflow.com/a/33112180.
355
+ """
356
+ initial_sig = inspect.signature(func)
357
+
358
+ @wraps(func)
359
+ async def _protected_func(request: Request, **kwargs):
360
+ request_secret = request.headers.get("x-webhook-secret")
361
+ if request_secret is None:
362
+ return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401)
363
+ if request_secret != webhook_secret:
364
+ return JSONResponse({"error": "Invalid webhook secret."}, status_code=403)
365
+
366
+ # Inject `request` in kwargs if required
367
+ if "request" in initial_sig.parameters:
368
+ kwargs["request"] = request
369
+
370
+ # Handle both sync and async routes
371
+ if inspect.iscoroutinefunction(func):
372
+ return await func(**kwargs)
373
+ else:
374
+ return func(**kwargs)
375
+
376
+ # Update signature to include request
377
+ if "request" not in initial_sig.parameters:
378
+ _protected_func.__signature__ = initial_sig.replace( # type: ignore
379
+ parameters=(
380
+ inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request),
381
+ )
382
+ + tuple(initial_sig.parameters.values())
383
+ )
384
+
385
+ # Return protected route
386
+ return _protected_func
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/community.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data structures to interact with Discussions and Pull Requests on the Hub.
3
+
4
+ See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions)
5
+ for more information on Pull Requests, Discussions, and the community tab.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+ from datetime import datetime
10
+ from typing import List, Literal, Optional, Union
11
+
12
+ from . import constants
13
+ from .utils import parse_datetime
14
+
15
+
16
+ DiscussionStatus = Literal["open", "closed", "merged", "draft"]
17
+
18
+
19
+ @dataclass
20
+ class Discussion:
21
+ """
22
+ A Discussion or Pull Request on the Hub.
23
+
24
+ This dataclass is not intended to be instantiated directly.
25
+
26
+ Attributes:
27
+ title (`str`):
28
+ The title of the Discussion / Pull Request
29
+ status (`str`):
30
+ The status of the Discussion / Pull Request.
31
+ It must be one of:
32
+ * `"open"`
33
+ * `"closed"`
34
+ * `"merged"` (only for Pull Requests )
35
+ * `"draft"` (only for Pull Requests )
36
+ num (`int`):
37
+ The number of the Discussion / Pull Request.
38
+ repo_id (`str`):
39
+ The id (`"{namespace}/{repo_name}"`) of the repo on which
40
+ the Discussion / Pull Request was open.
41
+ repo_type (`str`):
42
+ The type of the repo on which the Discussion / Pull Request was open.
43
+ Possible values are: `"model"`, `"dataset"`, `"space"`.
44
+ author (`str`):
45
+ The username of the Discussion / Pull Request author.
46
+ Can be `"deleted"` if the user has been deleted since.
47
+ is_pull_request (`bool`):
48
+ Whether or not this is a Pull Request.
49
+ created_at (`datetime`):
50
+ The `datetime` of creation of the Discussion / Pull Request.
51
+ endpoint (`str`):
52
+ Endpoint of the Hub. Default is https://huggingface.co.
53
+ git_reference (`str`, *optional*):
54
+ (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
55
+ url (`str`):
56
+ (property) URL of the discussion on the Hub.
57
+ """
58
+
59
+ title: str
60
+ status: DiscussionStatus
61
+ num: int
62
+ repo_id: str
63
+ repo_type: str
64
+ author: str
65
+ is_pull_request: bool
66
+ created_at: datetime
67
+ endpoint: str
68
+
69
+ @property
70
+ def git_reference(self) -> Optional[str]:
71
+ """
72
+ If this is a Pull Request , returns the git reference to which changes can be pushed.
73
+ Returns `None` otherwise.
74
+ """
75
+ if self.is_pull_request:
76
+ return f"refs/pr/{self.num}"
77
+ return None
78
+
79
+ @property
80
+ def url(self) -> str:
81
+ """Returns the URL of the discussion on the Hub."""
82
+ if self.repo_type is None or self.repo_type == constants.REPO_TYPE_MODEL:
83
+ return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}"
84
+ return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}"
85
+
86
+
87
+ @dataclass
88
+ class DiscussionWithDetails(Discussion):
89
+ """
90
+ Subclass of [`Discussion`].
91
+
92
+ Attributes:
93
+ title (`str`):
94
+ The title of the Discussion / Pull Request
95
+ status (`str`):
96
+ The status of the Discussion / Pull Request.
97
+ It can be one of:
98
+ * `"open"`
99
+ * `"closed"`
100
+ * `"merged"` (only for Pull Requests )
101
+ * `"draft"` (only for Pull Requests )
102
+ num (`int`):
103
+ The number of the Discussion / Pull Request.
104
+ repo_id (`str`):
105
+ The id (`"{namespace}/{repo_name}"`) of the repo on which
106
+ the Discussion / Pull Request was open.
107
+ repo_type (`str`):
108
+ The type of the repo on which the Discussion / Pull Request was open.
109
+ Possible values are: `"model"`, `"dataset"`, `"space"`.
110
+ author (`str`):
111
+ The username of the Discussion / Pull Request author.
112
+ Can be `"deleted"` if the user has been deleted since.
113
+ is_pull_request (`bool`):
114
+ Whether or not this is a Pull Request.
115
+ created_at (`datetime`):
116
+ The `datetime` of creation of the Discussion / Pull Request.
117
+ events (`list` of [`DiscussionEvent`])
118
+ The list of [`DiscussionEvents`] in this Discussion or Pull Request.
119
+ conflicting_files (`Union[List[str], bool, None]`, *optional*):
120
+ A list of conflicting files if this is a Pull Request.
121
+ `None` if `self.is_pull_request` is `False`.
122
+ `True` if there are conflicting files but the list can't be retrieved.
123
+ target_branch (`str`, *optional*):
124
+ The branch into which changes are to be merged if this is a
125
+ Pull Request . `None` if `self.is_pull_request` is `False`.
126
+ merge_commit_oid (`str`, *optional*):
127
+ If this is a merged Pull Request , this is set to the OID / SHA of
128
+ the merge commit, `None` otherwise.
129
+ diff (`str`, *optional*):
130
+ The git diff if this is a Pull Request , `None` otherwise.
131
+ endpoint (`str`):
132
+ Endpoint of the Hub. Default is https://huggingface.co.
133
+ git_reference (`str`, *optional*):
134
+ (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
135
+ url (`str`):
136
+ (property) URL of the discussion on the Hub.
137
+ """
138
+
139
+ events: List["DiscussionEvent"]
140
+ conflicting_files: Union[List[str], bool, None]
141
+ target_branch: Optional[str]
142
+ merge_commit_oid: Optional[str]
143
+ diff: Optional[str]
144
+
145
+
146
+ @dataclass
147
+ class DiscussionEvent:
148
+ """
149
+ An event in a Discussion or Pull Request.
150
+
151
+ Use concrete classes:
152
+ * [`DiscussionComment`]
153
+ * [`DiscussionStatusChange`]
154
+ * [`DiscussionCommit`]
155
+ * [`DiscussionTitleChange`]
156
+
157
+ Attributes:
158
+ id (`str`):
159
+ The ID of the event. An hexadecimal string.
160
+ type (`str`):
161
+ The type of the event.
162
+ created_at (`datetime`):
163
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
164
+ object holding the creation timestamp for the event.
165
+ author (`str`):
166
+ The username of the Discussion / Pull Request author.
167
+ Can be `"deleted"` if the user has been deleted since.
168
+ """
169
+
170
+ id: str
171
+ type: str
172
+ created_at: datetime
173
+ author: str
174
+
175
+ _event: dict
176
+ """Stores the original event data, in case we need to access it later."""
177
+
178
+
179
+ @dataclass
180
+ class DiscussionComment(DiscussionEvent):
181
+ """A comment in a Discussion / Pull Request.
182
+
183
+ Subclass of [`DiscussionEvent`].
184
+
185
+
186
+ Attributes:
187
+ id (`str`):
188
+ The ID of the event. An hexadecimal string.
189
+ type (`str`):
190
+ The type of the event.
191
+ created_at (`datetime`):
192
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
193
+ object holding the creation timestamp for the event.
194
+ author (`str`):
195
+ The username of the Discussion / Pull Request author.
196
+ Can be `"deleted"` if the user has been deleted since.
197
+ content (`str`):
198
+ The raw markdown content of the comment. Mentions, links and images are not rendered.
199
+ edited (`bool`):
200
+ Whether or not this comment has been edited.
201
+ hidden (`bool`):
202
+ Whether or not this comment has been hidden.
203
+ """
204
+
205
+ content: str
206
+ edited: bool
207
+ hidden: bool
208
+
209
+ @property
210
+ def rendered(self) -> str:
211
+ """The rendered comment, as a HTML string"""
212
+ return self._event["data"]["latest"]["html"]
213
+
214
+ @property
215
+ def last_edited_at(self) -> datetime:
216
+ """The last edit time, as a `datetime` object."""
217
+ return parse_datetime(self._event["data"]["latest"]["updatedAt"])
218
+
219
+ @property
220
+ def last_edited_by(self) -> str:
221
+ """The last edit time, as a `datetime` object."""
222
+ return self._event["data"]["latest"].get("author", {}).get("name", "deleted")
223
+
224
+ @property
225
+ def edit_history(self) -> List[dict]:
226
+ """The edit history of the comment"""
227
+ return self._event["data"]["history"]
228
+
229
+ @property
230
+ def number_of_edits(self) -> int:
231
+ return len(self.edit_history)
232
+
233
+
234
+ @dataclass
235
+ class DiscussionStatusChange(DiscussionEvent):
236
+ """A change of status in a Discussion / Pull Request.
237
+
238
+ Subclass of [`DiscussionEvent`].
239
+
240
+ Attributes:
241
+ id (`str`):
242
+ The ID of the event. An hexadecimal string.
243
+ type (`str`):
244
+ The type of the event.
245
+ created_at (`datetime`):
246
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
247
+ object holding the creation timestamp for the event.
248
+ author (`str`):
249
+ The username of the Discussion / Pull Request author.
250
+ Can be `"deleted"` if the user has been deleted since.
251
+ new_status (`str`):
252
+ The status of the Discussion / Pull Request after the change.
253
+ It can be one of:
254
+ * `"open"`
255
+ * `"closed"`
256
+ * `"merged"` (only for Pull Requests )
257
+ """
258
+
259
+ new_status: str
260
+
261
+
262
+ @dataclass
263
+ class DiscussionCommit(DiscussionEvent):
264
+ """A commit in a Pull Request.
265
+
266
+ Subclass of [`DiscussionEvent`].
267
+
268
+ Attributes:
269
+ id (`str`):
270
+ The ID of the event. An hexadecimal string.
271
+ type (`str`):
272
+ The type of the event.
273
+ created_at (`datetime`):
274
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
275
+ object holding the creation timestamp for the event.
276
+ author (`str`):
277
+ The username of the Discussion / Pull Request author.
278
+ Can be `"deleted"` if the user has been deleted since.
279
+ summary (`str`):
280
+ The summary of the commit.
281
+ oid (`str`):
282
+ The OID / SHA of the commit, as a hexadecimal string.
283
+ """
284
+
285
+ summary: str
286
+ oid: str
287
+
288
+
289
+ @dataclass
290
+ class DiscussionTitleChange(DiscussionEvent):
291
+ """A rename event in a Discussion / Pull Request.
292
+
293
+ Subclass of [`DiscussionEvent`].
294
+
295
+ Attributes:
296
+ id (`str`):
297
+ The ID of the event. An hexadecimal string.
298
+ type (`str`):
299
+ The type of the event.
300
+ created_at (`datetime`):
301
+ A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
302
+ object holding the creation timestamp for the event.
303
+ author (`str`):
304
+ The username of the Discussion / Pull Request author.
305
+ Can be `"deleted"` if the user has been deleted since.
306
+ old_title (`str`):
307
+ The previous title for the Discussion / Pull Request.
308
+ new_title (`str`):
309
+ The new title.
310
+ """
311
+
312
+ old_title: str
313
+ new_title: str
314
+
315
+
316
+ def deserialize_event(event: dict) -> DiscussionEvent:
317
+ """Instantiates a [`DiscussionEvent`] from a dict"""
318
+ event_id: str = event["id"]
319
+ event_type: str = event["type"]
320
+ created_at = parse_datetime(event["createdAt"])
321
+
322
+ common_args = dict(
323
+ id=event_id,
324
+ type=event_type,
325
+ created_at=created_at,
326
+ author=event.get("author", {}).get("name", "deleted"),
327
+ _event=event,
328
+ )
329
+
330
+ if event_type == "comment":
331
+ return DiscussionComment(
332
+ **common_args,
333
+ edited=event["data"]["edited"],
334
+ hidden=event["data"]["hidden"],
335
+ content=event["data"]["latest"]["raw"],
336
+ )
337
+ if event_type == "status-change":
338
+ return DiscussionStatusChange(
339
+ **common_args,
340
+ new_status=event["data"]["status"],
341
+ )
342
+ if event_type == "commit":
343
+ return DiscussionCommit(
344
+ **common_args,
345
+ summary=event["data"]["subject"],
346
+ oid=event["data"]["oid"],
347
+ )
348
+ if event_type == "title-change":
349
+ return DiscussionTitleChange(
350
+ **common_args,
351
+ old_title=event["data"]["from"],
352
+ new_title=event["data"]["to"],
353
+ )
354
+
355
+ return DiscussionEvent(**common_args)
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/constants.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import typing
4
+ from typing import Literal, Optional, Tuple
5
+
6
+
7
+ # Possible values for env variables
8
+
9
+
10
+ ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
11
+ ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
12
+
13
+
14
+ def _is_true(value: Optional[str]) -> bool:
15
+ if value is None:
16
+ return False
17
+ return value.upper() in ENV_VARS_TRUE_VALUES
18
+
19
+
20
+ def _as_int(value: Optional[str]) -> Optional[int]:
21
+ if value is None:
22
+ return None
23
+ return int(value)
24
+
25
+
26
+ # Constants for file downloads
27
+
28
+ PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"
29
+ TF2_WEIGHTS_NAME = "tf_model.h5"
30
+ TF_WEIGHTS_NAME = "model.ckpt"
31
+ FLAX_WEIGHTS_NAME = "flax_model.msgpack"
32
+ CONFIG_NAME = "config.json"
33
+ REPOCARD_NAME = "README.md"
34
+ DEFAULT_ETAG_TIMEOUT = 10
35
+ DEFAULT_DOWNLOAD_TIMEOUT = 10
36
+ DEFAULT_REQUEST_TIMEOUT = 10
37
+ DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024
38
+ HF_TRANSFER_CONCURRENCY = 100
39
+
40
+ # Constants for serialization
41
+
42
+ PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead
43
+ SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"
44
+ TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
45
+
46
+ # Constants for safetensors repos
47
+
48
+ SAFETENSORS_SINGLE_FILE = "model.safetensors"
49
+ SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"
50
+ SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
51
+
52
+ # Timeout of aquiring file lock and logging the attempt
53
+ FILELOCK_LOG_EVERY_SECONDS = 10
54
+
55
+ # Git-related constants
56
+
57
+ DEFAULT_REVISION = "main"
58
+ REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
59
+
60
+ HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
61
+
62
+ _staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
63
+
64
+ _HF_DEFAULT_ENDPOINT = "https://huggingface.co"
65
+ _HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
66
+ ENDPOINT = os.getenv("HF_ENDPOINT") or (_HF_DEFAULT_STAGING_ENDPOINT if _staging_mode else _HF_DEFAULT_ENDPOINT)
67
+
68
+ HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
69
+ HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
70
+ HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
71
+ HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
72
+
73
+ INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
74
+
75
+ # See https://huggingface.co/docs/inference-endpoints/index
76
+ INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
77
+
78
+
79
+ REPO_ID_SEPARATOR = "--"
80
+ # ^ this substring is not allowed in repo_ids on hf.co
81
+ # and is the canonical one we use for serialization of repo ids elsewhere.
82
+
83
+
84
+ REPO_TYPE_DATASET = "dataset"
85
+ REPO_TYPE_SPACE = "space"
86
+ REPO_TYPE_MODEL = "model"
87
+ REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]
88
+ SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
89
+
90
+ REPO_TYPES_URL_PREFIXES = {
91
+ REPO_TYPE_DATASET: "datasets/",
92
+ REPO_TYPE_SPACE: "spaces/",
93
+ }
94
+ REPO_TYPES_MAPPING = {
95
+ "datasets": REPO_TYPE_DATASET,
96
+ "spaces": REPO_TYPE_SPACE,
97
+ "models": REPO_TYPE_MODEL,
98
+ }
99
+
100
+ DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]
101
+ DISCUSSION_TYPES: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)
102
+ DiscussionStatusFilter = Literal["all", "open", "closed"]
103
+ DISCUSSION_STATUS: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
104
+
105
+ # Webhook subscription types
106
+ WEBHOOK_DOMAIN_T = Literal["repo", "discussions"]
107
+
108
+ # default cache
109
+ default_home = os.path.join(os.path.expanduser("~"), ".cache")
110
+ HF_HOME = os.path.expanduser(
111
+ os.getenv(
112
+ "HF_HOME",
113
+ os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"),
114
+ )
115
+ )
116
+ hf_cache_home = HF_HOME # for backward compatibility. TODO: remove this in 1.0.0
117
+
118
+ default_cache_path = os.path.join(HF_HOME, "hub")
119
+ default_assets_cache_path = os.path.join(HF_HOME, "assets")
120
+
121
+ # Legacy env variables
122
+ HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)
123
+ HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
124
+
125
+ # New env variables
126
+ HF_HUB_CACHE = os.getenv("HF_HUB_CACHE", HUGGINGFACE_HUB_CACHE)
127
+ HF_ASSETS_CACHE = os.getenv("HF_ASSETS_CACHE", HUGGINGFACE_ASSETS_CACHE)
128
+
129
+ HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
130
+
131
+ # Opt-out from telemetry requests
132
+ HF_HUB_DISABLE_TELEMETRY = (
133
+ _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable
134
+ or _is_true(os.environ.get("DISABLE_TELEMETRY"))
135
+ or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
136
+ )
137
+
138
+ # In the past, token was stored in a hardcoded location
139
+ # `_OLD_HF_TOKEN_PATH` is deprecated and will be removed "at some point".
140
+ # See https://github.com/huggingface/huggingface_hub/issues/1232
141
+ _OLD_HF_TOKEN_PATH = os.path.expanduser("~/.huggingface/token")
142
+ HF_TOKEN_PATH = os.environ.get("HF_TOKEN_PATH", os.path.join(HF_HOME, "token"))
143
+ HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
144
+
145
+ if _staging_mode:
146
+ # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
147
+ _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
148
+ HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
149
+ _OLD_HF_TOKEN_PATH = os.path.join(_staging_home, "_old_token")
150
+ HF_TOKEN_PATH = os.path.join(_staging_home, "token")
151
+
152
+ # Here, `True` will disable progress bars globally without possibility of enabling it
153
+ # programmatically. `False` will enable them without possibility of disabling them.
154
+ # If environment variable is not set (None), then the user is free to enable/disable
155
+ # them programmatically.
156
+ # TL;DR: env variable has priority over code
157
+ __HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
158
+ HF_HUB_DISABLE_PROGRESS_BARS: Optional[bool] = (
159
+ _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None
160
+ )
161
+
162
+ # Disable warning on machines that do not support symlinks (e.g. Windows non-developer)
163
+ HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
164
+
165
+ # Disable warning when using experimental features
166
+ HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
167
+
168
+ # Disable sending the cached token by default is all HTTP requests to the Hub
169
+ HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
170
+
171
+ # Enable fast-download using external dependency "hf_transfer"
172
+ # See:
173
+ # - https://pypi.org/project/hf-transfer/
174
+ # - https://github.com/huggingface/hf_transfer (private)
175
+ HF_HUB_ENABLE_HF_TRANSFER: bool = _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER"))
176
+
177
+
178
+ # UNUSED
179
+ # We don't use symlinks in local dir anymore.
180
+ HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD: int = (
181
+ _as_int(os.environ.get("HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD")) or 5 * 1024 * 1024
182
+ )
183
+
184
+ # Used to override the etag timeout on a system level
185
+ HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
186
+
187
+ # Used to override the get request timeout on a system level
188
+ HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
189
+
190
+ # List frameworks that are handled by the InferenceAPI service. Useful to scan endpoints and check which models are
191
+ # deployed and running. Since 95% of the models are using the top 4 frameworks listed below, we scan only those by
192
+ # default. We still keep the full list of supported frameworks in case we want to scan all of them.
193
+ MAIN_INFERENCE_API_FRAMEWORKS = [
194
+ "diffusers",
195
+ "sentence-transformers",
196
+ "text-generation-inference",
197
+ "transformers",
198
+ ]
199
+
200
+ ALL_INFERENCE_API_FRAMEWORKS = MAIN_INFERENCE_API_FRAMEWORKS + [
201
+ "adapter-transformers",
202
+ "allennlp",
203
+ "asteroid",
204
+ "bertopic",
205
+ "doctr",
206
+ "espnet",
207
+ "fairseq",
208
+ "fastai",
209
+ "fasttext",
210
+ "flair",
211
+ "k2",
212
+ "keras",
213
+ "mindspore",
214
+ "nemo",
215
+ "open_clip",
216
+ "paddlenlp",
217
+ "peft",
218
+ "pyannote-audio",
219
+ "sklearn",
220
+ "spacy",
221
+ "span-marker",
222
+ "speechbrain",
223
+ "stanza",
224
+ "timm",
225
+ ]
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/errors.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains all custom errors."""
2
+
3
+ from pathlib import Path
4
+ from typing import Optional, Union
5
+
6
+ from requests import HTTPError, Response
7
+
8
+
9
+ # CACHE ERRORS
10
+
11
+
12
+ class CacheNotFound(Exception):
13
+ """Exception thrown when the Huggingface cache is not found."""
14
+
15
+ cache_dir: Union[str, Path]
16
+
17
+ def __init__(self, msg: str, cache_dir: Union[str, Path], *args, **kwargs):
18
+ super().__init__(msg, *args, **kwargs)
19
+ self.cache_dir = cache_dir
20
+
21
+
22
+ class CorruptedCacheException(Exception):
23
+ """Exception for any unexpected structure in the Huggingface cache-system."""
24
+
25
+
26
+ # HEADERS ERRORS
27
+
28
+
29
+ class LocalTokenNotFoundError(EnvironmentError):
30
+ """Raised if local token is required but not found."""
31
+
32
+
33
+ # HTTP ERRORS
34
+
35
+
36
+ class OfflineModeIsEnabled(ConnectionError):
37
+ """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""
38
+
39
+
40
+ class HfHubHTTPError(HTTPError):
41
+ """
42
+ HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
43
+
44
+ Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
45
+ sent back by the server, it will be added to the error message.
46
+
47
+ Added details:
48
+ - Request id from "X-Request-Id" header if exists. If not, fallback to "X-Amzn-Trace-Id" header if exists.
49
+ - Server error message from the header "X-Error-Message".
50
+ - Server error message if we can found one in the response body.
51
+
52
+ Example:
53
+ ```py
54
+ import requests
55
+ from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
56
+
57
+ response = get_session().post(...)
58
+ try:
59
+ hf_raise_for_status(response)
60
+ except HfHubHTTPError as e:
61
+ print(str(e)) # formatted message
62
+ e.request_id, e.server_message # details returned by server
63
+
64
+ # Complete the error message with additional information once it's raised
65
+ e.append_to_message("\n`create_commit` expects the repository to exist.")
66
+ raise
67
+ ```
68
+ """
69
+
70
+ def __init__(self, message: str, response: Optional[Response] = None, *, server_message: Optional[str] = None):
71
+ self.request_id = (
72
+ response.headers.get("x-request-id") or response.headers.get("X-Amzn-Trace-Id")
73
+ if response is not None
74
+ else None
75
+ )
76
+ self.server_message = server_message
77
+
78
+ super().__init__(
79
+ message,
80
+ response=response, # type: ignore [arg-type]
81
+ request=response.request if response is not None else None, # type: ignore [arg-type]
82
+ )
83
+
84
+ def append_to_message(self, additional_message: str) -> None:
85
+ """Append additional information to the `HfHubHTTPError` initial message."""
86
+ self.args = (self.args[0] + additional_message,) + self.args[1:]
87
+
88
+
89
+ # INFERENCE CLIENT ERRORS
90
+
91
+
92
+ class InferenceTimeoutError(HTTPError, TimeoutError):
93
+ """Error raised when a model is unavailable or the request times out."""
94
+
95
+
96
+ # INFERENCE ENDPOINT ERRORS
97
+
98
+
99
+ class InferenceEndpointError(Exception):
100
+ """Generic exception when dealing with Inference Endpoints."""
101
+
102
+
103
+ class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
104
+ """Exception for timeouts while waiting for Inference Endpoint."""
105
+
106
+
107
+ # SAFETENSORS ERRORS
108
+
109
+
110
+ class SafetensorsParsingError(Exception):
111
+ """Raised when failing to parse a safetensors file metadata.
112
+
113
+ This can be the case if the file is not a safetensors file or does not respect the specification.
114
+ """
115
+
116
+
117
+ class NotASafetensorsRepoError(Exception):
118
+ """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
119
+ `model.safetensors.index.json` file.
120
+ """
121
+
122
+
123
+ # TEXT GENERATION ERRORS
124
+
125
+
126
+ class TextGenerationError(HTTPError):
127
+ """Generic error raised if text-generation went wrong."""
128
+
129
+
130
+ # Text Generation Inference Errors
131
+ class ValidationError(TextGenerationError):
132
+ """Server-side validation error."""
133
+
134
+
135
+ class GenerationError(TextGenerationError):
136
+ pass
137
+
138
+
139
+ class OverloadedError(TextGenerationError):
140
+ pass
141
+
142
+
143
+ class IncompleteGenerationError(TextGenerationError):
144
+ pass
145
+
146
+
147
+ class UnknownError(TextGenerationError):
148
+ pass
149
+
150
+
151
+ # VALIDATION ERRORS
152
+
153
+
154
+ class HFValidationError(ValueError):
155
+ """Generic exception thrown by `huggingface_hub` validators.
156
+
157
+ Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
158
+ """
159
+
160
+
161
+ # FILE METADATA ERRORS
162
+
163
+
164
+ class FileMetadataError(OSError):
165
+ """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
166
+
167
+ Inherits from `OSError` for backward compatibility.
168
+ """
169
+
170
+
171
+ # REPOSITORY ERRORS
172
+
173
+
174
+ class RepositoryNotFoundError(HfHubHTTPError):
175
+ """
176
+ Raised when trying to access a hf.co URL with an invalid repository name, or
177
+ with a private repo name the user does not have access to.
178
+
179
+ Example:
180
+
181
+ ```py
182
+ >>> from huggingface_hub import model_info
183
+ >>> model_info("<non_existent_repository>")
184
+ (...)
185
+ huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
186
+
187
+ Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
188
+ Please make sure you specified the correct `repo_id` and `repo_type`.
189
+ If the repo is private, make sure you are authenticated.
190
+ Invalid username or password.
191
+ ```
192
+ """
193
+
194
+
195
+ class GatedRepoError(RepositoryNotFoundError):
196
+ """
197
+ Raised when trying to access a gated repository for which the user is not on the
198
+ authorized list.
199
+
200
+ Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
201
+
202
+ Example:
203
+
204
+ ```py
205
+ >>> from huggingface_hub import model_info
206
+ >>> model_info("<gated_repository>")
207
+ (...)
208
+ huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
209
+
210
+ Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
211
+ Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
212
+ Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
213
+ ```
214
+ """
215
+
216
+
217
+ class DisabledRepoError(HfHubHTTPError):
218
+ """
219
+ Raised when trying to access a repository that has been disabled by its author.
220
+
221
+ Example:
222
+
223
+ ```py
224
+ >>> from huggingface_hub import dataset_info
225
+ >>> dataset_info("laion/laion-art")
226
+ (...)
227
+ huggingface_hub.utils._errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
228
+
229
+ Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
230
+ Access to this resource is disabled.
231
+ ```
232
+ """
233
+
234
+
235
+ # REVISION ERROR
236
+
237
+
238
+ class RevisionNotFoundError(HfHubHTTPError):
239
+ """
240
+ Raised when trying to access a hf.co URL with a valid repository but an invalid
241
+ revision.
242
+
243
+ Example:
244
+
245
+ ```py
246
+ >>> from huggingface_hub import hf_hub_download
247
+ >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
248
+ (...)
249
+ huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
250
+
251
+ Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
252
+ ```
253
+ """
254
+
255
+
256
+ # ENTRY ERRORS
257
+ class EntryNotFoundError(HfHubHTTPError):
258
+ """
259
+ Raised when trying to access a hf.co URL with a valid repository and revision
260
+ but an invalid filename.
261
+
262
+ Example:
263
+
264
+ ```py
265
+ >>> from huggingface_hub import hf_hub_download
266
+ >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
267
+ (...)
268
+ huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
269
+
270
+ Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
271
+ ```
272
+ """
273
+
274
+
275
+ class LocalEntryNotFoundError(EntryNotFoundError, FileNotFoundError, ValueError):
276
+ """
277
+ Raised when trying to access a file or snapshot that is not on the disk when network is
278
+ disabled or unavailable (connection issue). The entry may exist on the Hub.
279
+
280
+ Note: `ValueError` type is to ensure backward compatibility.
281
+ Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError`
282
+ even when it is not a network issue.
283
+
284
+ Example:
285
+
286
+ ```py
287
+ >>> from huggingface_hub import hf_hub_download
288
+ >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
289
+ (...)
290
+ huggingface_hub.utils._errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.
291
+ ```
292
+ """
293
+
294
+ def __init__(self, message: str):
295
+ super().__init__(message, response=None)
296
+
297
+
298
+ # REQUEST ERROR
299
+ class BadRequestError(HfHubHTTPError, ValueError):
300
+ """
301
+ Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
302
+
303
+ Example:
304
+
305
+ ```py
306
+ >>> resp = requests.post("hf.co/api/check", ...)
307
+ >>> hf_raise_for_status(resp, endpoint_name="check")
308
+ huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
309
+ ```
310
+ """
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/fastai_utils.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ from pickle import DEFAULT_PROTOCOL, PicklingError
5
+ from typing import Any, Dict, List, Optional, Union
6
+
7
+ from packaging import version
8
+
9
+ from huggingface_hub import constants, snapshot_download
10
+ from huggingface_hub.hf_api import HfApi
11
+ from huggingface_hub.utils import (
12
+ SoftTemporaryDirectory,
13
+ get_fastai_version,
14
+ get_fastcore_version,
15
+ get_python_version,
16
+ )
17
+
18
+ from .utils import logging, validate_hf_hub_args
19
+ from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility...
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ def _check_fastai_fastcore_versions(
26
+ fastai_min_version: str = "2.4",
27
+ fastcore_min_version: str = "1.3.27",
28
+ ):
29
+ """
30
+ Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
31
+
32
+ Args:
33
+ fastai_min_version (`str`, *optional*):
34
+ The minimum fastai version supported.
35
+ fastcore_min_version (`str`, *optional*):
36
+ The minimum fastcore version supported.
37
+
38
+ <Tip>
39
+ Raises the following error:
40
+
41
+ - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
42
+ if the fastai or fastcore libraries are not available or are of an invalid version.
43
+
44
+ </Tip>
45
+ """
46
+
47
+ if (get_fastcore_version() or get_fastai_version()) == "N/A":
48
+ raise ImportError(
49
+ f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are"
50
+ f" required. Currently using fastai=={get_fastai_version()} and"
51
+ f" fastcore=={get_fastcore_version()}."
52
+ )
53
+
54
+ current_fastai_version = version.Version(get_fastai_version())
55
+ current_fastcore_version = version.Version(get_fastcore_version())
56
+
57
+ if current_fastai_version < version.Version(fastai_min_version):
58
+ raise ImportError(
59
+ "`push_to_hub_fastai` and `from_pretrained_fastai` require a"
60
+ f" fastai>={fastai_min_version} version, but you are using fastai version"
61
+ f" {get_fastai_version()} which is incompatible. Upgrade with `pip install"
62
+ " fastai==2.5.6`."
63
+ )
64
+
65
+ if current_fastcore_version < version.Version(fastcore_min_version):
66
+ raise ImportError(
67
+ "`push_to_hub_fastai` and `from_pretrained_fastai` require a"
68
+ f" fastcore>={fastcore_min_version} version, but you are using fastcore"
69
+ f" version {get_fastcore_version()} which is incompatible. Upgrade with"
70
+ " `pip install fastcore==1.3.27`."
71
+ )
72
+
73
+
74
+ def _check_fastai_fastcore_pyproject_versions(
75
+ storage_folder: str,
76
+ fastai_min_version: str = "2.4",
77
+ fastcore_min_version: str = "1.3.27",
78
+ ):
79
+ """
80
+ Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
81
+ that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
82
+ or does not contain versions for fastai and fastcore, then it logs a warning.
83
+
84
+ Args:
85
+ storage_folder (`str`):
86
+ Folder to look for the `pyproject.toml` file.
87
+ fastai_min_version (`str`, *optional*):
88
+ The minimum fastai version supported.
89
+ fastcore_min_version (`str`, *optional*):
90
+ The minimum fastcore version supported.
91
+
92
+ <Tip>
93
+ Raises the following errors:
94
+
95
+ - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
96
+ if the `toml` module is not installed.
97
+ - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
98
+ if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
99
+
100
+ </Tip>
101
+ """
102
+
103
+ try:
104
+ import toml
105
+ except ModuleNotFoundError:
106
+ raise ImportError(
107
+ "`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module."
108
+ " Install it with `pip install toml`."
109
+ )
110
+
111
+ # Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages.
112
+ if not os.path.isfile(f"{storage_folder}/pyproject.toml"):
113
+ logger.warning(
114
+ "There is no `pyproject.toml` in the repository that contains the fastai"
115
+ " `Learner`. The `pyproject.toml` would allow us to verify that your fastai"
116
+ " and fastcore versions are compatible with those of the model you want to"
117
+ " load."
118
+ )
119
+ return
120
+ pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
121
+
122
+ if "build-system" not in pyproject_toml.keys():
123
+ logger.warning(
124
+ "There is no `build-system` section in the pyproject.toml of the repository"
125
+ " that contains the fastai `Learner`. The `build-system` would allow us to"
126
+ " verify that your fastai and fastcore versions are compatible with those"
127
+ " of the model you want to load."
128
+ )
129
+ return
130
+ build_system_toml = pyproject_toml["build-system"]
131
+
132
+ if "requires" not in build_system_toml.keys():
133
+ logger.warning(
134
+ "There is no `requires` section in the pyproject.toml of the repository"
135
+ " that contains the fastai `Learner`. The `requires` would allow us to"
136
+ " verify that your fastai and fastcore versions are compatible with those"
137
+ " of the model you want to load."
138
+ )
139
+ return
140
+ package_versions = build_system_toml["requires"]
141
+
142
+ # Extracts contains fastai and fastcore versions from `pyproject.toml` if available.
143
+ # If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest.
144
+ fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")]
145
+ if len(fastai_packages) == 0:
146
+ logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.")
147
+ # fastai_version is an empty string if not specified
148
+ else:
149
+ fastai_version = str(fastai_packages[0]).partition("=")[2]
150
+ if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version):
151
+ raise ImportError(
152
+ "`from_pretrained_fastai` requires"
153
+ f" fastai>={fastai_min_version} version but the model to load uses"
154
+ f" {fastai_version} which is incompatible."
155
+ )
156
+
157
+ fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")]
158
+ if len(fastcore_packages) == 0:
159
+ logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.")
160
+ # fastcore_version is an empty string if not specified
161
+ else:
162
+ fastcore_version = str(fastcore_packages[0]).partition("=")[2]
163
+ if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version):
164
+ raise ImportError(
165
+ "`from_pretrained_fastai` requires"
166
+ f" fastcore>={fastcore_min_version} version, but you are using fastcore"
167
+ f" version {fastcore_version} which is incompatible."
168
+ )
169
+
170
+
171
+ README_TEMPLATE = """---
172
+ tags:
173
+ - fastai
174
+ ---
175
+
176
+ # Amazing!
177
+
178
+ 🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
179
+
180
+ # Some next steps
181
+ 1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
182
+
183
+ 2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
184
+
185
+ 3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
186
+
187
+ Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
188
+
189
+
190
+ ---
191
+
192
+
193
+ # Model card
194
+
195
+ ## Model description
196
+ More information needed
197
+
198
+ ## Intended uses & limitations
199
+ More information needed
200
+
201
+ ## Training and evaluation data
202
+ More information needed
203
+ """
204
+
205
+ PYPROJECT_TEMPLATE = f"""[build-system]
206
+ requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
207
+ build-backend = "setuptools.build_meta:__legacy__"
208
+ """
209
+
210
+
211
+ def _create_model_card(repo_dir: Path):
212
+ """
213
+ Creates a model card for the repository.
214
+
215
+ Args:
216
+ repo_dir (`Path`):
217
+ Directory where model card is created.
218
+ """
219
+ readme_path = repo_dir / "README.md"
220
+
221
+ if not readme_path.exists():
222
+ with readme_path.open("w", encoding="utf-8") as f:
223
+ f.write(README_TEMPLATE)
224
+
225
+
226
+ def _create_model_pyproject(repo_dir: Path):
227
+ """
228
+ Creates a `pyproject.toml` for the repository.
229
+
230
+ Args:
231
+ repo_dir (`Path`):
232
+ Directory where `pyproject.toml` is created.
233
+ """
234
+ pyproject_path = repo_dir / "pyproject.toml"
235
+
236
+ if not pyproject_path.exists():
237
+ with pyproject_path.open("w", encoding="utf-8") as f:
238
+ f.write(PYPROJECT_TEMPLATE)
239
+
240
+
241
+ def _save_pretrained_fastai(
242
+ learner,
243
+ save_directory: Union[str, Path],
244
+ config: Optional[Dict[str, Any]] = None,
245
+ ):
246
+ """
247
+ Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
248
+
249
+ Args:
250
+ learner (`Learner`):
251
+ The `fastai.Learner` you'd like to save.
252
+ save_directory (`str` or `Path`):
253
+ Specific directory in which you want to save the fastai learner.
254
+ config (`dict`, *optional*):
255
+ Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
256
+
257
+ <Tip>
258
+
259
+ Raises the following error:
260
+
261
+ - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
262
+ if the config file provided is not a dictionary.
263
+
264
+ </Tip>
265
+ """
266
+ _check_fastai_fastcore_versions()
267
+
268
+ os.makedirs(save_directory, exist_ok=True)
269
+
270
+ # if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE.
271
+ if config is not None:
272
+ if not isinstance(config, dict):
273
+ raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'")
274
+ path = os.path.join(save_directory, constants.CONFIG_NAME)
275
+ with open(path, "w") as f:
276
+ json.dump(config, f)
277
+
278
+ _create_model_card(Path(save_directory))
279
+ _create_model_pyproject(Path(save_directory))
280
+
281
+ # learner.export saves the model in `self.path`.
282
+ learner.path = Path(save_directory)
283
+ os.makedirs(save_directory, exist_ok=True)
284
+ try:
285
+ learner.export(
286
+ fname="model.pkl",
287
+ pickle_protocol=DEFAULT_PROTOCOL,
288
+ )
289
+ except PicklingError:
290
+ raise PicklingError(
291
+ "You are using a lambda function, i.e., an anonymous function. `pickle`"
292
+ " cannot pickle function objects and requires that all functions have"
293
+ " names. One possible solution is to name the function."
294
+ )
295
+
296
+
297
+ @validate_hf_hub_args
298
+ def from_pretrained_fastai(
299
+ repo_id: str,
300
+ revision: Optional[str] = None,
301
+ ):
302
+ """
303
+ Load pretrained fastai model from the Hub or from a local directory.
304
+
305
+ Args:
306
+ repo_id (`str`):
307
+ The location where the pickled fastai.Learner is. It can be either of the two:
308
+ - Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
309
+ You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
310
+ Revision is the specific model version to use. Since we use a git-based system for storing models and other
311
+ artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
312
+ - Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
313
+ indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
314
+ revision (`str`, *optional*):
315
+ Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
316
+
317
+ Returns:
318
+ The `fastai.Learner` model in the `repo_id` repo.
319
+ """
320
+ _check_fastai_fastcore_versions()
321
+
322
+ # Load the `repo_id` repo.
323
+ # `snapshot_download` returns the folder where the model was stored.
324
+ # `cache_dir` will be the default '/root/.cache/huggingface/hub'
325
+ if not os.path.isdir(repo_id):
326
+ storage_folder = snapshot_download(
327
+ repo_id=repo_id,
328
+ revision=revision,
329
+ library_name="fastai",
330
+ library_version=get_fastai_version(),
331
+ )
332
+ else:
333
+ storage_folder = repo_id
334
+
335
+ _check_fastai_fastcore_pyproject_versions(storage_folder)
336
+
337
+ from fastai.learner import load_learner # type: ignore
338
+
339
+ return load_learner(os.path.join(storage_folder, "model.pkl"))
340
+
341
+
342
+ @validate_hf_hub_args
343
+ def push_to_hub_fastai(
344
+ learner,
345
+ *,
346
+ repo_id: str,
347
+ commit_message: str = "Push FastAI model using huggingface_hub.",
348
+ private: bool = False,
349
+ token: Optional[str] = None,
350
+ config: Optional[dict] = None,
351
+ branch: Optional[str] = None,
352
+ create_pr: Optional[bool] = None,
353
+ allow_patterns: Optional[Union[List[str], str]] = None,
354
+ ignore_patterns: Optional[Union[List[str], str]] = None,
355
+ delete_patterns: Optional[Union[List[str], str]] = None,
356
+ api_endpoint: Optional[str] = None,
357
+ ):
358
+ """
359
+ Upload learner checkpoint files to the Hub.
360
+
361
+ Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
362
+ `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
363
+ details.
364
+
365
+ Args:
366
+ learner (`Learner`):
367
+ The `fastai.Learner' you'd like to push to the Hub.
368
+ repo_id (`str`):
369
+ The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de').
370
+ commit_message (`str`, *optional*):
371
+ Message to commit while pushing. Will default to :obj:`"add model"`.
372
+ private (`bool`, *optional*, defaults to `False`):
373
+ Whether or not the repository created should be private.
374
+ token (`str`, *optional*):
375
+ The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt.
376
+ config (`dict`, *optional*):
377
+ Configuration object to be saved alongside the model weights.
378
+ branch (`str`, *optional*):
379
+ The git branch on which to push the model. This defaults to
380
+ the default branch as specified in your repository, which
381
+ defaults to `"main"`.
382
+ create_pr (`boolean`, *optional*):
383
+ Whether or not to create a Pull Request from `branch` with that commit.
384
+ Defaults to `False`.
385
+ api_endpoint (`str`, *optional*):
386
+ The API endpoint to use when pushing the model to the hub.
387
+ allow_patterns (`List[str]` or `str`, *optional*):
388
+ If provided, only files matching at least one pattern are pushed.
389
+ ignore_patterns (`List[str]` or `str`, *optional*):
390
+ If provided, files matching any of the patterns are not pushed.
391
+ delete_patterns (`List[str]` or `str`, *optional*):
392
+ If provided, remote files matching any of the patterns will be deleted from the repo.
393
+
394
+ Returns:
395
+ The url of the commit of your model in the given repository.
396
+
397
+ <Tip>
398
+
399
+ Raises the following error:
400
+
401
+ - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
402
+ if the user is not log on to the Hugging Face Hub.
403
+
404
+ </Tip>
405
+ """
406
+ _check_fastai_fastcore_versions()
407
+ api = HfApi(endpoint=api_endpoint)
408
+ repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
409
+
410
+ # Push the files to the repo in a single commit
411
+ with SoftTemporaryDirectory() as tmp:
412
+ saved_path = Path(tmp) / repo_id
413
+ _save_pretrained_fastai(learner, saved_path, config=config)
414
+ return api.upload_folder(
415
+ repo_id=repo_id,
416
+ token=token,
417
+ folder_path=saved_path,
418
+ commit_message=commit_message,
419
+ revision=branch,
420
+ create_pr=create_pr,
421
+ allow_patterns=allow_patterns,
422
+ ignore_patterns=ignore_patterns,
423
+ delete_patterns=delete_patterns,
424
+ )
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/file_download.py ADDED
@@ -0,0 +1,1624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import copy
3
+ import errno
4
+ import inspect
5
+ import os
6
+ import re
7
+ import shutil
8
+ import stat
9
+ import time
10
+ import uuid
11
+ import warnings
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any, BinaryIO, Dict, Literal, NoReturn, Optional, Tuple, Union
15
+ from urllib.parse import quote, urlparse
16
+
17
+ import requests
18
+
19
+ from . import (
20
+ __version__, # noqa: F401 # for backward compatibility
21
+ constants,
22
+ )
23
+ from ._local_folder import get_local_download_paths, read_download_metadata, write_download_metadata
24
+ from .constants import (
25
+ HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401 # for backward compatibility
26
+ HUGGINGFACE_HUB_CACHE, # noqa: F401 # for backward compatibility
27
+ )
28
+ from .errors import (
29
+ EntryNotFoundError,
30
+ FileMetadataError,
31
+ GatedRepoError,
32
+ LocalEntryNotFoundError,
33
+ RepositoryNotFoundError,
34
+ RevisionNotFoundError,
35
+ )
36
+ from .utils import (
37
+ OfflineModeIsEnabled,
38
+ SoftTemporaryDirectory,
39
+ WeakFileLock,
40
+ build_hf_headers,
41
+ get_fastai_version, # noqa: F401 # for backward compatibility
42
+ get_fastcore_version, # noqa: F401 # for backward compatibility
43
+ get_graphviz_version, # noqa: F401 # for backward compatibility
44
+ get_jinja_version, # noqa: F401 # for backward compatibility
45
+ get_pydot_version, # noqa: F401 # for backward compatibility
46
+ get_session,
47
+ get_tf_version, # noqa: F401 # for backward compatibility
48
+ get_torch_version, # noqa: F401 # for backward compatibility
49
+ hf_raise_for_status,
50
+ is_fastai_available, # noqa: F401 # for backward compatibility
51
+ is_fastcore_available, # noqa: F401 # for backward compatibility
52
+ is_graphviz_available, # noqa: F401 # for backward compatibility
53
+ is_jinja_available, # noqa: F401 # for backward compatibility
54
+ is_pydot_available, # noqa: F401 # for backward compatibility
55
+ is_tf_available, # noqa: F401 # for backward compatibility
56
+ is_torch_available, # noqa: F401 # for backward compatibility
57
+ logging,
58
+ reset_sessions,
59
+ tqdm,
60
+ validate_hf_hub_args,
61
+ )
62
+ from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility
63
+ from .utils._typing import HTTP_METHOD_T
64
+ from .utils.sha import sha_fileobj
65
+
66
+
67
+ logger = logging.get_logger(__name__)
68
+
69
+ # Return value when trying to load a file from cache but the file does not exist in the distant repo.
70
+ _CACHED_NO_EXIST = object()
71
+ _CACHED_NO_EXIST_T = Any
72
+
73
+ # Regex to get filename from a "Content-Disposition" header for CDN-served files
74
+ HEADER_FILENAME_PATTERN = re.compile(r'filename="(?P<filename>.*?)";')
75
+
76
+ # Regex to check if the revision IS directly a commit_hash
77
+ REGEX_COMMIT_HASH = re.compile(r"^[0-9a-f]{40}$")
78
+
79
+ # Regex to check if the file etag IS a valid sha256
80
+ REGEX_SHA256 = re.compile(r"^[0-9a-f]{64}$")
81
+
82
+ _are_symlinks_supported_in_dir: Dict[str, bool] = {}
83
+
84
+
85
+ def are_symlinks_supported(cache_dir: Union[str, Path, None] = None) -> bool:
86
+ """Return whether the symlinks are supported on the machine.
87
+
88
+ Since symlinks support can change depending on the mounted disk, we need to check
89
+ on the precise cache folder. By default, the default HF cache directory is checked.
90
+
91
+ Args:
92
+ cache_dir (`str`, `Path`, *optional*):
93
+ Path to the folder where cached files are stored.
94
+
95
+ Returns: [bool] Whether symlinks are supported in the directory.
96
+ """
97
+ # Defaults to HF cache
98
+ if cache_dir is None:
99
+ cache_dir = constants.HF_HUB_CACHE
100
+ cache_dir = str(Path(cache_dir).expanduser().resolve()) # make it unique
101
+
102
+ # Check symlink compatibility only once (per cache directory) at first time use
103
+ if cache_dir not in _are_symlinks_supported_in_dir:
104
+ _are_symlinks_supported_in_dir[cache_dir] = True
105
+
106
+ os.makedirs(cache_dir, exist_ok=True)
107
+ with SoftTemporaryDirectory(dir=cache_dir) as tmpdir:
108
+ src_path = Path(tmpdir) / "dummy_file_src"
109
+ src_path.touch()
110
+ dst_path = Path(tmpdir) / "dummy_file_dst"
111
+
112
+ # Relative source path as in `_create_symlink``
113
+ relative_src = os.path.relpath(src_path, start=os.path.dirname(dst_path))
114
+ try:
115
+ os.symlink(relative_src, dst_path)
116
+ except OSError:
117
+ # Likely running on Windows
118
+ _are_symlinks_supported_in_dir[cache_dir] = False
119
+
120
+ if not constants.HF_HUB_DISABLE_SYMLINKS_WARNING:
121
+ message = (
122
+ "`huggingface_hub` cache-system uses symlinks by default to"
123
+ " efficiently store duplicated files but your machine does not"
124
+ f" support them in {cache_dir}. Caching files will still work"
125
+ " but in a degraded version that might require more space on"
126
+ " your disk. This warning can be disabled by setting the"
127
+ " `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For"
128
+ " more details, see"
129
+ " https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations."
130
+ )
131
+ if os.name == "nt":
132
+ message += (
133
+ "\nTo support symlinks on Windows, you either need to"
134
+ " activate Developer Mode or to run Python as an"
135
+ " administrator. In order to activate developer mode,"
136
+ " see this article:"
137
+ " https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development"
138
+ )
139
+ warnings.warn(message)
140
+
141
+ return _are_symlinks_supported_in_dir[cache_dir]
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class HfFileMetadata:
146
+ """Data structure containing information about a file versioned on the Hub.
147
+
148
+ Returned by [`get_hf_file_metadata`] based on a URL.
149
+
150
+ Args:
151
+ commit_hash (`str`, *optional*):
152
+ The commit_hash related to the file.
153
+ etag (`str`, *optional*):
154
+ Etag of the file on the server.
155
+ location (`str`):
156
+ Location where to download the file. Can be a Hub url or not (CDN).
157
+ size (`size`):
158
+ Size of the file. In case of an LFS file, contains the size of the actual
159
+ LFS file, not the pointer.
160
+ """
161
+
162
+ commit_hash: Optional[str]
163
+ etag: Optional[str]
164
+ location: str
165
+ size: Optional[int]
166
+
167
+
168
+ @validate_hf_hub_args
169
+ def hf_hub_url(
170
+ repo_id: str,
171
+ filename: str,
172
+ *,
173
+ subfolder: Optional[str] = None,
174
+ repo_type: Optional[str] = None,
175
+ revision: Optional[str] = None,
176
+ endpoint: Optional[str] = None,
177
+ ) -> str:
178
+ """Construct the URL of a file from the given information.
179
+
180
+ The resolved address can either be a huggingface.co-hosted url, or a link to
181
+ Cloudfront (a Content Delivery Network, or CDN) for large files which are
182
+ more than a few MBs.
183
+
184
+ Args:
185
+ repo_id (`str`):
186
+ A namespace (user or an organization) name and a repo name separated
187
+ by a `/`.
188
+ filename (`str`):
189
+ The name of the file in the repo.
190
+ subfolder (`str`, *optional*):
191
+ An optional value corresponding to a folder inside the repo.
192
+ repo_type (`str`, *optional*):
193
+ Set to `"dataset"` or `"space"` if downloading from a dataset or space,
194
+ `None` or `"model"` if downloading from a model. Default is `None`.
195
+ revision (`str`, *optional*):
196
+ An optional Git revision id which can be a branch name, a tag, or a
197
+ commit hash.
198
+
199
+ Example:
200
+
201
+ ```python
202
+ >>> from huggingface_hub import hf_hub_url
203
+
204
+ >>> hf_hub_url(
205
+ ... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin"
206
+ ... )
207
+ 'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin'
208
+ ```
209
+
210
+ <Tip>
211
+
212
+ Notes:
213
+
214
+ Cloudfront is replicated over the globe so downloads are way faster for
215
+ the end user (and it also lowers our bandwidth costs).
216
+
217
+ Cloudfront aggressively caches files by default (default TTL is 24
218
+ hours), however this is not an issue here because we implement a
219
+ git-based versioning system on huggingface.co, which means that we store
220
+ the files on S3/Cloudfront in a content-addressable way (i.e., the file
221
+ name is its hash). Using content-addressable filenames means cache can't
222
+ ever be stale.
223
+
224
+ In terms of client-side caching from this library, we base our caching
225
+ on the objects' entity tag (`ETag`), which is an identifier of a
226
+ specific version of a resource [1]_. An object's ETag is: its git-sha1
227
+ if stored in git, or its sha256 if stored in git-lfs.
228
+
229
+ </Tip>
230
+
231
+ References:
232
+
233
+ - [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
234
+ """
235
+ if subfolder == "":
236
+ subfolder = None
237
+ if subfolder is not None:
238
+ filename = f"{subfolder}/{filename}"
239
+
240
+ if repo_type not in constants.REPO_TYPES:
241
+ raise ValueError("Invalid repo type")
242
+
243
+ if repo_type in constants.REPO_TYPES_URL_PREFIXES:
244
+ repo_id = constants.REPO_TYPES_URL_PREFIXES[repo_type] + repo_id
245
+
246
+ if revision is None:
247
+ revision = constants.DEFAULT_REVISION
248
+ url = HUGGINGFACE_CO_URL_TEMPLATE.format(
249
+ repo_id=repo_id, revision=quote(revision, safe=""), filename=quote(filename)
250
+ )
251
+ # Update endpoint if provided
252
+ if endpoint is not None and url.startswith(constants.ENDPOINT):
253
+ url = endpoint + url[len(constants.ENDPOINT) :]
254
+ return url
255
+
256
+
257
+ def _request_wrapper(
258
+ method: HTTP_METHOD_T, url: str, *, follow_relative_redirects: bool = False, **params
259
+ ) -> requests.Response:
260
+ """Wrapper around requests methods to follow relative redirects if `follow_relative_redirects=True` even when
261
+ `allow_redirection=False`.
262
+
263
+ Args:
264
+ method (`str`):
265
+ HTTP method, such as 'GET' or 'HEAD'.
266
+ url (`str`):
267
+ The URL of the resource to fetch.
268
+ follow_relative_redirects (`bool`, *optional*, defaults to `False`)
269
+ If True, relative redirection (redirection to the same site) will be resolved even when `allow_redirection`
270
+ kwarg is set to False. Useful when we want to follow a redirection to a renamed repository without
271
+ following redirection to a CDN.
272
+ **params (`dict`, *optional*):
273
+ Params to pass to `requests.request`.
274
+ """
275
+ # Recursively follow relative redirects
276
+ if follow_relative_redirects:
277
+ response = _request_wrapper(
278
+ method=method,
279
+ url=url,
280
+ follow_relative_redirects=False,
281
+ **params,
282
+ )
283
+
284
+ # If redirection, we redirect only relative paths.
285
+ # This is useful in case of a renamed repository.
286
+ if 300 <= response.status_code <= 399:
287
+ parsed_target = urlparse(response.headers["Location"])
288
+ if parsed_target.netloc == "":
289
+ # This means it is a relative 'location' headers, as allowed by RFC 7231.
290
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
291
+ # We want to follow this relative redirect !
292
+ #
293
+ # Highly inspired by `resolve_redirects` from requests library.
294
+ # See https://github.com/psf/requests/blob/main/requests/sessions.py#L159
295
+ next_url = urlparse(url)._replace(path=parsed_target.path).geturl()
296
+ return _request_wrapper(method=method, url=next_url, follow_relative_redirects=True, **params)
297
+ return response
298
+
299
+ # Perform request and return if status_code is not in the retry list.
300
+ response = get_session().request(method=method, url=url, **params)
301
+ hf_raise_for_status(response)
302
+ return response
303
+
304
+
305
+ def http_get(
306
+ url: str,
307
+ temp_file: BinaryIO,
308
+ *,
309
+ proxies: Optional[Dict] = None,
310
+ resume_size: float = 0,
311
+ headers: Optional[Dict[str, str]] = None,
312
+ expected_size: Optional[int] = None,
313
+ displayed_filename: Optional[str] = None,
314
+ _nb_retries: int = 5,
315
+ _tqdm_bar: Optional[tqdm] = None,
316
+ ) -> None:
317
+ """
318
+ Download a remote file. Do not gobble up errors, and will return errors tailored to the Hugging Face Hub.
319
+
320
+ If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely a
321
+ transient error (network outage?). We log a warning message and try to resume the download a few times before
322
+ giving up. The method gives up after 5 attempts if no new data has being received from the server.
323
+
324
+ Args:
325
+ url (`str`):
326
+ The URL of the file to download.
327
+ temp_file (`BinaryIO`):
328
+ The file-like object where to save the file.
329
+ proxies (`dict`, *optional*):
330
+ Dictionary mapping protocol to the URL of the proxy passed to `requests.request`.
331
+ resume_size (`float`, *optional*):
332
+ The number of bytes already downloaded. If set to 0 (default), the whole file is download. If set to a
333
+ positive number, the download will resume at the given position.
334
+ headers (`dict`, *optional*):
335
+ Dictionary of HTTP Headers to send with the request.
336
+ expected_size (`int`, *optional*):
337
+ The expected size of the file to download. If set, the download will raise an error if the size of the
338
+ received content is different from the expected one.
339
+ displayed_filename (`str`, *optional*):
340
+ The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If
341
+ not set, the filename is guessed from the URL or the `Content-Disposition` header.
342
+ """
343
+ if expected_size is not None and resume_size == expected_size:
344
+ # If the file is already fully downloaded, we don't need to download it again.
345
+ return
346
+
347
+ hf_transfer = None
348
+ if constants.HF_HUB_ENABLE_HF_TRANSFER:
349
+ if resume_size != 0:
350
+ warnings.warn("'hf_transfer' does not support `resume_size`: falling back to regular download method")
351
+ elif proxies is not None:
352
+ warnings.warn("'hf_transfer' does not support `proxies`: falling back to regular download method")
353
+ else:
354
+ try:
355
+ import hf_transfer # type: ignore[no-redef]
356
+ except ImportError:
357
+ raise ValueError(
358
+ "Fast download using 'hf_transfer' is enabled"
359
+ " (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is not"
360
+ " available in your environment. Try `pip install hf_transfer`."
361
+ )
362
+
363
+ initial_headers = headers
364
+ headers = copy.deepcopy(headers) or {}
365
+ if resume_size > 0:
366
+ headers["Range"] = "bytes=%d-" % (resume_size,)
367
+
368
+ r = _request_wrapper(
369
+ method="GET", url=url, stream=True, proxies=proxies, headers=headers, timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT
370
+ )
371
+ hf_raise_for_status(r)
372
+ content_length = r.headers.get("Content-Length")
373
+
374
+ # NOTE: 'total' is the total number of bytes to download, not the number of bytes in the file.
375
+ # If the file is compressed, the number of bytes in the saved file will be higher than 'total'.
376
+ total = resume_size + int(content_length) if content_length is not None else None
377
+
378
+ if displayed_filename is None:
379
+ displayed_filename = url
380
+ content_disposition = r.headers.get("Content-Disposition")
381
+ if content_disposition is not None:
382
+ match = HEADER_FILENAME_PATTERN.search(content_disposition)
383
+ if match is not None:
384
+ # Means file is on CDN
385
+ displayed_filename = match.groupdict()["filename"]
386
+
387
+ # Truncate filename if too long to display
388
+ if len(displayed_filename) > 40:
389
+ displayed_filename = f"(…){displayed_filename[-40:]}"
390
+
391
+ consistency_error_message = (
392
+ f"Consistency check failed: file should be of size {expected_size} but has size"
393
+ f" {{actual_size}} ({displayed_filename}).\nWe are sorry for the inconvenience. Please retry"
394
+ " with `force_download=True`.\nIf the issue persists, please let us know by opening an issue "
395
+ "on https://github.com/huggingface/huggingface_hub."
396
+ )
397
+
398
+ # Stream file to buffer
399
+ progress_cm: tqdm = (
400
+ tqdm( # type: ignore[assignment]
401
+ unit="B",
402
+ unit_scale=True,
403
+ total=total,
404
+ initial=resume_size,
405
+ desc=displayed_filename,
406
+ disable=True if (logger.getEffectiveLevel() == logging.NOTSET) else None,
407
+ # ^ set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached
408
+ # see https://github.com/huggingface/huggingface_hub/pull/2000
409
+ name="huggingface_hub.http_get",
410
+ )
411
+ if _tqdm_bar is None
412
+ else contextlib.nullcontext(_tqdm_bar)
413
+ # ^ `contextlib.nullcontext` mimics a context manager that does nothing
414
+ # Makes it easier to use the same code path for both cases but in the later
415
+ # case, the progress bar is not closed when exiting the context manager.
416
+ )
417
+
418
+ with progress_cm as progress:
419
+ if hf_transfer and total is not None and total > 5 * constants.DOWNLOAD_CHUNK_SIZE:
420
+ supports_callback = "callback" in inspect.signature(hf_transfer.download).parameters
421
+ if not supports_callback:
422
+ warnings.warn(
423
+ "You are using an outdated version of `hf_transfer`. "
424
+ "Consider upgrading to latest version to enable progress bars "
425
+ "using `pip install -U hf_transfer`."
426
+ )
427
+ try:
428
+ hf_transfer.download(
429
+ url=url,
430
+ filename=temp_file.name,
431
+ max_files=constants.HF_TRANSFER_CONCURRENCY,
432
+ chunk_size=constants.DOWNLOAD_CHUNK_SIZE,
433
+ headers=headers,
434
+ parallel_failures=3,
435
+ max_retries=5,
436
+ **({"callback": progress.update} if supports_callback else {}),
437
+ )
438
+ except Exception as e:
439
+ raise RuntimeError(
440
+ "An error occurred while downloading using `hf_transfer`. Consider"
441
+ " disabling HF_HUB_ENABLE_HF_TRANSFER for better error handling."
442
+ ) from e
443
+ if not supports_callback:
444
+ progress.update(total)
445
+ if expected_size is not None and expected_size != os.path.getsize(temp_file.name):
446
+ raise EnvironmentError(
447
+ consistency_error_message.format(
448
+ actual_size=os.path.getsize(temp_file.name),
449
+ )
450
+ )
451
+ return
452
+ new_resume_size = resume_size
453
+ try:
454
+ for chunk in r.iter_content(chunk_size=constants.DOWNLOAD_CHUNK_SIZE):
455
+ if chunk: # filter out keep-alive new chunks
456
+ progress.update(len(chunk))
457
+ temp_file.write(chunk)
458
+ new_resume_size += len(chunk)
459
+ # Some data has been downloaded from the server so we reset the number of retries.
460
+ _nb_retries = 5
461
+ except (requests.ConnectionError, requests.ReadTimeout) as e:
462
+ # If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely
463
+ # a transient error (network outage?). We log a warning message and try to resume the download a few times
464
+ # before giving up. Tre retry mechanism is basic but should be enough in most cases.
465
+ if _nb_retries <= 0:
466
+ logger.warning("Error while downloading from %s: %s\nMax retries exceeded.", url, str(e))
467
+ raise
468
+ logger.warning("Error while downloading from %s: %s\nTrying to resume download...", url, str(e))
469
+ time.sleep(1)
470
+ reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects
471
+ return http_get(
472
+ url=url,
473
+ temp_file=temp_file,
474
+ proxies=proxies,
475
+ resume_size=new_resume_size,
476
+ headers=initial_headers,
477
+ expected_size=expected_size,
478
+ _nb_retries=_nb_retries - 1,
479
+ _tqdm_bar=_tqdm_bar,
480
+ )
481
+
482
+ if expected_size is not None and expected_size != temp_file.tell():
483
+ raise EnvironmentError(
484
+ consistency_error_message.format(
485
+ actual_size=temp_file.tell(),
486
+ )
487
+ )
488
+
489
+
490
+ def _normalize_etag(etag: Optional[str]) -> Optional[str]:
491
+ """Normalize ETag HTTP header, so it can be used to create nice filepaths.
492
+
493
+ The HTTP spec allows two forms of ETag:
494
+ ETag: W/"<etag_value>"
495
+ ETag: "<etag_value>"
496
+
497
+ For now, we only expect the second form from the server, but we want to be future-proof so we support both. For
498
+ more context, see `TestNormalizeEtag` tests and https://github.com/huggingface/huggingface_hub/pull/1428.
499
+
500
+ Args:
501
+ etag (`str`, *optional*): HTTP header
502
+
503
+ Returns:
504
+ `str` or `None`: string that can be used as a nice directory name.
505
+ Returns `None` if input is None.
506
+ """
507
+ if etag is None:
508
+ return None
509
+ return etag.lstrip("W/").strip('"')
510
+
511
+
512
+ def _create_relative_symlink(src: str, dst: str, new_blob: bool = False) -> None:
513
+ """Alias method used in `transformers` conversion script."""
514
+ return _create_symlink(src=src, dst=dst, new_blob=new_blob)
515
+
516
+
517
+ def _create_symlink(src: str, dst: str, new_blob: bool = False) -> None:
518
+ """Create a symbolic link named dst pointing to src.
519
+
520
+ By default, it will try to create a symlink using a relative path. Relative paths have 2 advantages:
521
+ - If the cache_folder is moved (example: back-up on a shared drive), relative paths within the cache folder will
522
+ not break.
523
+ - Relative paths seems to be better handled on Windows. Issue was reported 3 times in less than a week when
524
+ changing from relative to absolute paths. See https://github.com/huggingface/huggingface_hub/issues/1398,
525
+ https://github.com/huggingface/diffusers/issues/2729 and https://github.com/huggingface/transformers/pull/22228.
526
+ NOTE: The issue with absolute paths doesn't happen on admin mode.
527
+ When creating a symlink from the cache to a local folder, it is possible that a relative path cannot be created.
528
+ This happens when paths are not on the same volume. In that case, we use absolute paths.
529
+
530
+
531
+ The result layout looks something like
532
+ └── [ 128] snapshots
533
+ ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
534
+ │ ├── [ 52] README.md -> ../../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
535
+ │ └── [ 76] pytorch_model.bin -> ../../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
536
+
537
+ If symlinks cannot be created on this platform (most likely to be Windows), the workaround is to avoid symlinks by
538
+ having the actual file in `dst`. If it is a new file (`new_blob=True`), we move it to `dst`. If it is not a new file
539
+ (`new_blob=False`), we don't know if the blob file is already referenced elsewhere. To avoid breaking existing
540
+ cache, the file is duplicated on the disk.
541
+
542
+ In case symlinks are not supported, a warning message is displayed to the user once when loading `huggingface_hub`.
543
+ The warning message can be disabled with the `DISABLE_SYMLINKS_WARNING` environment variable.
544
+ """
545
+ try:
546
+ os.remove(dst)
547
+ except OSError:
548
+ pass
549
+
550
+ abs_src = os.path.abspath(os.path.expanduser(src))
551
+ abs_dst = os.path.abspath(os.path.expanduser(dst))
552
+ abs_dst_folder = os.path.dirname(abs_dst)
553
+
554
+ # Use relative_dst in priority
555
+ try:
556
+ relative_src = os.path.relpath(abs_src, abs_dst_folder)
557
+ except ValueError:
558
+ # Raised on Windows if src and dst are not on the same volume. This is the case when creating a symlink to a
559
+ # local_dir instead of within the cache directory.
560
+ # See https://docs.python.org/3/library/os.path.html#os.path.relpath
561
+ relative_src = None
562
+
563
+ try:
564
+ commonpath = os.path.commonpath([abs_src, abs_dst])
565
+ _support_symlinks = are_symlinks_supported(commonpath)
566
+ except ValueError:
567
+ # Raised if src and dst are not on the same volume. Symlinks will still work on Linux/Macos.
568
+ # See https://docs.python.org/3/library/os.path.html#os.path.commonpath
569
+ _support_symlinks = os.name != "nt"
570
+ except PermissionError:
571
+ # Permission error means src and dst are not in the same volume (e.g. destination path has been provided
572
+ # by the user via `local_dir`. Let's test symlink support there)
573
+ _support_symlinks = are_symlinks_supported(abs_dst_folder)
574
+ except OSError as e:
575
+ # OS error (errno=30) means that the commonpath is readonly on Linux/MacOS.
576
+ if e.errno == errno.EROFS:
577
+ _support_symlinks = are_symlinks_supported(abs_dst_folder)
578
+ else:
579
+ raise
580
+
581
+ # Symlinks are supported => let's create a symlink.
582
+ if _support_symlinks:
583
+ src_rel_or_abs = relative_src or abs_src
584
+ logger.debug(f"Creating pointer from {src_rel_or_abs} to {abs_dst}")
585
+ try:
586
+ os.symlink(src_rel_or_abs, abs_dst)
587
+ return
588
+ except FileExistsError:
589
+ if os.path.islink(abs_dst) and os.path.realpath(abs_dst) == os.path.realpath(abs_src):
590
+ # `abs_dst` already exists and is a symlink to the `abs_src` blob. It is most likely that the file has
591
+ # been cached twice concurrently (exactly between `os.remove` and `os.symlink`). Do nothing.
592
+ return
593
+ else:
594
+ # Very unlikely to happen. Means a file `dst` has been created exactly between `os.remove` and
595
+ # `os.symlink` and is not a symlink to the `abs_src` blob file. Raise exception.
596
+ raise
597
+ except PermissionError:
598
+ # Permission error means src and dst are not in the same volume (e.g. download to local dir) and symlink
599
+ # is supported on both volumes but not between them. Let's just make a hard copy in that case.
600
+ pass
601
+
602
+ # Symlinks are not supported => let's move or copy the file.
603
+ if new_blob:
604
+ logger.info(f"Symlink not supported. Moving file from {abs_src} to {abs_dst}")
605
+ shutil.move(abs_src, abs_dst, copy_function=_copy_no_matter_what)
606
+ else:
607
+ logger.info(f"Symlink not supported. Copying file from {abs_src} to {abs_dst}")
608
+ shutil.copyfile(abs_src, abs_dst)
609
+
610
+
611
+ def _cache_commit_hash_for_specific_revision(storage_folder: str, revision: str, commit_hash: str) -> None:
612
+ """Cache reference between a revision (tag, branch or truncated commit hash) and the corresponding commit hash.
613
+
614
+ Does nothing if `revision` is already a proper `commit_hash` or reference is already cached.
615
+ """
616
+ if revision != commit_hash:
617
+ ref_path = Path(storage_folder) / "refs" / revision
618
+ ref_path.parent.mkdir(parents=True, exist_ok=True)
619
+ if not ref_path.exists() or commit_hash != ref_path.read_text():
620
+ # Update ref only if has been updated. Could cause useless error in case
621
+ # repo is already cached and user doesn't have write access to cache folder.
622
+ # See https://github.com/huggingface/huggingface_hub/issues/1216.
623
+ ref_path.write_text(commit_hash)
624
+
625
+
626
+ @validate_hf_hub_args
627
+ def repo_folder_name(*, repo_id: str, repo_type: str) -> str:
628
+ """Return a serialized version of a hf.co repo name and type, safe for disk storage
629
+ as a single non-nested folder.
630
+
631
+ Example: models--julien-c--EsperBERTo-small
632
+ """
633
+ # remove all `/` occurrences to correctly convert repo to directory name
634
+ parts = [f"{repo_type}s", *repo_id.split("/")]
635
+ return constants.REPO_ID_SEPARATOR.join(parts)
636
+
637
+
638
+ def _check_disk_space(expected_size: int, target_dir: Union[str, Path]) -> None:
639
+ """Check disk usage and log a warning if there is not enough disk space to download the file.
640
+
641
+ Args:
642
+ expected_size (`int`):
643
+ The expected size of the file in bytes.
644
+ target_dir (`str`):
645
+ The directory where the file will be stored after downloading.
646
+ """
647
+
648
+ target_dir = Path(target_dir) # format as `Path`
649
+ for path in [target_dir] + list(target_dir.parents): # first check target_dir, then each parents one by one
650
+ try:
651
+ target_dir_free = shutil.disk_usage(path).free
652
+ if target_dir_free < expected_size:
653
+ warnings.warn(
654
+ "Not enough free disk space to download the file. "
655
+ f"The expected file size is: {expected_size / 1e6:.2f} MB. "
656
+ f"The target location {target_dir} only has {target_dir_free / 1e6:.2f} MB free disk space."
657
+ )
658
+ return
659
+ except OSError: # raise on anything: file does not exist or space disk cannot be checked
660
+ pass
661
+
662
+
663
+ @validate_hf_hub_args
664
+ def hf_hub_download(
665
+ repo_id: str,
666
+ filename: str,
667
+ *,
668
+ subfolder: Optional[str] = None,
669
+ repo_type: Optional[str] = None,
670
+ revision: Optional[str] = None,
671
+ library_name: Optional[str] = None,
672
+ library_version: Optional[str] = None,
673
+ cache_dir: Union[str, Path, None] = None,
674
+ local_dir: Union[str, Path, None] = None,
675
+ user_agent: Union[Dict, str, None] = None,
676
+ force_download: bool = False,
677
+ proxies: Optional[Dict] = None,
678
+ etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
679
+ token: Union[bool, str, None] = None,
680
+ local_files_only: bool = False,
681
+ headers: Optional[Dict[str, str]] = None,
682
+ endpoint: Optional[str] = None,
683
+ resume_download: Optional[bool] = None,
684
+ force_filename: Optional[str] = None,
685
+ local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
686
+ ) -> str:
687
+ """Download a given file if it's not already present in the local cache.
688
+
689
+ The new cache file layout looks like this:
690
+ - The cache directory contains one subfolder per repo_id (namespaced by repo type)
691
+ - inside each repo folder:
692
+ - refs is a list of the latest known revision => commit_hash pairs
693
+ - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
694
+ whether they're LFS files or not)
695
+ - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
696
+ that have been resolved at that particular commit. Each filename is a symlink to the blob
697
+ at that particular commit.
698
+
699
+ ```
700
+ [ 96] .
701
+ └── [ 160] models--julien-c--EsperBERTo-small
702
+ ├── [ 160] blobs
703
+ │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
704
+ │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
705
+ │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
706
+ ├── [ 96] refs
707
+ │ └── [ 40] main
708
+ └── [ 128] snapshots
709
+ ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
710
+ │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
711
+ │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
712
+ └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
713
+ ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
714
+ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
715
+ ```
716
+
717
+ If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
718
+ option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
719
+ to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
720
+ cache-system, it's optimized for regularly pulling the latest version of a repository.
721
+
722
+ Args:
723
+ repo_id (`str`):
724
+ A user or an organization name and a repo name separated by a `/`.
725
+ filename (`str`):
726
+ The name of the file in the repo.
727
+ subfolder (`str`, *optional*):
728
+ An optional value corresponding to a folder inside the model repo.
729
+ repo_type (`str`, *optional*):
730
+ Set to `"dataset"` or `"space"` if downloading from a dataset or space,
731
+ `None` or `"model"` if downloading from a model. Default is `None`.
732
+ revision (`str`, *optional*):
733
+ An optional Git revision id which can be a branch name, a tag, or a
734
+ commit hash.
735
+ library_name (`str`, *optional*):
736
+ The name of the library to which the object corresponds.
737
+ library_version (`str`, *optional*):
738
+ The version of the library.
739
+ cache_dir (`str`, `Path`, *optional*):
740
+ Path to the folder where cached files are stored.
741
+ local_dir (`str` or `Path`, *optional*):
742
+ If provided, the downloaded file will be placed under this directory.
743
+ user_agent (`dict`, `str`, *optional*):
744
+ The user-agent info in the form of a dictionary or a string.
745
+ force_download (`bool`, *optional*, defaults to `False`):
746
+ Whether the file should be downloaded even if it already exists in
747
+ the local cache.
748
+ proxies (`dict`, *optional*):
749
+ Dictionary mapping protocol to the URL of the proxy passed to
750
+ `requests.request`.
751
+ etag_timeout (`float`, *optional*, defaults to `10`):
752
+ When fetching ETag, how many seconds to wait for the server to send
753
+ data before giving up which is passed to `requests.request`.
754
+ token (`str`, `bool`, *optional*):
755
+ A token to be used for the download.
756
+ - If `True`, the token is read from the HuggingFace config
757
+ folder.
758
+ - If a string, it's used as the authentication token.
759
+ local_files_only (`bool`, *optional*, defaults to `False`):
760
+ If `True`, avoid downloading the file and return the path to the
761
+ local cached file if it exists.
762
+ headers (`dict`, *optional*):
763
+ Additional headers to be sent with the request.
764
+
765
+ Returns:
766
+ `str`: Local path of file or if networking is off, last version of file cached on disk.
767
+
768
+ Raises:
769
+ [`~utils.RepositoryNotFoundError`]
770
+ If the repository to download from cannot be found. This may be because it doesn't exist,
771
+ or because it is set to `private` and you do not have access.
772
+ [`~utils.RevisionNotFoundError`]
773
+ If the revision to download from cannot be found.
774
+ [`~utils.EntryNotFoundError`]
775
+ If the file to download cannot be found.
776
+ [`~utils.LocalEntryNotFoundError`]
777
+ If network is disabled or unavailable and file is not found in cache.
778
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
779
+ If `token=True` but the token cannot be found.
780
+ [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
781
+ If ETag cannot be determined.
782
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
783
+ If some parameter value is invalid.
784
+
785
+ """
786
+ if constants.HF_HUB_ETAG_TIMEOUT != constants.DEFAULT_ETAG_TIMEOUT:
787
+ # Respect environment variable above user value
788
+ etag_timeout = constants.HF_HUB_ETAG_TIMEOUT
789
+
790
+ if force_filename is not None:
791
+ warnings.warn(
792
+ "The `force_filename` parameter is deprecated as a new caching system, "
793
+ "which keeps the filenames as they are on the Hub, is now in place.",
794
+ FutureWarning,
795
+ )
796
+ if resume_download is not None:
797
+ warnings.warn(
798
+ "`resume_download` is deprecated and will be removed in version 1.0.0. "
799
+ "Downloads always resume when possible. "
800
+ "If you want to force a new download, use `force_download=True`.",
801
+ FutureWarning,
802
+ )
803
+
804
+ if cache_dir is None:
805
+ cache_dir = constants.HF_HUB_CACHE
806
+ if revision is None:
807
+ revision = constants.DEFAULT_REVISION
808
+ if isinstance(cache_dir, Path):
809
+ cache_dir = str(cache_dir)
810
+ if isinstance(local_dir, Path):
811
+ local_dir = str(local_dir)
812
+
813
+ if subfolder == "":
814
+ subfolder = None
815
+ if subfolder is not None:
816
+ # This is used to create a URL, and not a local path, hence the forward slash.
817
+ filename = f"{subfolder}/{filename}"
818
+
819
+ if repo_type is None:
820
+ repo_type = "model"
821
+ if repo_type not in constants.REPO_TYPES:
822
+ raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES)}")
823
+
824
+ headers = build_hf_headers(
825
+ token=token,
826
+ library_name=library_name,
827
+ library_version=library_version,
828
+ user_agent=user_agent,
829
+ headers=headers,
830
+ )
831
+
832
+ if local_dir is not None:
833
+ if local_dir_use_symlinks != "auto":
834
+ warnings.warn(
835
+ "`local_dir_use_symlinks` parameter is deprecated and will be ignored. "
836
+ "The process to download files to a local folder has been updated and do "
837
+ "not rely on symlinks anymore. You only need to pass a destination folder "
838
+ "as`local_dir`.\n"
839
+ "For more details, check out https://huggingface.co/docs/huggingface_hub/main/en/guides/download#download-files-to-local-folder."
840
+ )
841
+
842
+ return _hf_hub_download_to_local_dir(
843
+ # Destination
844
+ local_dir=local_dir,
845
+ # File info
846
+ repo_id=repo_id,
847
+ repo_type=repo_type,
848
+ filename=filename,
849
+ revision=revision,
850
+ # HTTP info
851
+ endpoint=endpoint,
852
+ etag_timeout=etag_timeout,
853
+ headers=headers,
854
+ proxies=proxies,
855
+ token=token,
856
+ # Additional options
857
+ cache_dir=cache_dir,
858
+ force_download=force_download,
859
+ local_files_only=local_files_only,
860
+ )
861
+ else:
862
+ return _hf_hub_download_to_cache_dir(
863
+ # Destination
864
+ cache_dir=cache_dir,
865
+ # File info
866
+ repo_id=repo_id,
867
+ filename=filename,
868
+ repo_type=repo_type,
869
+ revision=revision,
870
+ # HTTP info
871
+ endpoint=endpoint,
872
+ etag_timeout=etag_timeout,
873
+ headers=headers,
874
+ proxies=proxies,
875
+ token=token,
876
+ # Additional options
877
+ local_files_only=local_files_only,
878
+ force_download=force_download,
879
+ )
880
+
881
+
882
+ def _hf_hub_download_to_cache_dir(
883
+ *,
884
+ # Destination
885
+ cache_dir: str,
886
+ # File info
887
+ repo_id: str,
888
+ filename: str,
889
+ repo_type: str,
890
+ revision: str,
891
+ # HTTP info
892
+ endpoint: Optional[str],
893
+ etag_timeout: float,
894
+ headers: Dict[str, str],
895
+ proxies: Optional[Dict],
896
+ token: Optional[Union[bool, str]],
897
+ # Additional options
898
+ local_files_only: bool,
899
+ force_download: bool,
900
+ ) -> str:
901
+ """Download a given file to a cache folder, if not already present.
902
+
903
+ Method should not be called directly. Please use `hf_hub_download` instead.
904
+ """
905
+ locks_dir = os.path.join(cache_dir, ".locks")
906
+ storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
907
+
908
+ # cross platform transcription of filename, to be used as a local file path.
909
+ relative_filename = os.path.join(*filename.split("/"))
910
+ if os.name == "nt":
911
+ if relative_filename.startswith("..\\") or "\\..\\" in relative_filename:
912
+ raise ValueError(
913
+ f"Invalid filename: cannot handle filename '{relative_filename}' on Windows. Please ask the repository"
914
+ " owner to rename this file."
915
+ )
916
+
917
+ # if user provides a commit_hash and they already have the file on disk, shortcut everything.
918
+ if REGEX_COMMIT_HASH.match(revision):
919
+ pointer_path = _get_pointer_path(storage_folder, revision, relative_filename)
920
+ if os.path.exists(pointer_path) and not force_download:
921
+ return pointer_path
922
+
923
+ # Try to get metadata (etag, commit_hash, url, size) from the server.
924
+ # If we can't, a HEAD request error is returned.
925
+ (url_to_download, etag, commit_hash, expected_size, head_call_error) = _get_metadata_or_catch_error(
926
+ repo_id=repo_id,
927
+ filename=filename,
928
+ repo_type=repo_type,
929
+ revision=revision,
930
+ endpoint=endpoint,
931
+ proxies=proxies,
932
+ etag_timeout=etag_timeout,
933
+ headers=headers,
934
+ token=token,
935
+ local_files_only=local_files_only,
936
+ storage_folder=storage_folder,
937
+ relative_filename=relative_filename,
938
+ )
939
+
940
+ # etag can be None for several reasons:
941
+ # 1. we passed local_files_only.
942
+ # 2. we don't have a connection
943
+ # 3. Hub is down (HTTP 500, 503, 504)
944
+ # 4. repo is not found -for example private or gated- and invalid/missing token sent
945
+ # 5. Hub is blocked by a firewall or proxy is not set correctly.
946
+ # => Try to get the last downloaded one from the specified revision.
947
+ #
948
+ # If the specified revision is a commit hash, look inside "snapshots".
949
+ # If the specified revision is a branch or tag, look inside "refs".
950
+ if head_call_error is not None:
951
+ # Couldn't make a HEAD call => let's try to find a local file
952
+ if not force_download:
953
+ commit_hash = None
954
+ if REGEX_COMMIT_HASH.match(revision):
955
+ commit_hash = revision
956
+ else:
957
+ ref_path = os.path.join(storage_folder, "refs", revision)
958
+ if os.path.isfile(ref_path):
959
+ with open(ref_path) as f:
960
+ commit_hash = f.read()
961
+
962
+ # Return pointer file if exists
963
+ if commit_hash is not None:
964
+ pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename)
965
+ if os.path.exists(pointer_path) and not force_download:
966
+ return pointer_path
967
+
968
+ # Otherwise, raise appropriate error
969
+ _raise_on_head_call_error(head_call_error, force_download, local_files_only)
970
+
971
+ # From now on, etag, commit_hash, url and size are not None.
972
+ assert etag is not None, "etag must have been retrieved from server"
973
+ assert commit_hash is not None, "commit_hash must have been retrieved from server"
974
+ assert url_to_download is not None, "file location must have been retrieved from server"
975
+ assert expected_size is not None, "expected_size must have been retrieved from server"
976
+ blob_path = os.path.join(storage_folder, "blobs", etag)
977
+ pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename)
978
+
979
+ os.makedirs(os.path.dirname(blob_path), exist_ok=True)
980
+ os.makedirs(os.path.dirname(pointer_path), exist_ok=True)
981
+
982
+ # if passed revision is not identical to commit_hash
983
+ # then revision has to be a branch name or tag name.
984
+ # In that case store a ref.
985
+ _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash)
986
+
987
+ # If file already exists, return it (except if force_download=True)
988
+ if not force_download:
989
+ if os.path.exists(pointer_path):
990
+ return pointer_path
991
+
992
+ if os.path.exists(blob_path):
993
+ # we have the blob already, but not the pointer
994
+ _create_symlink(blob_path, pointer_path, new_blob=False)
995
+ return pointer_path
996
+
997
+ # Prevent parallel downloads of the same file with a lock.
998
+ # etag could be duplicated across repos,
999
+ lock_path = os.path.join(locks_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type), f"{etag}.lock")
1000
+
1001
+ # Some Windows versions do not allow for paths longer than 255 characters.
1002
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix.
1003
+ if os.name == "nt" and len(os.path.abspath(lock_path)) > 255:
1004
+ lock_path = "\\\\?\\" + os.path.abspath(lock_path)
1005
+
1006
+ if os.name == "nt" and len(os.path.abspath(blob_path)) > 255:
1007
+ blob_path = "\\\\?\\" + os.path.abspath(blob_path)
1008
+
1009
+ Path(lock_path).parent.mkdir(parents=True, exist_ok=True)
1010
+ with WeakFileLock(lock_path):
1011
+ _download_to_tmp_and_move(
1012
+ incomplete_path=Path(blob_path + ".incomplete"),
1013
+ destination_path=Path(blob_path),
1014
+ url_to_download=url_to_download,
1015
+ proxies=proxies,
1016
+ headers=headers,
1017
+ expected_size=expected_size,
1018
+ filename=filename,
1019
+ force_download=force_download,
1020
+ )
1021
+ if not os.path.exists(pointer_path):
1022
+ _create_symlink(blob_path, pointer_path, new_blob=True)
1023
+
1024
+ return pointer_path
1025
+
1026
+
1027
+ def _hf_hub_download_to_local_dir(
1028
+ *,
1029
+ # Destination
1030
+ local_dir: Union[str, Path],
1031
+ # File info
1032
+ repo_id: str,
1033
+ repo_type: str,
1034
+ filename: str,
1035
+ revision: str,
1036
+ # HTTP info
1037
+ endpoint: Optional[str],
1038
+ etag_timeout: float,
1039
+ headers: Dict[str, str],
1040
+ proxies: Optional[Dict],
1041
+ token: Union[bool, str, None],
1042
+ # Additional options
1043
+ cache_dir: str,
1044
+ force_download: bool,
1045
+ local_files_only: bool,
1046
+ ) -> str:
1047
+ """Download a given file to a local folder, if not already present.
1048
+
1049
+ Method should not be called directly. Please use `hf_hub_download` instead.
1050
+ """
1051
+ # Some Windows versions do not allow for paths longer than 255 characters.
1052
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix.
1053
+ if os.name == "nt" and len(os.path.abspath(local_dir)) > 255:
1054
+ local_dir = "\\\\?\\" + os.path.abspath(local_dir)
1055
+ local_dir = Path(local_dir)
1056
+ paths = get_local_download_paths(local_dir=local_dir, filename=filename)
1057
+ local_metadata = read_download_metadata(local_dir=local_dir, filename=filename)
1058
+
1059
+ # Local file exists + metadata exists + commit_hash matches => return file
1060
+ if (
1061
+ not force_download
1062
+ and REGEX_COMMIT_HASH.match(revision)
1063
+ and paths.file_path.is_file()
1064
+ and local_metadata is not None
1065
+ and local_metadata.commit_hash == revision
1066
+ ):
1067
+ return str(paths.file_path)
1068
+
1069
+ # Local file doesn't exist or commit_hash doesn't match => we need the etag
1070
+ (url_to_download, etag, commit_hash, expected_size, head_call_error) = _get_metadata_or_catch_error(
1071
+ repo_id=repo_id,
1072
+ filename=filename,
1073
+ repo_type=repo_type,
1074
+ revision=revision,
1075
+ endpoint=endpoint,
1076
+ proxies=proxies,
1077
+ etag_timeout=etag_timeout,
1078
+ headers=headers,
1079
+ token=token,
1080
+ local_files_only=local_files_only,
1081
+ )
1082
+
1083
+ if head_call_error is not None:
1084
+ # No HEAD call but local file exists => default to local file
1085
+ if not force_download and paths.file_path.is_file():
1086
+ logger.warning(
1087
+ f"Couldn't access the Hub to check for update but local file already exists. Defaulting to existing file. (error: {head_call_error})"
1088
+ )
1089
+ return str(paths.file_path)
1090
+ # Otherwise => raise
1091
+ _raise_on_head_call_error(head_call_error, force_download, local_files_only)
1092
+
1093
+ # From now on, etag, commit_hash, url and size are not None.
1094
+ assert etag is not None, "etag must have been retrieved from server"
1095
+ assert commit_hash is not None, "commit_hash must have been retrieved from server"
1096
+ assert url_to_download is not None, "file location must have been retrieved from server"
1097
+ assert expected_size is not None, "expected_size must have been retrieved from server"
1098
+
1099
+ # Local file exists => check if it's up-to-date
1100
+ if not force_download and paths.file_path.is_file():
1101
+ # etag matches => update metadata and return file
1102
+ if local_metadata is not None and local_metadata.etag == etag:
1103
+ write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
1104
+ return str(paths.file_path)
1105
+
1106
+ # metadata is outdated + etag is a sha256
1107
+ # => means it's an LFS file (large)
1108
+ # => let's compute local hash and compare
1109
+ # => if match, update metadata and return file
1110
+ if local_metadata is None and REGEX_SHA256.match(etag) is not None:
1111
+ with open(paths.file_path, "rb") as f:
1112
+ file_hash = sha_fileobj(f).hex()
1113
+ if file_hash == etag:
1114
+ write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
1115
+ return str(paths.file_path)
1116
+
1117
+ # Local file doesn't exist or etag isn't a match => retrieve file from remote (or cache)
1118
+
1119
+ # If we are lucky enough, the file is already in the cache => copy it
1120
+ if not force_download:
1121
+ cached_path = try_to_load_from_cache(
1122
+ repo_id=repo_id,
1123
+ filename=filename,
1124
+ cache_dir=cache_dir,
1125
+ revision=commit_hash,
1126
+ repo_type=repo_type,
1127
+ )
1128
+ if isinstance(cached_path, str):
1129
+ with WeakFileLock(paths.lock_path):
1130
+ paths.file_path.parent.mkdir(parents=True, exist_ok=True)
1131
+ shutil.copyfile(cached_path, paths.file_path)
1132
+ write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
1133
+ return str(paths.file_path)
1134
+
1135
+ # Otherwise, let's download the file!
1136
+ with WeakFileLock(paths.lock_path):
1137
+ paths.file_path.unlink(missing_ok=True) # delete outdated file first
1138
+ _download_to_tmp_and_move(
1139
+ incomplete_path=paths.incomplete_path(etag),
1140
+ destination_path=paths.file_path,
1141
+ url_to_download=url_to_download,
1142
+ proxies=proxies,
1143
+ headers=headers,
1144
+ expected_size=expected_size,
1145
+ filename=filename,
1146
+ force_download=force_download,
1147
+ )
1148
+
1149
+ write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag)
1150
+ return str(paths.file_path)
1151
+
1152
+
1153
+ @validate_hf_hub_args
1154
+ def try_to_load_from_cache(
1155
+ repo_id: str,
1156
+ filename: str,
1157
+ cache_dir: Union[str, Path, None] = None,
1158
+ revision: Optional[str] = None,
1159
+ repo_type: Optional[str] = None,
1160
+ ) -> Union[str, _CACHED_NO_EXIST_T, None]:
1161
+ """
1162
+ Explores the cache to return the latest cached file for a given revision if found.
1163
+
1164
+ This function will not raise any exception if the file in not cached.
1165
+
1166
+ Args:
1167
+ cache_dir (`str` or `os.PathLike`):
1168
+ The folder where the cached files lie.
1169
+ repo_id (`str`):
1170
+ The ID of the repo on huggingface.co.
1171
+ filename (`str`):
1172
+ The filename to look for inside `repo_id`.
1173
+ revision (`str`, *optional*):
1174
+ The specific model version to use. Will default to `"main"` if it's not provided and no `commit_hash` is
1175
+ provided either.
1176
+ repo_type (`str`, *optional*):
1177
+ The type of the repository. Will default to `"model"`.
1178
+
1179
+ Returns:
1180
+ `Optional[str]` or `_CACHED_NO_EXIST`:
1181
+ Will return `None` if the file was not cached. Otherwise:
1182
+ - The exact path to the cached file if it's found in the cache
1183
+ - A special value `_CACHED_NO_EXIST` if the file does not exist at the given commit hash and this fact was
1184
+ cached.
1185
+
1186
+ Example:
1187
+
1188
+ ```python
1189
+ from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST
1190
+
1191
+ filepath = try_to_load_from_cache()
1192
+ if isinstance(filepath, str):
1193
+ # file exists and is cached
1194
+ ...
1195
+ elif filepath is _CACHED_NO_EXIST:
1196
+ # non-existence of file is cached
1197
+ ...
1198
+ else:
1199
+ # file is not cached
1200
+ ...
1201
+ ```
1202
+ """
1203
+ if revision is None:
1204
+ revision = "main"
1205
+ if repo_type is None:
1206
+ repo_type = "model"
1207
+ if repo_type not in constants.REPO_TYPES:
1208
+ raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES)}")
1209
+ if cache_dir is None:
1210
+ cache_dir = constants.HF_HUB_CACHE
1211
+
1212
+ object_id = repo_id.replace("/", "--")
1213
+ repo_cache = os.path.join(cache_dir, f"{repo_type}s--{object_id}")
1214
+ if not os.path.isdir(repo_cache):
1215
+ # No cache for this model
1216
+ return None
1217
+
1218
+ refs_dir = os.path.join(repo_cache, "refs")
1219
+ snapshots_dir = os.path.join(repo_cache, "snapshots")
1220
+ no_exist_dir = os.path.join(repo_cache, ".no_exist")
1221
+
1222
+ # Resolve refs (for instance to convert main to the associated commit sha)
1223
+ if os.path.isdir(refs_dir):
1224
+ revision_file = os.path.join(refs_dir, revision)
1225
+ if os.path.isfile(revision_file):
1226
+ with open(revision_file) as f:
1227
+ revision = f.read()
1228
+
1229
+ # Check if file is cached as "no_exist"
1230
+ if os.path.isfile(os.path.join(no_exist_dir, revision, filename)):
1231
+ return _CACHED_NO_EXIST
1232
+
1233
+ # Check if revision folder exists
1234
+ if not os.path.exists(snapshots_dir):
1235
+ return None
1236
+ cached_shas = os.listdir(snapshots_dir)
1237
+ if revision not in cached_shas:
1238
+ # No cache for this revision and we won't try to return a random revision
1239
+ return None
1240
+
1241
+ # Check if file exists in cache
1242
+ cached_file = os.path.join(snapshots_dir, revision, filename)
1243
+ return cached_file if os.path.isfile(cached_file) else None
1244
+
1245
+
1246
+ @validate_hf_hub_args
1247
+ def get_hf_file_metadata(
1248
+ url: str,
1249
+ token: Union[bool, str, None] = None,
1250
+ proxies: Optional[Dict] = None,
1251
+ timeout: Optional[float] = constants.DEFAULT_REQUEST_TIMEOUT,
1252
+ library_name: Optional[str] = None,
1253
+ library_version: Optional[str] = None,
1254
+ user_agent: Union[Dict, str, None] = None,
1255
+ headers: Optional[Dict[str, str]] = None,
1256
+ ) -> HfFileMetadata:
1257
+ """Fetch metadata of a file versioned on the Hub for a given url.
1258
+
1259
+ Args:
1260
+ url (`str`):
1261
+ File url, for example returned by [`hf_hub_url`].
1262
+ token (`str` or `bool`, *optional*):
1263
+ A token to be used for the download.
1264
+ - If `True`, the token is read from the HuggingFace config
1265
+ folder.
1266
+ - If `False` or `None`, no token is provided.
1267
+ - If a string, it's used as the authentication token.
1268
+ proxies (`dict`, *optional*):
1269
+ Dictionary mapping protocol to the URL of the proxy passed to
1270
+ `requests.request`.
1271
+ timeout (`float`, *optional*, defaults to 10):
1272
+ How many seconds to wait for the server to send metadata before giving up.
1273
+ library_name (`str`, *optional*):
1274
+ The name of the library to which the object corresponds.
1275
+ library_version (`str`, *optional*):
1276
+ The version of the library.
1277
+ user_agent (`dict`, `str`, *optional*):
1278
+ The user-agent info in the form of a dictionary or a string.
1279
+ headers (`dict`, *optional*):
1280
+ Additional headers to be sent with the request.
1281
+
1282
+ Returns:
1283
+ A [`HfFileMetadata`] object containing metadata such as location, etag, size and
1284
+ commit_hash.
1285
+ """
1286
+ headers = build_hf_headers(
1287
+ token=token,
1288
+ library_name=library_name,
1289
+ library_version=library_version,
1290
+ user_agent=user_agent,
1291
+ headers=headers,
1292
+ )
1293
+ headers["Accept-Encoding"] = "identity" # prevent any compression => we want to know the real size of the file
1294
+
1295
+ # Retrieve metadata
1296
+ r = _request_wrapper(
1297
+ method="HEAD",
1298
+ url=url,
1299
+ headers=headers,
1300
+ allow_redirects=False,
1301
+ follow_relative_redirects=True,
1302
+ proxies=proxies,
1303
+ timeout=timeout,
1304
+ )
1305
+ hf_raise_for_status(r)
1306
+
1307
+ # Return
1308
+ return HfFileMetadata(
1309
+ commit_hash=r.headers.get(constants.HUGGINGFACE_HEADER_X_REPO_COMMIT),
1310
+ # We favor a custom header indicating the etag of the linked resource, and
1311
+ # we fallback to the regular etag header.
1312
+ etag=_normalize_etag(r.headers.get(constants.HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag")),
1313
+ # Either from response headers (if redirected) or defaults to request url
1314
+ # Do not use directly `url`, as `_request_wrapper` might have followed relative
1315
+ # redirects.
1316
+ location=r.headers.get("Location") or r.request.url, # type: ignore
1317
+ size=_int_or_none(
1318
+ r.headers.get(constants.HUGGINGFACE_HEADER_X_LINKED_SIZE) or r.headers.get("Content-Length")
1319
+ ),
1320
+ )
1321
+
1322
+
1323
+ def _get_metadata_or_catch_error(
1324
+ *,
1325
+ repo_id: str,
1326
+ filename: str,
1327
+ repo_type: str,
1328
+ revision: str,
1329
+ endpoint: Optional[str],
1330
+ proxies: Optional[Dict],
1331
+ etag_timeout: Optional[float],
1332
+ headers: Dict[str, str], # mutated inplace!
1333
+ token: Union[bool, str, None],
1334
+ local_files_only: bool,
1335
+ relative_filename: Optional[str] = None, # only used to store `.no_exists` in cache
1336
+ storage_folder: Optional[str] = None, # only used to store `.no_exists` in cache
1337
+ ) -> Union[
1338
+ # Either an exception is caught and returned
1339
+ Tuple[None, None, None, None, Exception],
1340
+ # Or the metadata is returned as
1341
+ # `(url_to_download, etag, commit_hash, expected_size, None)`
1342
+ Tuple[str, str, str, int, None],
1343
+ ]:
1344
+ """Get metadata for a file on the Hub, safely handling network issues.
1345
+
1346
+ Returns either the etag, commit_hash and expected size of the file, or the error
1347
+ raised while fetching the metadata.
1348
+
1349
+ NOTE: This function mutates `headers` inplace! It removes the `authorization` header
1350
+ if the file is a LFS blob and the domain of the url is different from the
1351
+ domain of the location (typically an S3 bucket).
1352
+ """
1353
+ if local_files_only:
1354
+ return (
1355
+ None,
1356
+ None,
1357
+ None,
1358
+ None,
1359
+ OfflineModeIsEnabled(
1360
+ f"Cannot access file since 'local_files_only=True' as been set. (repo_id: {repo_id}, repo_type: {repo_type}, revision: {revision}, filename: {filename})"
1361
+ ),
1362
+ )
1363
+
1364
+ url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision, endpoint=endpoint)
1365
+ url_to_download: str = url
1366
+ etag: Optional[str] = None
1367
+ commit_hash: Optional[str] = None
1368
+ expected_size: Optional[int] = None
1369
+ head_error_call: Optional[Exception] = None
1370
+
1371
+ # Try to get metadata from the server.
1372
+ # Do not raise yet if the file is not found or not accessible.
1373
+ if not local_files_only:
1374
+ try:
1375
+ try:
1376
+ metadata = get_hf_file_metadata(
1377
+ url=url, proxies=proxies, timeout=etag_timeout, headers=headers, token=token
1378
+ )
1379
+ except EntryNotFoundError as http_error:
1380
+ if storage_folder is not None and relative_filename is not None:
1381
+ # Cache the non-existence of the file
1382
+ commit_hash = http_error.response.headers.get(constants.HUGGINGFACE_HEADER_X_REPO_COMMIT)
1383
+ if commit_hash is not None:
1384
+ no_exist_file_path = Path(storage_folder) / ".no_exist" / commit_hash / relative_filename
1385
+ try:
1386
+ no_exist_file_path.parent.mkdir(parents=True, exist_ok=True)
1387
+ no_exist_file_path.touch()
1388
+ except OSError as e:
1389
+ logger.error(
1390
+ f"Could not cache non-existence of file. Will ignore error and continue. Error: {e}"
1391
+ )
1392
+ _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash)
1393
+ raise
1394
+
1395
+ # Commit hash must exist
1396
+ commit_hash = metadata.commit_hash
1397
+ if commit_hash is None:
1398
+ raise FileMetadataError(
1399
+ "Distant resource does not seem to be on huggingface.co. It is possible that a configuration issue"
1400
+ " prevents you from downloading resources from https://huggingface.co. Please check your firewall"
1401
+ " and proxy settings and make sure your SSL certificates are updated."
1402
+ )
1403
+
1404
+ # Etag must exist
1405
+ # If we don't have any of those, raise an error.
1406
+ etag = metadata.etag
1407
+ if etag is None:
1408
+ raise FileMetadataError(
1409
+ "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility."
1410
+ )
1411
+
1412
+ # Size must exist
1413
+ expected_size = metadata.size
1414
+ if expected_size is None:
1415
+ raise FileMetadataError("Distant resource does not have a Content-Length.")
1416
+
1417
+ # In case of a redirect, save an extra redirect on the request.get call,
1418
+ # and ensure we download the exact atomic version even if it changed
1419
+ # between the HEAD and the GET (unlikely, but hey).
1420
+ #
1421
+ # If url domain is different => we are downloading from a CDN => url is signed => don't send auth
1422
+ # If url domain is the same => redirect due to repo rename AND downloading a regular file => keep auth
1423
+ if url != metadata.location:
1424
+ url_to_download = metadata.location
1425
+ if urlparse(url).netloc != urlparse(metadata.location).netloc:
1426
+ # Remove authorization header when downloading a LFS blob
1427
+ headers.pop("authorization", None)
1428
+ except (requests.exceptions.SSLError, requests.exceptions.ProxyError):
1429
+ # Actually raise for those subclasses of ConnectionError
1430
+ raise
1431
+ except (
1432
+ requests.exceptions.ConnectionError,
1433
+ requests.exceptions.Timeout,
1434
+ OfflineModeIsEnabled,
1435
+ ) as error:
1436
+ # Otherwise, our Internet connection is down.
1437
+ # etag is None
1438
+ head_error_call = error
1439
+ except (RevisionNotFoundError, EntryNotFoundError):
1440
+ # The repo was found but the revision or entry doesn't exist on the Hub (never existed or got deleted)
1441
+ raise
1442
+ except requests.HTTPError as error:
1443
+ # Multiple reasons for an http error:
1444
+ # - Repository is private and invalid/missing token sent
1445
+ # - Repository is gated and invalid/missing token sent
1446
+ # - Hub is down (error 500 or 504)
1447
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
1448
+ # (if it's not the case, the error will be re-raised)
1449
+ head_error_call = error
1450
+ except FileMetadataError as error:
1451
+ # Multiple reasons for a FileMetadataError:
1452
+ # - Wrong network configuration (proxy, firewall, SSL certificates)
1453
+ # - Inconsistency on the Hub
1454
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
1455
+ # (if it's not the case, the error will be re-raised)
1456
+ head_error_call = error
1457
+
1458
+ if not (local_files_only or etag is not None or head_error_call is not None):
1459
+ raise RuntimeError("etag is empty due to uncovered problems")
1460
+
1461
+ return (url_to_download, etag, commit_hash, expected_size, head_error_call) # type: ignore [return-value]
1462
+
1463
+
1464
+ def _raise_on_head_call_error(head_call_error: Exception, force_download: bool, local_files_only: bool) -> NoReturn:
1465
+ """Raise an appropriate error when the HEAD call failed and we cannot locate a local file."""
1466
+
1467
+ # No head call => we cannot force download.
1468
+ if force_download:
1469
+ if local_files_only:
1470
+ raise ValueError("Cannot pass 'force_download=True' and 'local_files_only=True' at the same time.")
1471
+ elif isinstance(head_call_error, OfflineModeIsEnabled):
1472
+ raise ValueError("Cannot pass 'force_download=True' when offline mode is enabled.") from head_call_error
1473
+ else:
1474
+ raise ValueError("Force download failed due to the above error.") from head_call_error
1475
+
1476
+ # No head call + couldn't find an appropriate file on disk => raise an error.
1477
+ if local_files_only:
1478
+ raise LocalEntryNotFoundError(
1479
+ "Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable"
1480
+ " hf.co look-ups and downloads online, set 'local_files_only' to False."
1481
+ )
1482
+ elif isinstance(head_call_error, RepositoryNotFoundError) or isinstance(head_call_error, GatedRepoError):
1483
+ # Repo not found or gated => let's raise the actual error
1484
+ raise head_call_error
1485
+ else:
1486
+ # Otherwise: most likely a connection issue or Hub downtime => let's warn the user
1487
+ raise LocalEntryNotFoundError(
1488
+ "An error happened while trying to locate the file on the Hub and we cannot find the requested files"
1489
+ " in the local cache. Please check your connection and try again or make sure your Internet connection"
1490
+ " is on."
1491
+ ) from head_call_error
1492
+
1493
+
1494
+ def _download_to_tmp_and_move(
1495
+ incomplete_path: Path,
1496
+ destination_path: Path,
1497
+ url_to_download: str,
1498
+ proxies: Optional[Dict],
1499
+ headers: Dict[str, str],
1500
+ expected_size: Optional[int],
1501
+ filename: str,
1502
+ force_download: bool,
1503
+ ) -> None:
1504
+ """Download content from a URL to a destination path.
1505
+
1506
+ Internal logic:
1507
+ - return early if file is already downloaded
1508
+ - resume download if possible (from incomplete file)
1509
+ - do not resume download if `force_download=True` or `HF_HUB_ENABLE_HF_TRANSFER=True`
1510
+ - check disk space before downloading
1511
+ - download content to a temporary file
1512
+ - set correct permissions on temporary file
1513
+ - move the temporary file to the destination path
1514
+
1515
+ Both `incomplete_path` and `destination_path` must be on the same volume to avoid a local copy.
1516
+ """
1517
+ if destination_path.exists() and not force_download:
1518
+ # Do nothing if already exists (except if force_download=True)
1519
+ return
1520
+
1521
+ if incomplete_path.exists() and (force_download or (constants.HF_HUB_ENABLE_HF_TRANSFER and not proxies)):
1522
+ # By default, we will try to resume the download if possible.
1523
+ # However, if the user has set `force_download=True` or if `hf_transfer` is enabled, then we should
1524
+ # not resume the download => delete the incomplete file.
1525
+ message = f"Removing incomplete file '{incomplete_path}'"
1526
+ if force_download:
1527
+ message += " (force_download=True)"
1528
+ elif constants.HF_HUB_ENABLE_HF_TRANSFER and not proxies:
1529
+ message += " (hf_transfer=True)"
1530
+ logger.info(message)
1531
+ incomplete_path.unlink(missing_ok=True)
1532
+
1533
+ with incomplete_path.open("ab") as f:
1534
+ resume_size = f.tell()
1535
+ message = f"Downloading '{filename}' to '{incomplete_path}'"
1536
+ if resume_size > 0 and expected_size is not None:
1537
+ message += f" (resume from {resume_size}/{expected_size})"
1538
+ logger.info(message)
1539
+
1540
+ if expected_size is not None: # might be None if HTTP header not set correctly
1541
+ # Check disk space in both tmp and destination path
1542
+ _check_disk_space(expected_size, incomplete_path.parent)
1543
+ _check_disk_space(expected_size, destination_path.parent)
1544
+
1545
+ http_get(
1546
+ url_to_download,
1547
+ f,
1548
+ proxies=proxies,
1549
+ resume_size=resume_size,
1550
+ headers=headers,
1551
+ expected_size=expected_size,
1552
+ )
1553
+
1554
+ logger.info(f"Download complete. Moving file to {destination_path}")
1555
+ _chmod_and_move(incomplete_path, destination_path)
1556
+
1557
+
1558
+ def _int_or_none(value: Optional[str]) -> Optional[int]:
1559
+ try:
1560
+ return int(value) # type: ignore
1561
+ except (TypeError, ValueError):
1562
+ return None
1563
+
1564
+
1565
+ def _chmod_and_move(src: Path, dst: Path) -> None:
1566
+ """Set correct permission before moving a blob from tmp directory to cache dir.
1567
+
1568
+ Do not take into account the `umask` from the process as there is no convenient way
1569
+ to get it that is thread-safe.
1570
+
1571
+ See:
1572
+ - About umask: https://docs.python.org/3/library/os.html#os.umask
1573
+ - Thread-safety: https://stackoverflow.com/a/70343066
1574
+ - About solution: https://github.com/huggingface/huggingface_hub/pull/1220#issuecomment-1326211591
1575
+ - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1141
1576
+ - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1215
1577
+ """
1578
+ # Get umask by creating a temporary file in the cached repo folder.
1579
+ tmp_file = dst.parent.parent / f"tmp_{uuid.uuid4()}"
1580
+ try:
1581
+ tmp_file.touch()
1582
+ cache_dir_mode = Path(tmp_file).stat().st_mode
1583
+ os.chmod(str(src), stat.S_IMODE(cache_dir_mode))
1584
+ except OSError as e:
1585
+ logger.warning(
1586
+ f"Could not set the permissions on the file '{src}'. "
1587
+ f"Error: {e}.\nContinuing without setting permissions."
1588
+ )
1589
+ finally:
1590
+ try:
1591
+ tmp_file.unlink()
1592
+ except OSError:
1593
+ # fails if `tmp_file.touch()` failed => do nothing
1594
+ # See https://github.com/huggingface/huggingface_hub/issues/2359
1595
+ pass
1596
+
1597
+ shutil.move(str(src), str(dst), copy_function=_copy_no_matter_what)
1598
+
1599
+
1600
+ def _copy_no_matter_what(src: str, dst: str) -> None:
1601
+ """Copy file from src to dst.
1602
+
1603
+ If `shutil.copy2` fails, fallback to `shutil.copyfile`.
1604
+ """
1605
+ try:
1606
+ # Copy file with metadata and permission
1607
+ # Can fail e.g. if dst is an S3 mount
1608
+ shutil.copy2(src, dst)
1609
+ except OSError:
1610
+ # Copy only file content
1611
+ shutil.copyfile(src, dst)
1612
+
1613
+
1614
+ def _get_pointer_path(storage_folder: str, revision: str, relative_filename: str) -> str:
1615
+ # Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks
1616
+ snapshot_path = os.path.join(storage_folder, "snapshots")
1617
+ pointer_path = os.path.join(snapshot_path, revision, relative_filename)
1618
+ if Path(os.path.abspath(snapshot_path)) not in Path(os.path.abspath(pointer_path)).parents:
1619
+ raise ValueError(
1620
+ "Invalid pointer path: cannot create pointer path in snapshot folder if"
1621
+ f" `storage_folder='{storage_folder}'`, `revision='{revision}'` and"
1622
+ f" `relative_filename='{relative_filename}'`."
1623
+ )
1624
+ return pointer_path
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/hf_api.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/__init__.py ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_client.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_common.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities used by both the sync and async inference clients."""
16
+
17
+ import base64
18
+ import io
19
+ import json
20
+ import logging
21
+ from contextlib import contextmanager
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import (
25
+ TYPE_CHECKING,
26
+ Any,
27
+ AsyncIterable,
28
+ BinaryIO,
29
+ ContextManager,
30
+ Dict,
31
+ Generator,
32
+ Iterable,
33
+ List,
34
+ Literal,
35
+ NoReturn,
36
+ Optional,
37
+ Union,
38
+ overload,
39
+ )
40
+
41
+ from requests import HTTPError
42
+
43
+ from huggingface_hub.errors import (
44
+ GenerationError,
45
+ IncompleteGenerationError,
46
+ OverloadedError,
47
+ TextGenerationError,
48
+ UnknownError,
49
+ ValidationError,
50
+ )
51
+
52
+ from ..constants import ENDPOINT
53
+ from ..utils import (
54
+ build_hf_headers,
55
+ get_session,
56
+ hf_raise_for_status,
57
+ is_aiohttp_available,
58
+ is_numpy_available,
59
+ is_pillow_available,
60
+ )
61
+ from ._generated.types import ChatCompletionStreamOutput, TextGenerationStreamOutput
62
+
63
+
64
+ if TYPE_CHECKING:
65
+ from aiohttp import ClientResponse, ClientSession
66
+ from PIL.Image import Image
67
+
68
+ # TYPES
69
+ UrlT = str
70
+ PathT = Union[str, Path]
71
+ BinaryT = Union[bytes, BinaryIO]
72
+ ContentT = Union[BinaryT, PathT, UrlT]
73
+
74
+ # Use to set a Accept: image/png header
75
+ TASKS_EXPECTING_IMAGES = {"text-to-image", "image-to-image"}
76
+
77
+ logger = logging.getLogger(__name__)
78
+
79
+
80
+ # Add dataclass for ModelStatus. We use this dataclass in get_model_status function.
81
+ @dataclass
82
+ class ModelStatus:
83
+ """
84
+ This Dataclass represents the the model status in the Hugging Face Inference API.
85
+
86
+ Args:
87
+ loaded (`bool`):
88
+ If the model is currently loaded into Hugging Face's InferenceAPI. Models
89
+ are loaded on-demand, leading to the user's first request taking longer.
90
+ If a model is loaded, you can be assured that it is in a healthy state.
91
+ state (`str`):
92
+ The current state of the model. This can be 'Loaded', 'Loadable', 'TooBig'.
93
+ If a model's state is 'Loadable', it's not too big and has a supported
94
+ backend. Loadable models are automatically loaded when the user first
95
+ requests inference on the endpoint. This means it is transparent for the
96
+ user to load a model, except that the first call takes longer to complete.
97
+ compute_type (`Dict`):
98
+ Information about the compute resource the model is using or will use, such as 'gpu' type and number of
99
+ replicas.
100
+ framework (`str`):
101
+ The name of the framework that the model was built with, such as 'transformers'
102
+ or 'text-generation-inference'.
103
+ """
104
+
105
+ loaded: bool
106
+ state: str
107
+ compute_type: Dict
108
+ framework: str
109
+
110
+
111
+ ## IMPORT UTILS
112
+
113
+
114
+ def _import_aiohttp():
115
+ # Make sure `aiohttp` is installed on the machine.
116
+ if not is_aiohttp_available():
117
+ raise ImportError("Please install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).")
118
+ import aiohttp
119
+
120
+ return aiohttp
121
+
122
+
123
+ def _import_numpy():
124
+ """Make sure `numpy` is installed on the machine."""
125
+ if not is_numpy_available():
126
+ raise ImportError("Please install numpy to use deal with embeddings (`pip install numpy`).")
127
+ import numpy
128
+
129
+ return numpy
130
+
131
+
132
+ def _import_pil_image():
133
+ """Make sure `PIL` is installed on the machine."""
134
+ if not is_pillow_available():
135
+ raise ImportError(
136
+ "Please install Pillow to use deal with images (`pip install Pillow`). If you don't want the image to be"
137
+ " post-processed, use `client.post(...)` and get the raw response from the server."
138
+ )
139
+ from PIL import Image
140
+
141
+ return Image
142
+
143
+
144
+ ## RECOMMENDED MODELS
145
+
146
+ # Will be globally fetched only once (see '_fetch_recommended_models')
147
+ _RECOMMENDED_MODELS: Optional[Dict[str, Optional[str]]] = None
148
+
149
+
150
+ def _fetch_recommended_models() -> Dict[str, Optional[str]]:
151
+ global _RECOMMENDED_MODELS
152
+ if _RECOMMENDED_MODELS is None:
153
+ response = get_session().get(f"{ENDPOINT}/api/tasks", headers=build_hf_headers())
154
+ hf_raise_for_status(response)
155
+ _RECOMMENDED_MODELS = {
156
+ task: _first_or_none(details["widgetModels"]) for task, details in response.json().items()
157
+ }
158
+ return _RECOMMENDED_MODELS
159
+
160
+
161
+ def _first_or_none(items: List[Any]) -> Optional[Any]:
162
+ try:
163
+ return items[0] or None
164
+ except IndexError:
165
+ return None
166
+
167
+
168
+ ## ENCODING / DECODING UTILS
169
+
170
+
171
+ @overload
172
+ def _open_as_binary(
173
+ content: ContentT,
174
+ ) -> ContextManager[BinaryT]: ... # means "if input is not None, output is not None"
175
+
176
+
177
+ @overload
178
+ def _open_as_binary(
179
+ content: Literal[None],
180
+ ) -> ContextManager[Literal[None]]: ... # means "if input is None, output is None"
181
+
182
+
183
+ @contextmanager # type: ignore
184
+ def _open_as_binary(content: Optional[ContentT]) -> Generator[Optional[BinaryT], None, None]:
185
+ """Open `content` as a binary file, either from a URL, a local path, or raw bytes.
186
+
187
+ Do nothing if `content` is None,
188
+
189
+ TODO: handle a PIL.Image as input
190
+ TODO: handle base64 as input
191
+ """
192
+ # If content is a string => must be either a URL or a path
193
+ if isinstance(content, str):
194
+ if content.startswith("https://") or content.startswith("http://"):
195
+ logger.debug(f"Downloading content from {content}")
196
+ yield get_session().get(content).content # TODO: retrieve as stream and pipe to post request ?
197
+ return
198
+ content = Path(content)
199
+ if not content.exists():
200
+ raise FileNotFoundError(
201
+ f"File not found at {content}. If `data` is a string, it must either be a URL or a path to a local"
202
+ " file. To pass raw content, please encode it as bytes first."
203
+ )
204
+
205
+ # If content is a Path => open it
206
+ if isinstance(content, Path):
207
+ logger.debug(f"Opening content from {content}")
208
+ with content.open("rb") as f:
209
+ yield f
210
+ else:
211
+ # Otherwise: already a file-like object or None
212
+ yield content
213
+
214
+
215
+ def _b64_encode(content: ContentT) -> str:
216
+ """Encode a raw file (image, audio) into base64. Can be byes, an opened file, a path or a URL."""
217
+ with _open_as_binary(content) as data:
218
+ data_as_bytes = data if isinstance(data, bytes) else data.read()
219
+ return base64.b64encode(data_as_bytes).decode()
220
+
221
+
222
+ def _b64_to_image(encoded_image: str) -> "Image":
223
+ """Parse a base64-encoded string into a PIL Image."""
224
+ Image = _import_pil_image()
225
+ return Image.open(io.BytesIO(base64.b64decode(encoded_image)))
226
+
227
+
228
+ def _bytes_to_list(content: bytes) -> List:
229
+ """Parse bytes from a Response object into a Python list.
230
+
231
+ Expects the response body to be JSON-encoded data.
232
+
233
+ NOTE: This is exactly the same implementation as `_bytes_to_dict` and will not complain if the returned data is a
234
+ dictionary. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect.
235
+ """
236
+ return json.loads(content.decode())
237
+
238
+
239
+ def _bytes_to_dict(content: bytes) -> Dict:
240
+ """Parse bytes from a Response object into a Python dictionary.
241
+
242
+ Expects the response body to be JSON-encoded data.
243
+
244
+ NOTE: This is exactly the same implementation as `_bytes_to_list` and will not complain if the returned data is a
245
+ list. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect.
246
+ """
247
+ return json.loads(content.decode())
248
+
249
+
250
+ def _bytes_to_image(content: bytes) -> "Image":
251
+ """Parse bytes from a Response object into a PIL Image.
252
+
253
+ Expects the response body to be raw bytes. To deal with b64 encoded images, use `_b64_to_image` instead.
254
+ """
255
+ Image = _import_pil_image()
256
+ return Image.open(io.BytesIO(content))
257
+
258
+
259
+ ## PAYLOAD UTILS
260
+
261
+
262
+ def _prepare_payload(
263
+ inputs: Union[str, Dict[str, Any], ContentT],
264
+ parameters: Optional[Dict[str, Any]],
265
+ expect_binary: bool = False,
266
+ ) -> Dict[str, Any]:
267
+ """
268
+ Used in `InferenceClient` and `AsyncInferenceClient` to prepare the payload for an API request, handling various input types and parameters.
269
+ `expect_binary` is set to `True` when the inputs are a binary object or a local path or URL. This is the case for image and audio inputs.
270
+ """
271
+ if parameters is None:
272
+ parameters = {}
273
+ parameters = {k: v for k, v in parameters.items() if v is not None}
274
+ has_parameters = len(parameters) > 0
275
+
276
+ is_binary = isinstance(inputs, (bytes, Path))
277
+ # If expect_binary is True, inputs must be a binary object or a local path or a URL.
278
+ if expect_binary and not is_binary and not isinstance(inputs, str):
279
+ raise ValueError(f"Expected binary inputs or a local path or a URL. Got {inputs}") # type: ignore
280
+ # Send inputs as raw content when no parameters are provided
281
+ if expect_binary and not has_parameters:
282
+ return {"data": inputs}
283
+ # If expect_binary is False, inputs must not be a binary object.
284
+ if not expect_binary and is_binary:
285
+ raise ValueError(f"Unexpected binary inputs. Got {inputs}") # type: ignore
286
+
287
+ json: Dict[str, Any] = {}
288
+ # If inputs is a bytes-like object, encode it to base64
289
+ if expect_binary:
290
+ json["inputs"] = _b64_encode(inputs) # type: ignore
291
+ # Otherwise (string, dict, list) send it as is
292
+ else:
293
+ json["inputs"] = inputs
294
+ # Add parameters to the json payload if any
295
+ if has_parameters:
296
+ json["parameters"] = parameters
297
+ return {"json": json}
298
+
299
+
300
+ ## STREAMING UTILS
301
+
302
+
303
+ def _stream_text_generation_response(
304
+ bytes_output_as_lines: Iterable[bytes], details: bool
305
+ ) -> Union[Iterable[str], Iterable[TextGenerationStreamOutput]]:
306
+ """Used in `InferenceClient.text_generation`."""
307
+ # Parse ServerSentEvents
308
+ for byte_payload in bytes_output_as_lines:
309
+ try:
310
+ output = _format_text_generation_stream_output(byte_payload, details)
311
+ except StopIteration:
312
+ break
313
+ if output is not None:
314
+ yield output
315
+
316
+
317
+ async def _async_stream_text_generation_response(
318
+ bytes_output_as_lines: AsyncIterable[bytes], details: bool
319
+ ) -> Union[AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]:
320
+ """Used in `AsyncInferenceClient.text_generation`."""
321
+ # Parse ServerSentEvents
322
+ async for byte_payload in bytes_output_as_lines:
323
+ try:
324
+ output = _format_text_generation_stream_output(byte_payload, details)
325
+ except StopIteration:
326
+ break
327
+ if output is not None:
328
+ yield output
329
+
330
+
331
+ def _format_text_generation_stream_output(
332
+ byte_payload: bytes, details: bool
333
+ ) -> Optional[Union[str, TextGenerationStreamOutput]]:
334
+ if not byte_payload.startswith(b"data:"):
335
+ return None # empty line
336
+
337
+ if byte_payload.strip() == b"data: [DONE]":
338
+ raise StopIteration("[DONE] signal received.")
339
+
340
+ # Decode payload
341
+ payload = byte_payload.decode("utf-8")
342
+ json_payload = json.loads(payload.lstrip("data:").rstrip("/n"))
343
+
344
+ # Either an error as being returned
345
+ if json_payload.get("error") is not None:
346
+ raise _parse_text_generation_error(json_payload["error"], json_payload.get("error_type"))
347
+
348
+ # Or parse token payload
349
+ output = TextGenerationStreamOutput.parse_obj_as_instance(json_payload)
350
+ return output.token.text if not details else output
351
+
352
+
353
+ def _stream_chat_completion_response(
354
+ bytes_lines: Iterable[bytes],
355
+ ) -> Iterable[ChatCompletionStreamOutput]:
356
+ """Used in `InferenceClient.chat_completion` if model is served with TGI."""
357
+ for item in bytes_lines:
358
+ try:
359
+ output = _format_chat_completion_stream_output(item)
360
+ except StopIteration:
361
+ break
362
+ if output is not None:
363
+ yield output
364
+
365
+
366
+ async def _async_stream_chat_completion_response(
367
+ bytes_lines: AsyncIterable[bytes],
368
+ ) -> AsyncIterable[ChatCompletionStreamOutput]:
369
+ """Used in `AsyncInferenceClient.chat_completion`."""
370
+ async for item in bytes_lines:
371
+ try:
372
+ output = _format_chat_completion_stream_output(item)
373
+ except StopIteration:
374
+ break
375
+ if output is not None:
376
+ yield output
377
+
378
+
379
+ def _format_chat_completion_stream_output(
380
+ byte_payload: bytes,
381
+ ) -> Optional[ChatCompletionStreamOutput]:
382
+ if not byte_payload.startswith(b"data:"):
383
+ return None # empty line
384
+
385
+ if byte_payload.strip() == b"data: [DONE]":
386
+ raise StopIteration("[DONE] signal received.")
387
+
388
+ # Decode payload
389
+ payload = byte_payload.decode("utf-8")
390
+ json_payload = json.loads(payload.lstrip("data:").rstrip("/n"))
391
+
392
+ # Either an error as being returned
393
+ if json_payload.get("error") is not None:
394
+ raise _parse_text_generation_error(json_payload["error"], json_payload.get("error_type"))
395
+
396
+ # Or parse token payload
397
+ return ChatCompletionStreamOutput.parse_obj_as_instance(json_payload)
398
+
399
+
400
+ async def _async_yield_from(client: "ClientSession", response: "ClientResponse") -> AsyncIterable[bytes]:
401
+ async for byte_payload in response.content:
402
+ yield byte_payload.strip()
403
+ await client.close()
404
+
405
+
406
+ # "TGI servers" are servers running with the `text-generation-inference` backend.
407
+ # This backend is the go-to solution to run large language models at scale. However,
408
+ # for some smaller models (e.g. "gpt2") the default `transformers` + `api-inference`
409
+ # solution is still in use.
410
+ #
411
+ # Both approaches have very similar APIs, but not exactly the same. What we do first in
412
+ # the `text_generation` method is to assume the model is served via TGI. If we realize
413
+ # it's not the case (i.e. we receive an HTTP 400 Bad Request), we fallback to the
414
+ # default API with a warning message. When that's the case, We remember the unsupported
415
+ # attributes for this model in the `_UNSUPPORTED_TEXT_GENERATION_KWARGS` global variable.
416
+ #
417
+ # In addition, TGI servers have a built-in API route for chat-completion, which is not
418
+ # available on the default API. We use this route to provide a more consistent behavior
419
+ # when available.
420
+ #
421
+ # For more details, see https://github.com/huggingface/text-generation-inference and
422
+ # https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task.
423
+
424
+ _UNSUPPORTED_TEXT_GENERATION_KWARGS: Dict[Optional[str], List[str]] = {}
425
+
426
+
427
+ def _set_unsupported_text_generation_kwargs(model: Optional[str], unsupported_kwargs: List[str]) -> None:
428
+ _UNSUPPORTED_TEXT_GENERATION_KWARGS.setdefault(model, []).extend(unsupported_kwargs)
429
+
430
+
431
+ def _get_unsupported_text_generation_kwargs(model: Optional[str]) -> List[str]:
432
+ return _UNSUPPORTED_TEXT_GENERATION_KWARGS.get(model, [])
433
+
434
+
435
+ # TEXT GENERATION ERRORS
436
+ # ----------------------
437
+ # Text-generation errors are parsed separately to handle as much as possible the errors returned by the text generation
438
+ # inference project (https://github.com/huggingface/text-generation-inference).
439
+ # ----------------------
440
+
441
+
442
+ def raise_text_generation_error(http_error: HTTPError) -> NoReturn:
443
+ """
444
+ Try to parse text-generation-inference error message and raise HTTPError in any case.
445
+
446
+ Args:
447
+ error (`HTTPError`):
448
+ The HTTPError that have been raised.
449
+ """
450
+ # Try to parse a Text Generation Inference error
451
+
452
+ try:
453
+ # Hacky way to retrieve payload in case of aiohttp error
454
+ payload = getattr(http_error, "response_error_payload", None) or http_error.response.json()
455
+ error = payload.get("error")
456
+ error_type = payload.get("error_type")
457
+ except Exception: # no payload
458
+ raise http_error
459
+
460
+ # If error_type => more information than `hf_raise_for_status`
461
+ if error_type is not None:
462
+ exception = _parse_text_generation_error(error, error_type)
463
+ raise exception from http_error
464
+
465
+ # Otherwise, fallback to default error
466
+ raise http_error
467
+
468
+
469
+ def _parse_text_generation_error(error: Optional[str], error_type: Optional[str]) -> TextGenerationError:
470
+ if error_type == "generation":
471
+ return GenerationError(error) # type: ignore
472
+ if error_type == "incomplete_generation":
473
+ return IncompleteGenerationError(error) # type: ignore
474
+ if error_type == "overloaded":
475
+ return OverloadedError(error) # type: ignore
476
+ if error_type == "validation":
477
+ return ValidationError(error) # type: ignore
478
+ return UnknownError(error) # type: ignore
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__init__.py ADDED
File without changes
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (198 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/_async_client.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is auto-generated by `utils/generate_inference_types.py`.
2
+ # Do not modify it manually.
3
+ #
4
+ # ruff: noqa: F401
5
+
6
+ from .audio_classification import (
7
+ AudioClassificationInput,
8
+ AudioClassificationOutputElement,
9
+ AudioClassificationOutputTransform,
10
+ AudioClassificationParameters,
11
+ )
12
+ from .audio_to_audio import AudioToAudioInput, AudioToAudioOutputElement
13
+ from .automatic_speech_recognition import (
14
+ AutomaticSpeechRecognitionEarlyStoppingEnum,
15
+ AutomaticSpeechRecognitionGenerationParameters,
16
+ AutomaticSpeechRecognitionInput,
17
+ AutomaticSpeechRecognitionOutput,
18
+ AutomaticSpeechRecognitionOutputChunk,
19
+ AutomaticSpeechRecognitionParameters,
20
+ )
21
+ from .base import BaseInferenceType
22
+ from .chat_completion import (
23
+ ChatCompletionInput,
24
+ ChatCompletionInputFunctionDefinition,
25
+ ChatCompletionInputFunctionName,
26
+ ChatCompletionInputGrammarType,
27
+ ChatCompletionInputMessage,
28
+ ChatCompletionInputMessageChunk,
29
+ ChatCompletionInputStreamOptions,
30
+ ChatCompletionInputToolType,
31
+ ChatCompletionInputURL,
32
+ ChatCompletionOutput,
33
+ ChatCompletionOutputComplete,
34
+ ChatCompletionOutputFunctionDefinition,
35
+ ChatCompletionOutputLogprob,
36
+ ChatCompletionOutputLogprobs,
37
+ ChatCompletionOutputMessage,
38
+ ChatCompletionOutputToolCall,
39
+ ChatCompletionOutputTopLogprob,
40
+ ChatCompletionOutputUsage,
41
+ ChatCompletionStreamOutput,
42
+ ChatCompletionStreamOutputChoice,
43
+ ChatCompletionStreamOutputDelta,
44
+ ChatCompletionStreamOutputDeltaToolCall,
45
+ ChatCompletionStreamOutputFunction,
46
+ ChatCompletionStreamOutputLogprob,
47
+ ChatCompletionStreamOutputLogprobs,
48
+ ChatCompletionStreamOutputTopLogprob,
49
+ ChatCompletionStreamOutputUsage,
50
+ ToolElement,
51
+ )
52
+ from .depth_estimation import DepthEstimationInput, DepthEstimationOutput
53
+ from .document_question_answering import (
54
+ DocumentQuestionAnsweringInput,
55
+ DocumentQuestionAnsweringInputData,
56
+ DocumentQuestionAnsweringOutputElement,
57
+ DocumentQuestionAnsweringParameters,
58
+ )
59
+ from .feature_extraction import FeatureExtractionInput
60
+ from .fill_mask import FillMaskInput, FillMaskOutputElement, FillMaskParameters
61
+ from .image_classification import (
62
+ ImageClassificationInput,
63
+ ImageClassificationOutputElement,
64
+ ImageClassificationOutputTransform,
65
+ ImageClassificationParameters,
66
+ )
67
+ from .image_segmentation import ImageSegmentationInput, ImageSegmentationOutputElement, ImageSegmentationParameters
68
+ from .image_to_image import ImageToImageInput, ImageToImageOutput, ImageToImageParameters, ImageToImageTargetSize
69
+ from .image_to_text import (
70
+ ImageToTextEarlyStoppingEnum,
71
+ ImageToTextGenerationParameters,
72
+ ImageToTextInput,
73
+ ImageToTextOutput,
74
+ ImageToTextParameters,
75
+ )
76
+ from .object_detection import (
77
+ ObjectDetectionBoundingBox,
78
+ ObjectDetectionInput,
79
+ ObjectDetectionOutputElement,
80
+ ObjectDetectionParameters,
81
+ )
82
+ from .question_answering import (
83
+ QuestionAnsweringInput,
84
+ QuestionAnsweringInputData,
85
+ QuestionAnsweringOutputElement,
86
+ QuestionAnsweringParameters,
87
+ )
88
+ from .sentence_similarity import SentenceSimilarityInput, SentenceSimilarityInputData
89
+ from .summarization import SummarizationInput, SummarizationOutput, SummarizationParameters
90
+ from .table_question_answering import (
91
+ TableQuestionAnsweringInput,
92
+ TableQuestionAnsweringInputData,
93
+ TableQuestionAnsweringOutputElement,
94
+ )
95
+ from .text2text_generation import Text2TextGenerationInput, Text2TextGenerationOutput, Text2TextGenerationParameters
96
+ from .text_classification import (
97
+ TextClassificationInput,
98
+ TextClassificationOutputElement,
99
+ TextClassificationOutputTransform,
100
+ TextClassificationParameters,
101
+ )
102
+ from .text_generation import (
103
+ TextGenerationInput,
104
+ TextGenerationInputGenerateParameters,
105
+ TextGenerationInputGrammarType,
106
+ TextGenerationOutput,
107
+ TextGenerationOutputBestOfSequence,
108
+ TextGenerationOutputDetails,
109
+ TextGenerationOutputPrefillToken,
110
+ TextGenerationOutputToken,
111
+ TextGenerationStreamOutput,
112
+ TextGenerationStreamOutputStreamDetails,
113
+ TextGenerationStreamOutputToken,
114
+ )
115
+ from .text_to_audio import (
116
+ TextToAudioEarlyStoppingEnum,
117
+ TextToAudioGenerationParameters,
118
+ TextToAudioInput,
119
+ TextToAudioOutput,
120
+ TextToAudioParameters,
121
+ )
122
+ from .text_to_image import TextToImageInput, TextToImageOutput, TextToImageParameters, TextToImageTargetSize
123
+ from .text_to_speech import (
124
+ TextToSpeechEarlyStoppingEnum,
125
+ TextToSpeechGenerationParameters,
126
+ TextToSpeechInput,
127
+ TextToSpeechOutput,
128
+ TextToSpeechParameters,
129
+ )
130
+ from .token_classification import (
131
+ TokenClassificationInput,
132
+ TokenClassificationOutputElement,
133
+ TokenClassificationParameters,
134
+ )
135
+ from .translation import TranslationInput, TranslationOutput, TranslationParameters
136
+ from .video_classification import (
137
+ VideoClassificationInput,
138
+ VideoClassificationOutputElement,
139
+ VideoClassificationOutputTransform,
140
+ VideoClassificationParameters,
141
+ )
142
+ from .visual_question_answering import (
143
+ VisualQuestionAnsweringInput,
144
+ VisualQuestionAnsweringInputData,
145
+ VisualQuestionAnsweringOutputElement,
146
+ VisualQuestionAnsweringParameters,
147
+ )
148
+ from .zero_shot_classification import (
149
+ ZeroShotClassificationInput,
150
+ ZeroShotClassificationInputData,
151
+ ZeroShotClassificationOutputElement,
152
+ ZeroShotClassificationParameters,
153
+ )
154
+ from .zero_shot_image_classification import (
155
+ ZeroShotImageClassificationInput,
156
+ ZeroShotImageClassificationInputData,
157
+ ZeroShotImageClassificationOutputElement,
158
+ ZeroShotImageClassificationParameters,
159
+ )
160
+ from .zero_shot_object_detection import (
161
+ ZeroShotObjectDetectionBoundingBox,
162
+ ZeroShotObjectDetectionInput,
163
+ ZeroShotObjectDetectionInputData,
164
+ ZeroShotObjectDetectionOutputElement,
165
+ )
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_classification.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ AudioClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
13
+
14
+
15
+ @dataclass
16
+ class AudioClassificationParameters(BaseInferenceType):
17
+ """Additional inference parameters
18
+ Additional inference parameters for Audio Classification
19
+ """
20
+
21
+ function_to_apply: Optional["AudioClassificationOutputTransform"] = None
22
+ """The function to apply to the output."""
23
+ top_k: Optional[int] = None
24
+ """When specified, limits the output to the top K most probable classes."""
25
+
26
+
27
+ @dataclass
28
+ class AudioClassificationInput(BaseInferenceType):
29
+ """Inputs for Audio Classification inference"""
30
+
31
+ inputs: str
32
+ """The input audio data as a base64-encoded string. If no `parameters` are provided, you can
33
+ also provide the audio data as a raw bytes payload.
34
+ """
35
+ parameters: Optional[AudioClassificationParameters] = None
36
+ """Additional inference parameters"""
37
+
38
+
39
+ @dataclass
40
+ class AudioClassificationOutputElement(BaseInferenceType):
41
+ """Outputs for Audio Classification inference"""
42
+
43
+ label: str
44
+ """The predicted class label."""
45
+ score: float
46
+ """The corresponding probability."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_to_audio.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class AudioToAudioInput(BaseInferenceType):
14
+ """Inputs for Audio to Audio inference"""
15
+
16
+ inputs: Any
17
+ """The input audio data"""
18
+
19
+
20
+ @dataclass
21
+ class AudioToAudioOutputElement(BaseInferenceType):
22
+ """Outputs of inference for the Audio To Audio task
23
+ A generated audio file with its label.
24
+ """
25
+
26
+ blob: Any
27
+ """The generated audio file."""
28
+ content_type: str
29
+ """The content type of audio file."""
30
+ label: str
31
+ """The label of the audio file."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains a base class for all inference types."""
15
+
16
+ import inspect
17
+ import json
18
+ from dataclasses import asdict, dataclass
19
+ from typing import Any, Dict, List, Type, TypeVar, Union, get_args
20
+
21
+
22
+ T = TypeVar("T", bound="BaseInferenceType")
23
+
24
+
25
+ @dataclass
26
+ class BaseInferenceType(dict):
27
+ """Base class for all inference types.
28
+
29
+ Object is a dataclass and a dict for backward compatibility but plan is to remove the dict part in the future.
30
+
31
+ Handle parsing from dict, list and json strings in a permissive way to ensure future-compatibility (e.g. all fields
32
+ are made optional, and non-expected fields are added as dict attributes).
33
+ """
34
+
35
+ @classmethod
36
+ def parse_obj_as_list(cls: Type[T], data: Union[bytes, str, List, Dict]) -> List[T]:
37
+ """Alias to parse server response and return a single instance.
38
+
39
+ See `parse_obj` for more details.
40
+ """
41
+ output = cls.parse_obj(data)
42
+ if not isinstance(output, list):
43
+ raise ValueError(f"Invalid input data for {cls}. Expected a list, but got {type(output)}.")
44
+ return output
45
+
46
+ @classmethod
47
+ def parse_obj_as_instance(cls: Type[T], data: Union[bytes, str, List, Dict]) -> T:
48
+ """Alias to parse server response and return a single instance.
49
+
50
+ See `parse_obj` for more details.
51
+ """
52
+ output = cls.parse_obj(data)
53
+ if isinstance(output, list):
54
+ raise ValueError(f"Invalid input data for {cls}. Expected a single instance, but got a list.")
55
+ return output
56
+
57
+ @classmethod
58
+ def parse_obj(cls: Type[T], data: Union[bytes, str, List, Dict]) -> Union[List[T], T]:
59
+ """Parse server response as a dataclass or list of dataclasses.
60
+
61
+ To enable future-compatibility, we want to handle cases where the server return more fields than expected.
62
+ In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
63
+ added as dict attributes.
64
+ """
65
+ # Parse server response (from bytes)
66
+ if isinstance(data, bytes):
67
+ data = data.decode()
68
+ if isinstance(data, str):
69
+ data = json.loads(data)
70
+
71
+ # If a list, parse each item individually
72
+ if isinstance(data, List):
73
+ return [cls.parse_obj(d) for d in data] # type: ignore [misc]
74
+
75
+ # At this point, we expect a dict
76
+ if not isinstance(data, dict):
77
+ raise ValueError(f"Invalid data type: {type(data)}")
78
+
79
+ init_values = {}
80
+ other_values = {}
81
+ for key, value in data.items():
82
+ key = normalize_key(key)
83
+ if key in cls.__dataclass_fields__ and cls.__dataclass_fields__[key].init:
84
+ if isinstance(value, dict) or isinstance(value, list):
85
+ field_type = cls.__dataclass_fields__[key].type
86
+
87
+ # if `field_type` is a `BaseInferenceType`, parse it
88
+ if inspect.isclass(field_type) and issubclass(field_type, BaseInferenceType):
89
+ value = field_type.parse_obj(value)
90
+
91
+ # otherwise, recursively parse nested dataclasses (if possible)
92
+ # `get_args` returns handle Union and Optional for us
93
+ else:
94
+ expected_types = get_args(field_type)
95
+ for expected_type in expected_types:
96
+ if getattr(expected_type, "_name", None) == "List":
97
+ expected_type = get_args(expected_type)[
98
+ 0
99
+ ] # assume same type for all items in the list
100
+ if inspect.isclass(expected_type) and issubclass(expected_type, BaseInferenceType):
101
+ value = expected_type.parse_obj(value)
102
+ break
103
+ init_values[key] = value
104
+ else:
105
+ other_values[key] = value
106
+
107
+ # Make all missing fields default to None
108
+ # => ensure that dataclass initialization will never fail even if the server does not return all fields.
109
+ for key in cls.__dataclass_fields__:
110
+ if key not in init_values:
111
+ init_values[key] = None
112
+
113
+ # Initialize dataclass with expected values
114
+ item = cls(**init_values)
115
+
116
+ # Add remaining fields as dict attributes
117
+ item.update(other_values)
118
+ return item
119
+
120
+ def __post_init__(self):
121
+ self.update(asdict(self))
122
+
123
+ def __setitem__(self, __key: Any, __value: Any) -> None:
124
+ # Hacky way to keep dataclass values in sync when dict is updated
125
+ super().__setitem__(__key, __value)
126
+ if __key in self.__dataclass_fields__ and getattr(self, __key, None) != __value:
127
+ self.__setattr__(__key, __value)
128
+ return
129
+
130
+ def __setattr__(self, __name: str, __value: Any) -> None:
131
+ # Hacky way to keep dict values is sync when dataclass is updated
132
+ super().__setattr__(__name, __value)
133
+ if self.get(__name) != __value:
134
+ self[__name] = __value
135
+ return
136
+
137
+
138
+ def normalize_key(key: str) -> str:
139
+ # e.g "content-type" -> "content_type", "Accept" -> "accept"
140
+ return key.replace("-", "_").replace(" ", "_").lower()
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/document_question_answering.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, List, Optional, Union
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class DocumentQuestionAnsweringInputData(BaseInferenceType):
14
+ """One (document, question) pair to answer"""
15
+
16
+ image: Any
17
+ """The image on which the question is asked"""
18
+ question: str
19
+ """A question to ask of the document"""
20
+
21
+
22
+ @dataclass
23
+ class DocumentQuestionAnsweringParameters(BaseInferenceType):
24
+ """Additional inference parameters
25
+ Additional inference parameters for Document Question Answering
26
+ """
27
+
28
+ doc_stride: Optional[int] = None
29
+ """If the words in the document are too long to fit with the question for the model, it will
30
+ be split in several chunks with some overlap. This argument controls the size of that
31
+ overlap.
32
+ """
33
+ handle_impossible_answer: Optional[bool] = None
34
+ """Whether to accept impossible as an answer"""
35
+ lang: Optional[str] = None
36
+ """Language to use while running OCR. Defaults to english."""
37
+ max_answer_len: Optional[int] = None
38
+ """The maximum length of predicted answers (e.g., only answers with a shorter length are
39
+ considered).
40
+ """
41
+ max_question_len: Optional[int] = None
42
+ """The maximum length of the question after tokenization. It will be truncated if needed."""
43
+ max_seq_len: Optional[int] = None
44
+ """The maximum length of the total sentence (context + question) in tokens of each chunk
45
+ passed to the model. The context will be split in several chunks (using doc_stride as
46
+ overlap) if needed.
47
+ """
48
+ top_k: Optional[int] = None
49
+ """The number of answers to return (will be chosen by order of likelihood). Can return less
50
+ than top_k answers if there are not enough options available within the context.
51
+ """
52
+ word_boxes: Optional[List[Union[List[float], str]]] = None
53
+ """A list of words and bounding boxes (normalized 0->1000). If provided, the inference will
54
+ skip the OCR step and use the provided bounding boxes instead.
55
+ """
56
+
57
+
58
+ @dataclass
59
+ class DocumentQuestionAnsweringInput(BaseInferenceType):
60
+ """Inputs for Document Question Answering inference"""
61
+
62
+ inputs: DocumentQuestionAnsweringInputData
63
+ """One (document, question) pair to answer"""
64
+ parameters: Optional[DocumentQuestionAnsweringParameters] = None
65
+ """Additional inference parameters"""
66
+
67
+
68
+ @dataclass
69
+ class DocumentQuestionAnsweringOutputElement(BaseInferenceType):
70
+ """Outputs of inference for the Document Question Answering task"""
71
+
72
+ answer: str
73
+ """The answer to the question."""
74
+ end: int
75
+ """The end word index of the answer (in the OCR’d version of the input or provided word
76
+ boxes).
77
+ """
78
+ score: float
79
+ """The probability associated to the answer."""
80
+ start: int
81
+ """The start word index of the answer (in the OCR’d version of the input or provided word
82
+ boxes).
83
+ """
84
+ words: List[int]
85
+ """The index of each word/box pair that is in the answer"""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/feature_extraction.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ FeatureExtractionInputTruncationDirection = Literal["Left", "Right"]
13
+
14
+
15
+ @dataclass
16
+ class FeatureExtractionInput(BaseInferenceType):
17
+ """Feature Extraction Input.
18
+ Auto-generated from TEI specs.
19
+ For more details, check out
20
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tei-import.ts.
21
+ """
22
+
23
+ inputs: str
24
+ """The text to embed."""
25
+ normalize: Optional[bool] = None
26
+ prompt_name: Optional[str] = None
27
+ """The name of the prompt that should be used by for encoding. If not set, no prompt
28
+ will be applied.
29
+ Must be a key in the `Sentence Transformers` configuration `prompts` dictionary.
30
+ For example if ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ",
31
+ ...},
32
+ then the sentence "What is the capital of France?" will be encoded as
33
+ "query: What is the capital of France?" because the prompt text will be prepended before
34
+ any text to encode.
35
+ """
36
+ truncate: Optional[bool] = None
37
+ truncation_direction: Optional["FeatureExtractionInputTruncationDirection"] = None
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_classification.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ ImageClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
13
+
14
+
15
+ @dataclass
16
+ class ImageClassificationParameters(BaseInferenceType):
17
+ """Additional inference parameters
18
+ Additional inference parameters for Image Classification
19
+ """
20
+
21
+ function_to_apply: Optional["ImageClassificationOutputTransform"] = None
22
+ """The function to apply to the output."""
23
+ top_k: Optional[int] = None
24
+ """When specified, limits the output to the top K most probable classes."""
25
+
26
+
27
+ @dataclass
28
+ class ImageClassificationInput(BaseInferenceType):
29
+ """Inputs for Image Classification inference"""
30
+
31
+ inputs: str
32
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
33
+ also provide the image data as a raw bytes payload.
34
+ """
35
+ parameters: Optional[ImageClassificationParameters] = None
36
+ """Additional inference parameters"""
37
+
38
+
39
+ @dataclass
40
+ class ImageClassificationOutputElement(BaseInferenceType):
41
+ """Outputs of inference for the Image Classification task"""
42
+
43
+ label: str
44
+ """The predicted class label."""
45
+ score: float
46
+ """The corresponding probability."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_segmentation.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ ImageSegmentationSubtask = Literal["instance", "panoptic", "semantic"]
13
+
14
+
15
+ @dataclass
16
+ class ImageSegmentationParameters(BaseInferenceType):
17
+ """Additional inference parameters
18
+ Additional inference parameters for Image Segmentation
19
+ """
20
+
21
+ mask_threshold: Optional[float] = None
22
+ """Threshold to use when turning the predicted masks into binary values."""
23
+ overlap_mask_area_threshold: Optional[float] = None
24
+ """Mask overlap threshold to eliminate small, disconnected segments."""
25
+ subtask: Optional["ImageSegmentationSubtask"] = None
26
+ """Segmentation task to be performed, depending on model capabilities."""
27
+ threshold: Optional[float] = None
28
+ """Probability threshold to filter out predicted masks."""
29
+
30
+
31
+ @dataclass
32
+ class ImageSegmentationInput(BaseInferenceType):
33
+ """Inputs for Image Segmentation inference"""
34
+
35
+ inputs: str
36
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
37
+ also provide the image data as a raw bytes payload.
38
+ """
39
+ parameters: Optional[ImageSegmentationParameters] = None
40
+ """Additional inference parameters"""
41
+
42
+
43
+ @dataclass
44
+ class ImageSegmentationOutputElement(BaseInferenceType):
45
+ """Outputs of inference for the Image Segmentation task
46
+ A predicted mask / segment
47
+ """
48
+
49
+ label: str
50
+ """The label of the predicted segment."""
51
+ mask: str
52
+ """The corresponding mask as a black-and-white image (base64-encoded)."""
53
+ score: Optional[float] = None
54
+ """The score or confidence degree the model has."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_image.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, List, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class ImageToImageTargetSize(BaseInferenceType):
14
+ """The size in pixel of the output image."""
15
+
16
+ height: int
17
+ width: int
18
+
19
+
20
+ @dataclass
21
+ class ImageToImageParameters(BaseInferenceType):
22
+ """Additional inference parameters
23
+ Additional inference parameters for Image To Image
24
+ """
25
+
26
+ guidance_scale: Optional[float] = None
27
+ """For diffusion models. A higher guidance scale value encourages the model to generate
28
+ images closely linked to the text prompt at the expense of lower image quality.
29
+ """
30
+ negative_prompt: Optional[List[str]] = None
31
+ """One or several prompt to guide what NOT to include in image generation."""
32
+ num_inference_steps: Optional[int] = None
33
+ """For diffusion models. The number of denoising steps. More denoising steps usually lead to
34
+ a higher quality image at the expense of slower inference.
35
+ """
36
+ target_size: Optional[ImageToImageTargetSize] = None
37
+ """The size in pixel of the output image."""
38
+
39
+
40
+ @dataclass
41
+ class ImageToImageInput(BaseInferenceType):
42
+ """Inputs for Image To Image inference"""
43
+
44
+ inputs: str
45
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
46
+ also provide the image data as a raw bytes payload.
47
+ """
48
+ parameters: Optional[ImageToImageParameters] = None
49
+ """Additional inference parameters"""
50
+
51
+
52
+ @dataclass
53
+ class ImageToImageOutput(BaseInferenceType):
54
+ """Outputs of inference for the Image To Image task"""
55
+
56
+ image: Any
57
+ """The output image returned as raw bytes in the payload."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ SummarizationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
13
+
14
+
15
+ @dataclass
16
+ class SummarizationParameters(BaseInferenceType):
17
+ """Additional inference parameters.
18
+ Additional inference parameters for summarization.
19
+ """
20
+
21
+ clean_up_tokenization_spaces: Optional[bool] = None
22
+ """Whether to clean up the potential extra spaces in the text output."""
23
+ generate_parameters: Optional[Dict[str, Any]] = None
24
+ """Additional parametrization of the text generation algorithm."""
25
+ truncation: Optional["SummarizationTruncationStrategy"] = None
26
+ """The truncation strategy to use."""
27
+
28
+
29
+ @dataclass
30
+ class SummarizationInput(BaseInferenceType):
31
+ """Inputs for Summarization inference"""
32
+
33
+ inputs: str
34
+ """The input text to summarize."""
35
+ parameters: Optional[SummarizationParameters] = None
36
+ """Additional inference parameters."""
37
+
38
+
39
+ @dataclass
40
+ class SummarizationOutput(BaseInferenceType):
41
+ """Outputs of inference for the Summarization task"""
42
+
43
+ summary_text: str
44
+ """The summarized text."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/table_question_answering.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class TableQuestionAnsweringInputData(BaseInferenceType):
14
+ """One (table, question) pair to answer"""
15
+
16
+ question: str
17
+ """The question to be answered about the table"""
18
+ table: Dict[str, List[str]]
19
+ """The table to serve as context for the questions"""
20
+
21
+
22
+ @dataclass
23
+ class TableQuestionAnsweringInput(BaseInferenceType):
24
+ """Inputs for Table Question Answering inference"""
25
+
26
+ inputs: TableQuestionAnsweringInputData
27
+ """One (table, question) pair to answer"""
28
+ parameters: Optional[Dict[str, Any]] = None
29
+ """Additional inference parameters"""
30
+
31
+
32
+ @dataclass
33
+ class TableQuestionAnsweringOutputElement(BaseInferenceType):
34
+ """Outputs of inference for the Table Question Answering task"""
35
+
36
+ answer: str
37
+ """The answer of the question given the table. If there is an aggregator, the answer will be
38
+ preceded by `AGGREGATOR >`.
39
+ """
40
+ cells: List[str]
41
+ """List of strings made up of the answer cell values."""
42
+ coordinates: List[List[int]]
43
+ """Coordinates of the cells of the answers."""
44
+ aggregator: Optional[str] = None
45
+ """If the model has an aggregator, this returns the aggregator."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text2text_generation.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ Text2TextGenerationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
13
+
14
+
15
+ @dataclass
16
+ class Text2TextGenerationParameters(BaseInferenceType):
17
+ """Additional inference parameters
18
+ Additional inference parameters for Text2text Generation
19
+ """
20
+
21
+ clean_up_tokenization_spaces: Optional[bool] = None
22
+ """Whether to clean up the potential extra spaces in the text output."""
23
+ generate_parameters: Optional[Dict[str, Any]] = None
24
+ """Additional parametrization of the text generation algorithm"""
25
+ truncation: Optional["Text2TextGenerationTruncationStrategy"] = None
26
+ """The truncation strategy to use"""
27
+
28
+
29
+ @dataclass
30
+ class Text2TextGenerationInput(BaseInferenceType):
31
+ """Inputs for Text2text Generation inference"""
32
+
33
+ inputs: str
34
+ """The input text data"""
35
+ parameters: Optional[Text2TextGenerationParameters] = None
36
+ """Additional inference parameters"""
37
+
38
+
39
+ @dataclass
40
+ class Text2TextGenerationOutput(BaseInferenceType):
41
+ """Outputs of inference for the Text2text Generation task"""
42
+
43
+ generated_text: Any
44
+ text2_text_generation_output_generated_text: Optional[str] = None
45
+ """The generated text."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_classification.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ TextClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
13
+
14
+
15
+ @dataclass
16
+ class TextClassificationParameters(BaseInferenceType):
17
+ """
18
+ Additional inference parameters for Text Classification.
19
+ """
20
+
21
+ function_to_apply: Optional["TextClassificationOutputTransform"] = None
22
+ """
23
+ The function to apply to the output.
24
+ """
25
+ top_k: Optional[int] = None
26
+ """
27
+ When specified, limits the output to the top K most probable classes.
28
+ """
29
+
30
+
31
+ @dataclass
32
+ class TextClassificationInput(BaseInferenceType):
33
+ """Inputs for Text Classification inference"""
34
+
35
+ inputs: str
36
+ """The text to classify"""
37
+ parameters: Optional[TextClassificationParameters] = None
38
+ """Additional inference parameters"""
39
+
40
+
41
+ @dataclass
42
+ class TextClassificationOutputElement(BaseInferenceType):
43
+ """Outputs of inference for the Text Classification task"""
44
+
45
+ label: str
46
+ """The predicted class label."""
47
+ score: float
48
+ """The corresponding probability."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, List, Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ TypeEnum = Literal["json", "regex"]
13
+
14
+
15
+ @dataclass
16
+ class TextGenerationInputGrammarType(BaseInferenceType):
17
+ type: "TypeEnum"
18
+ value: Any
19
+ """A string that represents a [JSON Schema](https://json-schema.org/).
20
+ JSON Schema is a declarative language that allows to annotate JSON documents
21
+ with types and descriptions.
22
+ """
23
+
24
+
25
+ @dataclass
26
+ class TextGenerationInputGenerateParameters(BaseInferenceType):
27
+ adapter_id: Optional[str] = None
28
+ """Lora adapter id"""
29
+ best_of: Optional[int] = None
30
+ """Generate best_of sequences and return the one if the highest token logprobs."""
31
+ decoder_input_details: Optional[bool] = None
32
+ """Whether to return decoder input token logprobs and ids."""
33
+ details: Optional[bool] = None
34
+ """Whether to return generation details."""
35
+ do_sample: Optional[bool] = None
36
+ """Activate logits sampling."""
37
+ frequency_penalty: Optional[float] = None
38
+ """The parameter for frequency penalty. 1.0 means no penalty
39
+ Penalize new tokens based on their existing frequency in the text so far,
40
+ decreasing the model's likelihood to repeat the same line verbatim.
41
+ """
42
+ grammar: Optional[TextGenerationInputGrammarType] = None
43
+ max_new_tokens: Optional[int] = None
44
+ """Maximum number of tokens to generate."""
45
+ repetition_penalty: Optional[float] = None
46
+ """The parameter for repetition penalty. 1.0 means no penalty.
47
+ See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
48
+ """
49
+ return_full_text: Optional[bool] = None
50
+ """Whether to prepend the prompt to the generated text"""
51
+ seed: Optional[int] = None
52
+ """Random sampling seed."""
53
+ stop: Optional[List[str]] = None
54
+ """Stop generating tokens if a member of `stop` is generated."""
55
+ temperature: Optional[float] = None
56
+ """The value used to module the logits distribution."""
57
+ top_k: Optional[int] = None
58
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
59
+ top_n_tokens: Optional[int] = None
60
+ """The number of highest probability vocabulary tokens to keep for top-n-filtering."""
61
+ top_p: Optional[float] = None
62
+ """Top-p value for nucleus sampling."""
63
+ truncate: Optional[int] = None
64
+ """Truncate inputs tokens to the given size."""
65
+ typical_p: Optional[float] = None
66
+ """Typical Decoding mass
67
+ See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666)
68
+ for more information.
69
+ """
70
+ watermark: Optional[bool] = None
71
+ """Watermarking with [A Watermark for Large Language
72
+ Models](https://arxiv.org/abs/2301.10226).
73
+ """
74
+
75
+
76
+ @dataclass
77
+ class TextGenerationInput(BaseInferenceType):
78
+ """Text Generation Input.
79
+ Auto-generated from TGI specs.
80
+ For more details, check out
81
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
82
+ """
83
+
84
+ inputs: str
85
+ parameters: Optional[TextGenerationInputGenerateParameters] = None
86
+ stream: Optional[bool] = None
87
+
88
+
89
+ TextGenerationOutputFinishReason = Literal["length", "eos_token", "stop_sequence"]
90
+
91
+
92
+ @dataclass
93
+ class TextGenerationOutputPrefillToken(BaseInferenceType):
94
+ id: int
95
+ logprob: float
96
+ text: str
97
+
98
+
99
+ @dataclass
100
+ class TextGenerationOutputToken(BaseInferenceType):
101
+ id: int
102
+ logprob: float
103
+ special: bool
104
+ text: str
105
+
106
+
107
+ @dataclass
108
+ class TextGenerationOutputBestOfSequence(BaseInferenceType):
109
+ finish_reason: "TextGenerationOutputFinishReason"
110
+ generated_text: str
111
+ generated_tokens: int
112
+ prefill: List[TextGenerationOutputPrefillToken]
113
+ tokens: List[TextGenerationOutputToken]
114
+ seed: Optional[int] = None
115
+ top_tokens: Optional[List[List[TextGenerationOutputToken]]] = None
116
+
117
+
118
+ @dataclass
119
+ class TextGenerationOutputDetails(BaseInferenceType):
120
+ finish_reason: "TextGenerationOutputFinishReason"
121
+ generated_tokens: int
122
+ prefill: List[TextGenerationOutputPrefillToken]
123
+ tokens: List[TextGenerationOutputToken]
124
+ best_of_sequences: Optional[List[TextGenerationOutputBestOfSequence]] = None
125
+ seed: Optional[int] = None
126
+ top_tokens: Optional[List[List[TextGenerationOutputToken]]] = None
127
+
128
+
129
+ @dataclass
130
+ class TextGenerationOutput(BaseInferenceType):
131
+ """Text Generation Output.
132
+ Auto-generated from TGI specs.
133
+ For more details, check out
134
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
135
+ """
136
+
137
+ generated_text: str
138
+ details: Optional[TextGenerationOutputDetails] = None
139
+
140
+
141
+ @dataclass
142
+ class TextGenerationStreamOutputStreamDetails(BaseInferenceType):
143
+ finish_reason: "TextGenerationOutputFinishReason"
144
+ generated_tokens: int
145
+ input_length: int
146
+ seed: Optional[int] = None
147
+
148
+
149
+ @dataclass
150
+ class TextGenerationStreamOutputToken(BaseInferenceType):
151
+ id: int
152
+ logprob: float
153
+ special: bool
154
+ text: str
155
+
156
+
157
+ @dataclass
158
+ class TextGenerationStreamOutput(BaseInferenceType):
159
+ """Text Generation Stream Output.
160
+ Auto-generated from TGI specs.
161
+ For more details, check out
162
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
163
+ """
164
+
165
+ index: int
166
+ token: TextGenerationStreamOutputToken
167
+ details: Optional[TextGenerationStreamOutputStreamDetails] = None
168
+ generated_text: Optional[str] = None
169
+ top_tokens: Optional[List[TextGenerationStreamOutputToken]] = None
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_audio.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal, Optional, Union
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ TextToAudioEarlyStoppingEnum = Literal["never"]
13
+
14
+
15
+ @dataclass
16
+ class TextToAudioGenerationParameters(BaseInferenceType):
17
+ """Parametrization of the text generation process
18
+ Ad-hoc parametrization of the text generation process
19
+ """
20
+
21
+ do_sample: Optional[bool] = None
22
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
23
+ early_stopping: Optional[Union[bool, "TextToAudioEarlyStoppingEnum"]] = None
24
+ """Controls the stopping condition for beam-based methods."""
25
+ epsilon_cutoff: Optional[float] = None
26
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
27
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
28
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
29
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
30
+ """
31
+ eta_cutoff: Optional[float] = None
32
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
33
+ float strictly between 0 and 1, a token is only considered if it is greater than either
34
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
35
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
36
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
37
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
38
+ for more details.
39
+ """
40
+ max_length: Optional[int] = None
41
+ """The maximum length (in tokens) of the generated text, including the input."""
42
+ max_new_tokens: Optional[int] = None
43
+ """The maximum number of tokens to generate. Takes precedence over maxLength."""
44
+ min_length: Optional[int] = None
45
+ """The minimum length (in tokens) of the generated text, including the input."""
46
+ min_new_tokens: Optional[int] = None
47
+ """The minimum number of tokens to generate. Takes precedence over maxLength."""
48
+ num_beam_groups: Optional[int] = None
49
+ """Number of groups to divide num_beams into in order to ensure diversity among different
50
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
51
+ """
52
+ num_beams: Optional[int] = None
53
+ """Number of beams to use for beam search."""
54
+ penalty_alpha: Optional[float] = None
55
+ """The value balances the model confidence and the degeneration penalty in contrastive
56
+ search decoding.
57
+ """
58
+ temperature: Optional[float] = None
59
+ """The value used to modulate the next token probabilities."""
60
+ top_k: Optional[int] = None
61
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
62
+ top_p: Optional[float] = None
63
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
64
+ that add up to top_p or higher are kept for generation.
65
+ """
66
+ typical_p: Optional[float] = None
67
+ """Local typicality measures how similar the conditional probability of predicting a target
68
+ token next is to the expected conditional probability of predicting a random token next,
69
+ given the partial text already generated. If set to float < 1, the smallest set of the
70
+ most locally typical tokens with probabilities that add up to typical_p or higher are
71
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
72
+ """
73
+ use_cache: Optional[bool] = None
74
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
75
+
76
+
77
+ @dataclass
78
+ class TextToAudioParameters(BaseInferenceType):
79
+ """Additional inference parameters
80
+ Additional inference parameters for Text To Audio
81
+ """
82
+
83
+ generate: Optional[TextToAudioGenerationParameters] = None
84
+ """Parametrization of the text generation process"""
85
+
86
+
87
+ @dataclass
88
+ class TextToAudioInput(BaseInferenceType):
89
+ """Inputs for Text To Audio inference"""
90
+
91
+ inputs: str
92
+ """The input text data"""
93
+ parameters: Optional[TextToAudioParameters] = None
94
+ """Additional inference parameters"""
95
+
96
+
97
+ @dataclass
98
+ class TextToAudioOutput(BaseInferenceType):
99
+ """Outputs of inference for the Text To Audio task"""
100
+
101
+ audio: Any
102
+ """The generated audio waveform."""
103
+ sampling_rate: Any
104
+ text_to_audio_output_sampling_rate: Optional[float] = None
105
+ """The sampling rate of the generated audio waveform."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_speech.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal, Optional, Union
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ TextToSpeechEarlyStoppingEnum = Literal["never"]
13
+
14
+
15
+ @dataclass
16
+ class TextToSpeechGenerationParameters(BaseInferenceType):
17
+ """Parametrization of the text generation process
18
+ Ad-hoc parametrization of the text generation process
19
+ """
20
+
21
+ do_sample: Optional[bool] = None
22
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
23
+ early_stopping: Optional[Union[bool, "TextToSpeechEarlyStoppingEnum"]] = None
24
+ """Controls the stopping condition for beam-based methods."""
25
+ epsilon_cutoff: Optional[float] = None
26
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
27
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
28
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
29
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
30
+ """
31
+ eta_cutoff: Optional[float] = None
32
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
33
+ float strictly between 0 and 1, a token is only considered if it is greater than either
34
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
35
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
36
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
37
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
38
+ for more details.
39
+ """
40
+ max_length: Optional[int] = None
41
+ """The maximum length (in tokens) of the generated text, including the input."""
42
+ max_new_tokens: Optional[int] = None
43
+ """The maximum number of tokens to generate. Takes precedence over maxLength."""
44
+ min_length: Optional[int] = None
45
+ """The minimum length (in tokens) of the generated text, including the input."""
46
+ min_new_tokens: Optional[int] = None
47
+ """The minimum number of tokens to generate. Takes precedence over maxLength."""
48
+ num_beam_groups: Optional[int] = None
49
+ """Number of groups to divide num_beams into in order to ensure diversity among different
50
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
51
+ """
52
+ num_beams: Optional[int] = None
53
+ """Number of beams to use for beam search."""
54
+ penalty_alpha: Optional[float] = None
55
+ """The value balances the model confidence and the degeneration penalty in contrastive
56
+ search decoding.
57
+ """
58
+ temperature: Optional[float] = None
59
+ """The value used to modulate the next token probabilities."""
60
+ top_k: Optional[int] = None
61
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
62
+ top_p: Optional[float] = None
63
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
64
+ that add up to top_p or higher are kept for generation.
65
+ """
66
+ typical_p: Optional[float] = None
67
+ """Local typicality measures how similar the conditional probability of predicting a target
68
+ token next is to the expected conditional probability of predicting a random token next,
69
+ given the partial text already generated. If set to float < 1, the smallest set of the
70
+ most locally typical tokens with probabilities that add up to typical_p or higher are
71
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
72
+ """
73
+ use_cache: Optional[bool] = None
74
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
75
+
76
+
77
+ @dataclass
78
+ class TextToSpeechParameters(BaseInferenceType):
79
+ """Additional inference parameters
80
+ Additional inference parameters for Text To Speech
81
+ """
82
+
83
+ generate: Optional[TextToSpeechGenerationParameters] = None
84
+ """Parametrization of the text generation process"""
85
+
86
+
87
+ @dataclass
88
+ class TextToSpeechInput(BaseInferenceType):
89
+ """Inputs for Text To Speech inference"""
90
+
91
+ inputs: str
92
+ """The input text data"""
93
+ parameters: Optional[TextToSpeechParameters] = None
94
+ """Additional inference parameters"""
95
+
96
+
97
+ @dataclass
98
+ class TextToSpeechOutput(BaseInferenceType):
99
+ """Outputs for Text to Speech inference
100
+ Outputs of inference for the Text To Audio task
101
+ """
102
+
103
+ audio: Any
104
+ """The generated audio waveform."""
105
+ sampling_rate: Any
106
+ text_to_speech_output_sampling_rate: Optional[float] = None
107
+ """The sampling rate of the generated audio waveform."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/video_classification.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ VideoClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
13
+
14
+
15
+ @dataclass
16
+ class VideoClassificationParameters(BaseInferenceType):
17
+ """Additional inference parameters
18
+ Additional inference parameters for Video Classification
19
+ """
20
+
21
+ frame_sampling_rate: Optional[int] = None
22
+ """The sampling rate used to select frames from the video."""
23
+ function_to_apply: Optional["VideoClassificationOutputTransform"] = None
24
+ num_frames: Optional[int] = None
25
+ """The number of sampled frames to consider for classification."""
26
+ top_k: Optional[int] = None
27
+ """When specified, limits the output to the top K most probable classes."""
28
+
29
+
30
+ @dataclass
31
+ class VideoClassificationInput(BaseInferenceType):
32
+ """Inputs for Video Classification inference"""
33
+
34
+ inputs: Any
35
+ """The input video data"""
36
+ parameters: Optional[VideoClassificationParameters] = None
37
+ """Additional inference parameters"""
38
+
39
+
40
+ @dataclass
41
+ class VideoClassificationOutputElement(BaseInferenceType):
42
+ """Outputs of inference for the Video Classification task"""
43
+
44
+ label: str
45
+ """The predicted class label."""
46
+ score: float
47
+ """The corresponding probability."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_classification.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import List, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class ZeroShotClassificationInputData(BaseInferenceType):
14
+ """The input text data, with candidate labels"""
15
+
16
+ candidate_labels: List[str]
17
+ """The set of possible class labels to classify the text into."""
18
+ text: str
19
+ """The text to classify"""
20
+
21
+
22
+ @dataclass
23
+ class ZeroShotClassificationParameters(BaseInferenceType):
24
+ """Additional inference parameters
25
+ Additional inference parameters for Zero Shot Classification
26
+ """
27
+
28
+ hypothesis_template: Optional[str] = None
29
+ """The sentence used in conjunction with candidateLabels to attempt the text classification
30
+ by replacing the placeholder with the candidate labels.
31
+ """
32
+ multi_label: Optional[bool] = None
33
+ """Whether multiple candidate labels can be true. If false, the scores are normalized such
34
+ that the sum of the label likelihoods for each sequence is 1. If true, the labels are
35
+ considered independent and probabilities are normalized for each candidate.
36
+ """
37
+
38
+
39
+ @dataclass
40
+ class ZeroShotClassificationInput(BaseInferenceType):
41
+ """Inputs for Zero Shot Classification inference"""
42
+
43
+ inputs: ZeroShotClassificationInputData
44
+ """The input text data, with candidate labels"""
45
+ parameters: Optional[ZeroShotClassificationParameters] = None
46
+ """Additional inference parameters"""
47
+
48
+
49
+ @dataclass
50
+ class ZeroShotClassificationOutputElement(BaseInferenceType):
51
+ """Outputs of inference for the Zero Shot Classification task"""
52
+
53
+ label: str
54
+ """The predicted class label."""
55
+ score: float
56
+ """The corresponding probability."""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class ZeroShotObjectDetectionInputData(BaseInferenceType):
14
+ """The input image data, with candidate labels"""
15
+
16
+ candidate_labels: List[str]
17
+ """The candidate labels for this image"""
18
+ image: Any
19
+ """The image data to generate bounding boxes from"""
20
+
21
+
22
+ @dataclass
23
+ class ZeroShotObjectDetectionInput(BaseInferenceType):
24
+ """Inputs for Zero Shot Object Detection inference"""
25
+
26
+ inputs: ZeroShotObjectDetectionInputData
27
+ """The input image data, with candidate labels"""
28
+ parameters: Optional[Dict[str, Any]] = None
29
+ """Additional inference parameters"""
30
+
31
+
32
+ @dataclass
33
+ class ZeroShotObjectDetectionBoundingBox(BaseInferenceType):
34
+ """The predicted bounding box. Coordinates are relative to the top left corner of the input
35
+ image.
36
+ """
37
+
38
+ xmax: int
39
+ xmin: int
40
+ ymax: int
41
+ ymin: int
42
+
43
+
44
+ @dataclass
45
+ class ZeroShotObjectDetectionOutputElement(BaseInferenceType):
46
+ """Outputs of inference for the Zero Shot Object Detection task"""
47
+
48
+ box: ZeroShotObjectDetectionBoundingBox
49
+ """The predicted bounding box. Coordinates are relative to the top left corner of the input
50
+ image.
51
+ """
52
+ label: str
53
+ """A candidate label"""
54
+ score: float
55
+ """The associated score / probability"""
evalkit_internvl/lib/python3.10/site-packages/huggingface_hub/inference_api.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ from . import constants
5
+ from .hf_api import HfApi
6
+ from .utils import build_hf_headers, get_session, is_pillow_available, logging, validate_hf_hub_args
7
+ from .utils._deprecation import _deprecate_method
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+
13
+ ALL_TASKS = [
14
+ # NLP
15
+ "text-classification",
16
+ "token-classification",
17
+ "table-question-answering",
18
+ "question-answering",
19
+ "zero-shot-classification",
20
+ "translation",
21
+ "summarization",
22
+ "conversational",
23
+ "feature-extraction",
24
+ "text-generation",
25
+ "text2text-generation",
26
+ "fill-mask",
27
+ "sentence-similarity",
28
+ # Audio
29
+ "text-to-speech",
30
+ "automatic-speech-recognition",
31
+ "audio-to-audio",
32
+ "audio-classification",
33
+ "voice-activity-detection",
34
+ # Computer vision
35
+ "image-classification",
36
+ "object-detection",
37
+ "image-segmentation",
38
+ "text-to-image",
39
+ "image-to-image",
40
+ # Others
41
+ "tabular-classification",
42
+ "tabular-regression",
43
+ ]
44
+
45
+
46
+ class InferenceApi:
47
+ """Client to configure requests and make calls to the HuggingFace Inference API.
48
+
49
+ Example:
50
+
51
+ ```python
52
+ >>> from huggingface_hub.inference_api import InferenceApi
53
+
54
+ >>> # Mask-fill example
55
+ >>> inference = InferenceApi("bert-base-uncased")
56
+ >>> inference(inputs="The goal of life is [MASK].")
57
+ [{'sequence': 'the goal of life is life.', 'score': 0.10933292657136917, 'token': 2166, 'token_str': 'life'}]
58
+
59
+ >>> # Question Answering example
60
+ >>> inference = InferenceApi("deepset/roberta-base-squad2")
61
+ >>> inputs = {
62
+ ... "question": "What's my name?",
63
+ ... "context": "My name is Clara and I live in Berkeley.",
64
+ ... }
65
+ >>> inference(inputs)
66
+ {'score': 0.9326569437980652, 'start': 11, 'end': 16, 'answer': 'Clara'}
67
+
68
+ >>> # Zero-shot example
69
+ >>> inference = InferenceApi("typeform/distilbert-base-uncased-mnli")
70
+ >>> inputs = "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!"
71
+ >>> params = {"candidate_labels": ["refund", "legal", "faq"]}
72
+ >>> inference(inputs, params)
73
+ {'sequence': 'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!', 'labels': ['refund', 'faq', 'legal'], 'scores': [0.9378499388694763, 0.04914155602455139, 0.013008488342165947]}
74
+
75
+ >>> # Overriding configured task
76
+ >>> inference = InferenceApi("bert-base-uncased", task="feature-extraction")
77
+
78
+ >>> # Text-to-image
79
+ >>> inference = InferenceApi("stabilityai/stable-diffusion-2-1")
80
+ >>> inference("cat")
81
+ <PIL.PngImagePlugin.PngImageFile image (...)>
82
+
83
+ >>> # Return as raw response to parse the output yourself
84
+ >>> inference = InferenceApi("mio/amadeus")
85
+ >>> response = inference("hello world", raw_response=True)
86
+ >>> response.headers
87
+ {"Content-Type": "audio/flac", ...}
88
+ >>> response.content # raw bytes from server
89
+ b'(...)'
90
+ ```
91
+ """
92
+
93
+ @validate_hf_hub_args
94
+ @_deprecate_method(
95
+ version="1.0",
96
+ message=(
97
+ "`InferenceApi` client is deprecated in favor of the more feature-complete `InferenceClient`. Check out"
98
+ " this guide to learn how to convert your script to use it:"
99
+ " https://huggingface.co/docs/huggingface_hub/guides/inference#legacy-inferenceapi-client."
100
+ ),
101
+ )
102
+ def __init__(
103
+ self,
104
+ repo_id: str,
105
+ task: Optional[str] = None,
106
+ token: Optional[str] = None,
107
+ gpu: bool = False,
108
+ ):
109
+ """Inits headers and API call information.
110
+
111
+ Args:
112
+ repo_id (``str``):
113
+ Id of repository (e.g. `user/bert-base-uncased`).
114
+ task (``str``, `optional`, defaults ``None``):
115
+ Whether to force a task instead of using task specified in the
116
+ repository.
117
+ token (`str`, `optional`):
118
+ The API token to use as HTTP bearer authorization. This is not
119
+ the authentication token. You can find the token in
120
+ https://huggingface.co/settings/token. Alternatively, you can
121
+ find both your organizations and personal API tokens using
122
+ `HfApi().whoami(token)`.
123
+ gpu (`bool`, `optional`, defaults `False`):
124
+ Whether to use GPU instead of CPU for inference(requires Startup
125
+ plan at least).
126
+ """
127
+ self.options = {"wait_for_model": True, "use_gpu": gpu}
128
+ self.headers = build_hf_headers(token=token)
129
+
130
+ # Configure task
131
+ model_info = HfApi(token=token).model_info(repo_id=repo_id)
132
+ if not model_info.pipeline_tag and not task:
133
+ raise ValueError(
134
+ "Task not specified in the repository. Please add it to the model card"
135
+ " using pipeline_tag"
136
+ " (https://huggingface.co/docs#how-is-a-models-type-of-inference-api-and-widget-determined)"
137
+ )
138
+
139
+ if task and task != model_info.pipeline_tag:
140
+ if task not in ALL_TASKS:
141
+ raise ValueError(f"Invalid task {task}. Make sure it's valid.")
142
+
143
+ logger.warning(
144
+ "You're using a different task than the one specified in the"
145
+ " repository. Be sure to know what you're doing :)"
146
+ )
147
+ self.task = task
148
+ else:
149
+ assert model_info.pipeline_tag is not None, "Pipeline tag cannot be None"
150
+ self.task = model_info.pipeline_tag
151
+
152
+ self.api_url = f"{constants.INFERENCE_ENDPOINT}/pipeline/{self.task}/{repo_id}"
153
+
154
+ def __repr__(self):
155
+ # Do not add headers to repr to avoid leaking token.
156
+ return f"InferenceAPI(api_url='{self.api_url}', task='{self.task}', options={self.options})"
157
+
158
+ def __call__(
159
+ self,
160
+ inputs: Optional[Union[str, Dict, List[str], List[List[str]]]] = None,
161
+ params: Optional[Dict] = None,
162
+ data: Optional[bytes] = None,
163
+ raw_response: bool = False,
164
+ ) -> Any:
165
+ """Make a call to the Inference API.
166
+
167
+ Args:
168
+ inputs (`str` or `Dict` or `List[str]` or `List[List[str]]`, *optional*):
169
+ Inputs for the prediction.
170
+ params (`Dict`, *optional*):
171
+ Additional parameters for the models. Will be sent as `parameters` in the
172
+ payload.
173
+ data (`bytes`, *optional*):
174
+ Bytes content of the request. In this case, leave `inputs` and `params` empty.
175
+ raw_response (`bool`, defaults to `False`):
176
+ If `True`, the raw `Response` object is returned. You can parse its content
177
+ as preferred. By default, the content is parsed into a more practical format
178
+ (json dictionary or PIL Image for example).
179
+ """
180
+ # Build payload
181
+ payload: Dict[str, Any] = {
182
+ "options": self.options,
183
+ }
184
+ if inputs:
185
+ payload["inputs"] = inputs
186
+ if params:
187
+ payload["parameters"] = params
188
+
189
+ # Make API call
190
+ response = get_session().post(self.api_url, headers=self.headers, json=payload, data=data)
191
+
192
+ # Let the user handle the response
193
+ if raw_response:
194
+ return response
195
+
196
+ # By default, parse the response for the user.
197
+ content_type = response.headers.get("Content-Type") or ""
198
+ if content_type.startswith("image"):
199
+ if not is_pillow_available():
200
+ raise ImportError(
201
+ f"Task '{self.task}' returned as image but Pillow is not installed."
202
+ " Please install it (`pip install Pillow`) or pass"
203
+ " `raw_response=True` to get the raw `Response` object and parse"
204
+ " the image by yourself."
205
+ )
206
+
207
+ from PIL import Image
208
+
209
+ return Image.open(io.BytesIO(response.content))
210
+ elif content_type == "application/json":
211
+ return response.json()
212
+ else:
213
+ raise NotImplementedError(
214
+ f"{content_type} output type is not implemented yet. You can pass"
215
+ " `raw_response=True` to get the raw `Response` object and parse the"
216
+ " output by yourself."
217
+ )