Amar-Aly commited on
Commit
c84cbd1
·
verified ·
1 Parent(s): b837e4d

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. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/__init__.py +13 -0
  2. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/client.py +104 -0
  3. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/sse_client.py +144 -0
  4. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/types.py +115 -0
  5. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/__init__.py +13 -0
  6. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_cli_utils.py +1102 -0
  7. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_errors.py +113 -0
  8. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_output.py +238 -0
  9. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_skills.py +419 -0
  10. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/__init__.py +0 -0
  11. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/_async_client.py +0 -0
  12. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/__init__.py +204 -0
  13. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/audio_classification.py +43 -0
  14. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/audio_to_audio.py +30 -0
  15. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/automatic_speech_recognition.py +113 -0
  16. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/base.py +167 -0
  17. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/chat_completion.py +347 -0
  18. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/depth_estimation.py +28 -0
  19. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/document_question_answering.py +80 -0
  20. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/feature_extraction.py +36 -0
  21. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/fill_mask.py +47 -0
  22. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_classification.py +43 -0
  23. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_segmentation.py +51 -0
  24. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_text_to_image.py +67 -0
  25. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_text_to_video.py +65 -0
  26. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_to_image.py +60 -0
  27. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_to_text.py +100 -0
  28. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_to_video.py +60 -0
  29. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/object_detection.py +56 -0
  30. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/question_answering.py +72 -0
  31. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/sentence_similarity.py +27 -0
  32. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/summarization.py +41 -0
  33. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/table_question_answering.py +62 -0
  34. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text2text_generation.py +42 -0
  35. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_classification.py +41 -0
  36. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_generation.py +168 -0
  37. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_audio.py +99 -0
  38. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_image.py +50 -0
  39. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_speech.py +99 -0
  40. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_video.py +46 -0
  41. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/token_classification.py +51 -0
  42. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/translation.py +49 -0
  43. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/video_classification.py +45 -0
  44. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/visual_question_answering.py +49 -0
  45. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/zero_shot_classification.py +43 -0
  46. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/zero_shot_image_classification.py +38 -0
  47. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py +50 -0
  48. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_mcp/__init__.py +0 -0
  49. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_mcp/_cli_hacks.py +88 -0
  50. .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_mcp/agent.py +100 -0
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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.
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/client.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ import json
17
+ from collections import deque
18
+ from collections.abc import Iterator
19
+ from typing import Literal, TypedDict
20
+
21
+ import httpx
22
+
23
+ from ..utils._headers import build_hf_headers
24
+ from ..utils._http import hf_raise_for_status
25
+ from .sse_client import SSEClient
26
+ from .types import ApiGetReloadEventSourceData, ApiGetReloadRequest
27
+
28
+
29
+ HOT_RELOADING_PORT = 7887
30
+
31
+
32
+ class MultiReplicaStreamEvent(TypedDict):
33
+ kind: Literal["event"]
34
+ event: ApiGetReloadEventSourceData
35
+
36
+
37
+ class MultiReplicaStreamReplicaHash(TypedDict):
38
+ kind: Literal["replicaHash"]
39
+ hash: str
40
+
41
+
42
+ class MultiReplicaStreamFullMatch(TypedDict):
43
+ kind: Literal["fullMatch"]
44
+
45
+
46
+ class ReloadClient:
47
+ def __init__(
48
+ self,
49
+ *,
50
+ host: str,
51
+ subdomain: str,
52
+ replica_hash: str,
53
+ token: str | None,
54
+ ):
55
+ base_host = host.replace(subdomain, f"{subdomain}--{HOT_RELOADING_PORT}")
56
+ self.replica_hash = replica_hash
57
+ self.client = httpx.Client(
58
+ base_url=f"{base_host}/--replicas/+{replica_hash}",
59
+ headers=build_hf_headers(token=token),
60
+ )
61
+
62
+ def get_reload(self, reload_id: str) -> Iterator[ApiGetReloadEventSourceData]:
63
+ req = ApiGetReloadRequest(reloadId=reload_id)
64
+ with self.client.stream("POST", "/get-reload", json=req) as res:
65
+ hf_raise_for_status(res)
66
+ for event in SSEClient(res.iter_bytes()).events():
67
+ if event.event == "message":
68
+ yield json.loads(event.data)
69
+
70
+
71
+ def multi_replica_reload_events(
72
+ commit_sha: str,
73
+ host: str,
74
+ subdomain: str,
75
+ replica_hashes: list[str],
76
+ token: str | None,
77
+ ) -> Iterator[MultiReplicaStreamEvent | MultiReplicaStreamReplicaHash | MultiReplicaStreamFullMatch]:
78
+ clients = [
79
+ ReloadClient(
80
+ host=host,
81
+ subdomain=subdomain,
82
+ replica_hash=hash,
83
+ token=token,
84
+ )
85
+ for hash in replica_hashes
86
+ ]
87
+
88
+ first_client_events: dict[int, ApiGetReloadEventSourceData] = {}
89
+ for client_index, client in enumerate(clients):
90
+ if len(clients) > 1:
91
+ yield {"kind": "replicaHash", "hash": client.replica_hash}
92
+ full_match = True
93
+ replay: deque[ApiGetReloadEventSourceData] = deque()
94
+ for event_index, event in enumerate(client.get_reload(commit_sha)):
95
+ if client_index == 0:
96
+ first_client_events[event_index] = event
97
+ elif full_match := full_match and first_client_events.get(event_index) == event:
98
+ replay.append(event)
99
+ continue
100
+ while replay:
101
+ yield {"kind": "event", "event": replay.popleft()}
102
+ yield {"kind": "event", "event": event}
103
+ if client_index > 0 and full_match:
104
+ yield {"kind": "fullMatch"}
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/sse_client.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vendored file: Server Side Events (SSE) client for Python.
3
+
4
+ Source:
5
+ - Author: Maxime Petazzoni <maxime.petazzoni@bulix.org>
6
+ - Repository: https://github.com/mpetazzoni/sseclient
7
+ - File: https://github.com/mpetazzoni/sseclient/blob/main/sseclient/__init__.py
8
+
9
+ License:
10
+ - Apache-2.0 (from upstream project)
11
+
12
+ Provides a generator of SSE received through an existing HTTP response.
13
+ """
14
+
15
+ import logging
16
+
17
+ __author__ = 'Maxime Petazzoni <maxime.petazzoni@bulix.org>'
18
+ __email__ = 'maxime.petazzoni@bulix.org'
19
+ __all__ = ['SSEClient']
20
+
21
+ _FIELD_SEPARATOR = ':'
22
+
23
+
24
+ class SSEClient:
25
+ """Implementation of a SSE client.
26
+
27
+ See http://www.w3.org/TR/2009/WD-eventsource-20091029/ for the
28
+ specification.
29
+ """
30
+
31
+ def __init__(self, event_source, char_enc='utf-8'):
32
+ """Initialize the SSE client over an existing, ready to consume
33
+ event source.
34
+
35
+ The event source is expected to be a binary stream and have a close()
36
+ method. That would usually be something that implements
37
+ io.BinaryIOBase, like an httplib or urllib3 HTTPResponse object.
38
+ """
39
+ self._logger = logging.getLogger(self.__class__.__module__)
40
+ self._logger.debug('Initialized SSE client from event source %s',
41
+ event_source)
42
+ self._event_source = event_source
43
+ self._char_enc = char_enc
44
+
45
+ def _read(self):
46
+ """Read the incoming event source stream and yield event chunks.
47
+
48
+ Unfortunately it is possible for some servers to decide to break an
49
+ event into multiple HTTP chunks in the response. It is thus necessary
50
+ to correctly stitch together consecutive response chunks and find the
51
+ SSE delimiter (empty new line) to yield full, correct event chunks."""
52
+ data = b''
53
+ for chunk in self._event_source:
54
+ for line in chunk.splitlines(True):
55
+ data += line
56
+ if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')):
57
+ yield data
58
+ data = b''
59
+ if data:
60
+ yield data
61
+
62
+ def events(self):
63
+ for chunk in self._read():
64
+ event = Event()
65
+ # Split before decoding so splitlines() only uses \r and \n
66
+ for line in chunk.splitlines():
67
+ # Decode the line.
68
+ line = line.decode(self._char_enc)
69
+
70
+ # Lines starting with a separator are comments and are to be
71
+ # ignored.
72
+ if not line.strip() or line.startswith(_FIELD_SEPARATOR):
73
+ continue
74
+
75
+ data = line.split(_FIELD_SEPARATOR, 1)
76
+ field = data[0]
77
+
78
+ # Ignore unknown fields.
79
+ if field not in event.__dict__:
80
+ self._logger.debug('Saw invalid field %s while parsing '
81
+ 'Server Side Event', field)
82
+ continue
83
+
84
+ if len(data) > 1:
85
+ # From the spec:
86
+ # "If value starts with a single U+0020 SPACE character,
87
+ # remove it from value."
88
+ if data[1].startswith(' '):
89
+ value = data[1][1:]
90
+ else:
91
+ value = data[1]
92
+ else:
93
+ # If no value is present after the separator,
94
+ # assume an empty value.
95
+ value = ''
96
+
97
+ # The data field may come over multiple lines and their values
98
+ # are concatenated with each other.
99
+ if field == 'data':
100
+ event.__dict__[field] += value + '\n'
101
+ else:
102
+ event.__dict__[field] = value
103
+
104
+ # Events with no data are not dispatched.
105
+ if not event.data:
106
+ continue
107
+
108
+ # If the data field ends with a newline, remove it.
109
+ if event.data.endswith('\n'):
110
+ event.data = event.data[0:-1]
111
+
112
+ # Empty event names default to 'message'
113
+ event.event = event.event or 'message'
114
+
115
+ # Dispatch the event
116
+ self._logger.debug('Dispatching %s...', event)
117
+ yield event
118
+
119
+ def close(self):
120
+ """Manually close the event source stream."""
121
+ self._event_source.close()
122
+
123
+
124
+ class Event:
125
+ """Representation of an event from the event stream."""
126
+
127
+ def __init__(self, id=None, event='message', data='', retry=None):
128
+ self.id = id
129
+ self.event = event
130
+ self.data = data
131
+ self.retry = retry
132
+
133
+ def __str__(self):
134
+ s = f'{self.event} event'
135
+ if self.id:
136
+ s += f' #{self.id}'
137
+ if self.data:
138
+ s += ', {} byte{}'.format(len(self.data),
139
+ 's' if len(self.data) else '')
140
+ else:
141
+ s += ', no data'
142
+ if self.retry:
143
+ s += f', retry in {self.retry}ms'
144
+ return s
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_hot_reload/types.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ from typing import Literal, TypedDict
17
+
18
+ from typing_extensions import NotRequired
19
+
20
+
21
+ class ReloadRegion(TypedDict):
22
+ startLine: int
23
+ startCol: int
24
+ endLine: int
25
+ endCol: int
26
+
27
+
28
+ class ReloadOperationObject(TypedDict):
29
+ kind: Literal["add", "update", "delete"]
30
+ region: ReloadRegion
31
+ objectType: str
32
+ objectName: str
33
+
34
+
35
+ class ReloadOperationRun(TypedDict):
36
+ kind: Literal["run"]
37
+ region: ReloadRegion
38
+ codeLines: str
39
+ stdout: NotRequired[str]
40
+ stderr: NotRequired[str]
41
+
42
+
43
+ class ReloadOperationException(TypedDict):
44
+ kind: Literal["exception"]
45
+ region: ReloadRegion
46
+ traceback: str
47
+
48
+
49
+ class ReloadOperationError(TypedDict):
50
+ kind: Literal["error"]
51
+ traceback: str
52
+
53
+
54
+ class ReloadOperationUI(TypedDict):
55
+ kind: Literal["ui"]
56
+ updated: bool
57
+
58
+
59
+ class ApiCreateReloadRequest(TypedDict):
60
+ filepath: str
61
+ contents: str
62
+ reloadId: NotRequired[str]
63
+
64
+
65
+ class ApiCreateReloadResponseSuccess(TypedDict):
66
+ status: Literal["created"]
67
+ reloadId: str
68
+
69
+
70
+ class ApiCreateReloadResponseError(TypedDict):
71
+ status: Literal["alreadyReloading", "fileNotFound"]
72
+
73
+
74
+ class ApiCreateReloadResponse(TypedDict):
75
+ res: ApiCreateReloadResponseError | ApiCreateReloadResponseSuccess
76
+
77
+
78
+ class ApiGetReloadRequest(TypedDict):
79
+ reloadId: str
80
+
81
+
82
+ class ApiGetReloadEventSourceData(TypedDict):
83
+ data: (
84
+ ReloadOperationError
85
+ | ReloadOperationException
86
+ | ReloadOperationObject
87
+ | ReloadOperationRun
88
+ | ReloadOperationUI
89
+ )
90
+
91
+
92
+ class ApiGetStatusRequest(TypedDict):
93
+ revision: str
94
+
95
+
96
+ class ApiGetStatusResponse(TypedDict):
97
+ reloading: bool
98
+ uncommited: list[str]
99
+
100
+
101
+ class ApiFetchContentsRequest(TypedDict):
102
+ filepath: str
103
+
104
+
105
+ class ApiFetchContentsResponseError(TypedDict):
106
+ status: Literal["fileNotFound"]
107
+
108
+
109
+ class ApiFetchContentsResponseSuccess(TypedDict):
110
+ status: Literal["ok"]
111
+ contents: str
112
+
113
+
114
+ class ApiFetchContentsResponse(TypedDict):
115
+ res: ApiFetchContentsResponseError | ApiFetchContentsResponseSuccess
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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.
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_cli_utils.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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 CLI utilities (styling, helpers)."""
15
+
16
+ import dataclasses
17
+ import datetime
18
+ import difflib
19
+ import importlib.metadata
20
+ import json
21
+ import os
22
+ import re
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ from collections.abc import Callable, Sequence
27
+ from enum import Enum
28
+ from pathlib import Path
29
+ from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar, Union, cast
30
+
31
+ import click
32
+ import typer
33
+ from typer.core import TyperCommand, TyperGroup
34
+
35
+ from huggingface_hub import Volume, __version__, constants
36
+ from huggingface_hub.errors import CLIError
37
+ from huggingface_hub.utils import ANSI, get_session, hf_raise_for_status, installation_method, logging, tabulate
38
+ from huggingface_hub.utils._dotenv import load_dotenv
39
+
40
+ from ._output import OutputFormatWithAuto, out
41
+
42
+
43
+ logger = logging.get_logger()
44
+
45
+ # Arbitrary maximum length of a cell in a table output
46
+ _MAX_CELL_LENGTH = 35
47
+
48
+ if TYPE_CHECKING:
49
+ from huggingface_hub.hf_api import HfApi
50
+
51
+
52
+ def get_hf_api(token: str | None = None) -> "HfApi":
53
+ # Import here to avoid circular import
54
+ from huggingface_hub.hf_api import HfApi
55
+
56
+ return HfApi(token=token, library_name="huggingface-cli", library_version=__version__)
57
+
58
+
59
+ #### TYPER UTILS
60
+
61
+ CLI_REFERENCE_URL = "https://huggingface.co/docs/huggingface_hub/en/guides/cli"
62
+
63
+
64
+ def generate_epilog(examples: list[str], docs_anchor: str | None = None) -> str:
65
+ """Generate an epilog with examples and a Learn More section.
66
+
67
+ Args:
68
+ examples: List of example commands (without the `$ ` prefix).
69
+ docs_anchor: Optional anchor for the docs URL (e.g., "#hf-download").
70
+
71
+ Returns:
72
+ Formatted epilog string.
73
+ """
74
+ docs_url = f"{CLI_REFERENCE_URL}{docs_anchor}" if docs_anchor else CLI_REFERENCE_URL
75
+ examples_str = "\n".join(f" $ {ex}" for ex in examples)
76
+ return f"""\
77
+ Examples
78
+ {examples_str}
79
+
80
+ Learn more
81
+ Use `hf <command> --help` for more information about a command.
82
+ Read the documentation at {docs_url}
83
+ """
84
+
85
+
86
+ TOPIC_T = Literal["main", "help"] | str
87
+ FallbackHandlerT = Callable[[list[str], set[str]], int | None]
88
+ ExpandPropertyT = TypeVar("ExpandPropertyT", bound=str)
89
+
90
+
91
+ def _format_epilog_no_indent(epilog: str | None, ctx: click.Context, formatter: click.HelpFormatter) -> None:
92
+ """Write the epilog without indentation."""
93
+ if epilog:
94
+ formatter.write_paragraph()
95
+ for line in epilog.split("\n"):
96
+ formatter.write_text(line)
97
+
98
+
99
+ _ALIAS_SPLIT = re.compile(r"\s*\|\s*")
100
+
101
+
102
+ class HFCliTyperGroup(TyperGroup):
103
+ """
104
+ Typer Group that:
105
+ - lists commands alphabetically within sections.
106
+ - separates commands by topic (main, help, etc.).
107
+ - formats epilog without extra indentation.
108
+ - supports aliases via pipe-separated names (e.g. ``name="list | ls"``).
109
+ - rewrites ``--json`` to ``--format json`` for commands that accept ``--format``.
110
+ - rewrites ``spaces/user/repo`` to ``user/repo --type space`` for commands that accept ``--type``.
111
+ - enriches "No such option" / "No such command" errors with available options or commands.
112
+ """
113
+
114
+ def invoke(self, ctx: click.Context) -> None:
115
+ """Enrich unknown-option errors with available options or subcommands.
116
+
117
+ Catches `NoSuchOption` raised during subcommand `make_context()`
118
+ (option parsing). For leaf commands (e.g. `hf repos create --test`)
119
+ we list the command's options; for groups (e.g. `hf cache --test`)
120
+ we list subcommands since groups have no user-facing options.
121
+ """
122
+ try:
123
+ return super().invoke(ctx)
124
+ except click.NoSuchOption as e:
125
+ if e.ctx is not None and e.ctx.command is not None:
126
+ cmd = e.ctx.command
127
+ if isinstance(cmd, click.Group):
128
+ # Group has no user-facing options -> show subcommands instead
129
+ items = [
130
+ (name, sub.get_short_help_str(limit=80))
131
+ for name in cmd.list_commands(e.ctx)
132
+ if (sub := cmd.get_command(e.ctx, name)) is not None and not sub.hidden
133
+ ]
134
+ _enrich_usage_error(e, "commands", items)
135
+ else:
136
+ # Leaf command -> show its options using Click's rich formatting
137
+ items = [
138
+ record
139
+ for p in cmd.get_params(e.ctx)
140
+ if isinstance(p, click.Option) and not p.hidden and (record := p.get_help_record(e.ctx))
141
+ ]
142
+ _enrich_usage_error(e, "options", items)
143
+ raise
144
+
145
+ def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
146
+ cmd_name = args[0] if args and not args[0].startswith("-") else None
147
+ cmd = self.get_command(ctx, cmd_name) if cmd_name else None
148
+
149
+ if cmd is not None:
150
+ self._rewrite_json_shorthand(cmd, args)
151
+ self._rewrite_quiet_shorthand(cmd, args)
152
+ self._rewrite_repo_type_prefix(cmd, args)
153
+
154
+ try:
155
+ return super().resolve_command(ctx, args)
156
+ except click.UsageError as e:
157
+ # Unknown subcommand -> add fuzzy suggestions and list available commands.
158
+ if cmd is None and cmd_name is not None:
159
+ # Expand aliases ("list | ls" → ["list", "ls"]) for accurate fuzzy matching.
160
+ visible_names = [
161
+ alias
162
+ for key, registered in self.commands.items()
163
+ if not registered.hidden
164
+ for alias in _ALIAS_SPLIT.split(key)
165
+ ]
166
+ matches = difflib.get_close_matches(cmd_name, visible_names)
167
+ if matches:
168
+ suggestions = ", ".join(f"'{m}'" for m in matches)
169
+ e.message = f"{e.message.rstrip('.')}. Did you mean {suggestions}?"
170
+ items = [
171
+ (name, sub.get_short_help_str(limit=80))
172
+ for name in self.list_commands(ctx)
173
+ if (sub := self.get_command(ctx, name)) is not None and not sub.hidden
174
+ ]
175
+ _enrich_usage_error(e, "commands", items)
176
+ raise
177
+
178
+ @staticmethod
179
+ def _rewrite_json_shorthand(cmd: click.Command, args: list[str]) -> None:
180
+ """Rewrite hidden ``--json`` shorthand to ``--format json``.
181
+
182
+ Only applies to commands that accept ``--format``. This avoids rewriting
183
+ ``--json`` for commands that pass args through to external binaries
184
+ (e.g. ``hf extensions exec``) or that simply don't support ``--format``.
185
+ """
186
+ if "--json" not in args:
187
+ return
188
+ has_format_option = any(isinstance(param, click.Option) and "--format" in param.opts for param in cmd.params)
189
+ if has_format_option:
190
+ if any(arg == "--format" or arg.startswith("--format=") for arg in args):
191
+ raise click.UsageError("'--json' and '--format' are mutually exclusive.")
192
+ idx = args.index("--json")
193
+ args[idx : idx + 1] = ["--format", "json"]
194
+
195
+ @staticmethod
196
+ def _rewrite_quiet_shorthand(cmd: click.Command, args: list[str]) -> None:
197
+ """Rewrite ``-q`` / ``--quiet`` shorthand to ``--format quiet``.
198
+
199
+ Only applies to commands that accept ``--format`` but do NOT already
200
+ have their own ``--quiet`` / ``-q`` option.
201
+ """
202
+ has_quiet = "-q" in args or "--quiet" in args
203
+ if not has_quiet:
204
+ return
205
+ has_format_option = any(isinstance(param, click.Option) and "--format" in param.opts for param in cmd.params)
206
+ has_quiet_option = any(
207
+ isinstance(param, click.Option) and ("--quiet" in param.opts or "-q" in param.opts) for param in cmd.params
208
+ )
209
+ if has_format_option and not has_quiet_option:
210
+ if any(arg == "--format" or arg.startswith("--format=") for arg in args):
211
+ raise click.UsageError("'--quiet' and '--format' are mutually exclusive.")
212
+ flag = "-q" if "-q" in args else "--quiet"
213
+ idx = args.index(flag)
214
+ args[idx : idx + 1] = ["--format", "quiet"]
215
+
216
+ @staticmethod
217
+ def _rewrite_repo_type_prefix(cmd: click.Command, args: list[str]) -> None:
218
+ """Rewrite prefixed repo IDs (e.g. ``spaces/user/repo``) to ``user/repo --type space``.
219
+
220
+ Only applies to commands that have a ``--type`` / ``--repo-type`` option and
221
+ at least one repo-ID positional argument (any ``click.Argument`` whose name
222
+ ends with ``_id``, e.g. ``repo_id``, ``from_id``, ``to_id``). When the
223
+ token that maps to such an argument matches ``{prefix}/org/repo`` (where
224
+ *prefix* is one of ``spaces``, ``datasets``, or ``models``), the prefix is
225
+ stripped and an implicit ``--type {type}`` is appended. An error is raised
226
+ if ``--type`` is also provided explicitly or if multiple prefixed arguments
227
+ disagree on the repo type.
228
+
229
+ Only repo-ID positional slots are inspected so that other positional
230
+ arguments (filenames, local paths, patterns …) are never misinterpreted as
231
+ prefixed repo IDs.
232
+ """
233
+ has_type_option = any(isinstance(param, click.Option) and "--type" in param.opts for param in cmd.params)
234
+ if not has_type_option:
235
+ return
236
+
237
+ # Locate all repo-ID positional arguments and their indices among Arguments.
238
+ repo_id_positions: set[int] = set()
239
+ arg_idx = 0
240
+ for param in cmd.params:
241
+ if isinstance(param, click.Argument):
242
+ if param.name in ("repo_id", "from_id", "to_id"):
243
+ repo_id_positions.add(arg_idx)
244
+ arg_idx += 1
245
+
246
+ if not repo_id_positions:
247
+ return
248
+
249
+ # Build a set of option names that consume a following value token.
250
+ value_options: set[str] = set()
251
+ for param in cmd.params:
252
+ if isinstance(param, click.Option) and not param.is_flag:
253
+ for opt in (*param.opts, *param.secondary_opts):
254
+ value_options.add(opt)
255
+
256
+ # Walk through args (skipping args[0] = command name) to map positional
257
+ # slots to their indices in `args`.
258
+ positional_count = 0
259
+ repo_id_arg_indices: list[int] = []
260
+ i = 1
261
+ while i < len(args):
262
+ arg = args[i]
263
+ if arg == "--":
264
+ break # everything after -- is positional literal; stop rewriting
265
+ if arg.startswith("-"):
266
+ if "=" in arg or arg not in value_options:
267
+ i += 1 # flag or --opt=val — single token
268
+ else:
269
+ i += 2 # value-taking option — skip the value too
270
+ else:
271
+ if positional_count in repo_id_positions:
272
+ repo_id_arg_indices.append(i)
273
+ positional_count += 1
274
+ i += 1
275
+
276
+ if not repo_id_arg_indices:
277
+ return
278
+
279
+ # Check each repo-ID arg for a type prefix and collect rewrites.
280
+ inferred_type: str | None = None
281
+ first_prefix: str | None = None
282
+ rewrites: list[tuple[int, str]] = [] # (args index, new value without prefix)
283
+
284
+ for arg_index in repo_id_arg_indices:
285
+ parts = args[arg_index].split("/", 2)
286
+ if len(parts) != 3 or parts[0] not in constants.REPO_TYPES_MAPPING:
287
+ continue
288
+ prefix = parts[0]
289
+ mapped_type = constants.REPO_TYPES_MAPPING[prefix]
290
+ if inferred_type is not None and mapped_type != inferred_type:
291
+ raise click.UsageError(f"Conflicting repo type prefixes: '{first_prefix}/' and '{prefix}/'.")
292
+ inferred_type = mapped_type
293
+ first_prefix = prefix
294
+ rewrites.append((arg_index, f"{parts[1]}/{parts[2]}"))
295
+
296
+ if not rewrites:
297
+ return
298
+
299
+ # Error if --type / --repo-type was also provided explicitly.
300
+ if any(
301
+ arg == "--type" or arg.startswith("--type=") or arg == "--repo-type" or arg.startswith("--repo-type=")
302
+ for arg in args
303
+ ):
304
+ raise click.UsageError(
305
+ f"Ambiguous repo type: got prefix '{first_prefix}/' in repo ID and explicit --type. Use one or the other."
306
+ )
307
+
308
+ # Apply all rewrites and append --type once.
309
+ for arg_index, new_value in rewrites:
310
+ args[arg_index] = new_value
311
+ args.extend(["--type", inferred_type]) # type: ignore
312
+
313
+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
314
+ # Try exact match first
315
+ cmd = super().get_command(ctx, cmd_name)
316
+ if cmd is not None:
317
+ return cmd
318
+ # Fall back to alias lookup: check if cmd_name matches any alias
319
+ # taken from https://github.com/fastapi/typer/issues/132#issuecomment-2417492805
320
+ for registered_name, registered_cmd in self.commands.items():
321
+ aliases = _ALIAS_SPLIT.split(registered_name)
322
+ if cmd_name in aliases:
323
+ return registered_cmd
324
+ return None
325
+
326
+ def _alias_map(self) -> dict[str, list[str]]:
327
+ """Build a mapping from primary command name to its aliases (if any)."""
328
+ result: dict[str, list[str]] = {}
329
+ for registered_name in self.commands:
330
+ parts = _ALIAS_SPLIT.split(registered_name)
331
+ primary = parts[0]
332
+ result[primary] = parts[1:]
333
+ return result
334
+
335
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
336
+ topics: dict[str, list] = {}
337
+ alias_map = self._alias_map()
338
+
339
+ for name in self.list_commands(ctx):
340
+ cmd = self.get_command(ctx, name)
341
+ if cmd is None or cmd.hidden:
342
+ continue
343
+ help_text = cmd.get_short_help_str(limit=formatter.width)
344
+ aliases = alias_map.get(name, [])
345
+ if aliases:
346
+ help_text = f"{help_text} [alias: {', '.join(aliases)}]"
347
+ topic = getattr(cmd, "topic", "main")
348
+ topics.setdefault(topic, []).append((name, help_text))
349
+
350
+ with formatter.section("Main commands"):
351
+ formatter.write_dl(topics["main"])
352
+ for topic in sorted(topics.keys()):
353
+ if topic == "main":
354
+ continue
355
+ with formatter.section(f"{topic.capitalize()} commands"):
356
+ formatter.write_dl(topics[topic])
357
+
358
+ def format_epilog(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
359
+ # Collect only the first example from each command (to keep group help concise)
360
+ # Full examples are shown in individual subcommand help (e.g. `hf buckets sync --help`)
361
+ all_examples: list[str] = []
362
+ for name in self.list_commands(ctx):
363
+ cmd = self.get_command(ctx, name)
364
+ if cmd is None or cmd.hidden:
365
+ continue
366
+ cmd_examples = getattr(cmd, "examples", [])
367
+ if cmd_examples:
368
+ all_examples.append(cmd_examples[0])
369
+
370
+ if all_examples:
371
+ epilog = generate_epilog(all_examples)
372
+ _format_epilog_no_indent(epilog, ctx, formatter)
373
+ elif self.epilog:
374
+ _format_epilog_no_indent(self.epilog, ctx, formatter)
375
+
376
+ def list_commands(self, ctx: click.Context) -> list[str]: # type: ignore[name-defined]
377
+ # For aliased commands ("list | ls"), use the primary name (first entry).
378
+ primary_names: list[str] = []
379
+ for name in self.commands:
380
+ primary = _ALIAS_SPLIT.split(name)[0]
381
+ primary_names.append(primary)
382
+ return sorted(primary_names)
383
+
384
+
385
+ def _enrich_usage_error(error: click.UsageError, label: str, items: list[tuple[str, str]]) -> None:
386
+ """Append a list of available options or commands to a usage error message."""
387
+ if not items or error.ctx is None or f"Available {label} for" in error.message:
388
+ return
389
+ cmd_path = error.ctx.command_path
390
+ lines = [f"\n\nAvailable {label} for '{cmd_path}':"]
391
+ for name, help_text in items:
392
+ lines.append(f" {name:30s} {help_text}")
393
+ lines.append(f"\nRun '{cmd_path} --help' for full details.")
394
+ if isinstance(error, click.NoSuchOption) and error.possibilities:
395
+ lines.append(f"\nDid you mean: {', '.join(sorted(error.possibilities))}?")
396
+ error.possibilities = []
397
+ error.message += "\n".join(lines)
398
+
399
+
400
+ def fallback_typer_group_factory(
401
+ fallback_handler: FallbackHandlerT,
402
+ extra_commands_provider: Callable[[], list[tuple[str, str]]] | None = None,
403
+ ) -> type[HFCliTyperGroup]:
404
+ """Return a Typer group class that runs a fallback handler before command resolution."""
405
+
406
+ class FallbackTyperGroup(HFCliTyperGroup):
407
+ def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
408
+ fallback_exit_code = fallback_handler(args, set(self.commands.keys()))
409
+ if fallback_exit_code is not None:
410
+ raise SystemExit(fallback_exit_code)
411
+ return super().resolve_command(ctx, args)
412
+
413
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
414
+ super().format_commands(ctx, formatter)
415
+ if extra_commands_provider is not None:
416
+ entries = extra_commands_provider()
417
+ if entries:
418
+ with formatter.section("Extension commands"):
419
+ formatter.write_dl(entries)
420
+
421
+ return FallbackTyperGroup
422
+
423
+
424
+ def HFCliCommand(topic: TOPIC_T, examples: list[str] | None = None) -> type[TyperCommand]:
425
+ def format_epilog(self: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
426
+ _format_epilog_no_indent(self.epilog, ctx, formatter)
427
+
428
+ return type(
429
+ f"TyperCommand{topic.capitalize()}",
430
+ (TyperCommand,),
431
+ {"topic": topic, "examples": examples or [], "format_epilog": format_epilog},
432
+ )
433
+
434
+
435
+ class HFCliApp(typer.Typer):
436
+ """Custom Typer app for Hugging Face CLI."""
437
+
438
+ def command( # type: ignore
439
+ self,
440
+ name: str | None = None,
441
+ *,
442
+ topic: TOPIC_T = "main",
443
+ examples: list[str] | None = None,
444
+ context_settings: dict[str, Any] | None = None,
445
+ help: str | None = None,
446
+ epilog: str | None = None,
447
+ short_help: str | None = None,
448
+ options_metavar: str = "[OPTIONS]",
449
+ add_help_option: bool = True,
450
+ no_args_is_help: bool = False,
451
+ hidden: bool = False,
452
+ deprecated: bool = False,
453
+ rich_help_panel: str | None = None,
454
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
455
+ # Generate epilog from examples if not explicitly provided
456
+ if epilog is None and examples:
457
+ epilog = generate_epilog(examples)
458
+
459
+ def _inner(func: Callable[..., Any]) -> Callable[..., Any]:
460
+ return super(HFCliApp, self).command(
461
+ name,
462
+ cls=HFCliCommand(topic, examples),
463
+ context_settings=context_settings,
464
+ help=help,
465
+ epilog=epilog,
466
+ short_help=short_help,
467
+ options_metavar=options_metavar,
468
+ add_help_option=add_help_option,
469
+ no_args_is_help=no_args_is_help,
470
+ hidden=hidden,
471
+ deprecated=deprecated,
472
+ rich_help_panel=rich_help_panel,
473
+ )(func)
474
+
475
+ return _inner
476
+
477
+
478
+ def typer_factory(help: str, epilog: str | None = None, cls: type[TyperGroup] | None = None) -> "HFCliApp":
479
+ """Create a Typer app with consistent settings.
480
+
481
+ Args:
482
+ help: Help text for the app.
483
+ epilog: Optional epilog text (use `generate_epilog` to create one).
484
+ cls: Optional Click group class to use (defaults to `HFCliTyperGroup`).
485
+
486
+ Returns:
487
+ A configured Typer app.
488
+ """
489
+ if cls is None:
490
+ cls = HFCliTyperGroup
491
+ return HFCliApp(
492
+ help=help,
493
+ epilog=epilog,
494
+ add_completion=True,
495
+ no_args_is_help=True,
496
+ cls=cls,
497
+ # Disable rich completely for consistent experience
498
+ rich_markup_mode=None,
499
+ rich_help_panel=None,
500
+ pretty_exceptions_enable=False,
501
+ # Disable TyperGroup's suggest_commands, it matches against raw aliased
502
+ # keys ("list | ls") leaking pipe syntax into user-facing messages.
503
+ # HFCliTyperGroup.resolve_command() handles suggestions with expanded names.
504
+ suggest_commands=False,
505
+ # Increase max content width for better readability
506
+ context_settings={
507
+ "max_content_width": 120,
508
+ "help_option_names": ["-h", "--help"],
509
+ },
510
+ )
511
+
512
+
513
+ class RepoType(str, Enum):
514
+ model = "model"
515
+ dataset = "dataset"
516
+ space = "space"
517
+
518
+
519
+ RepoIdArg = Annotated[
520
+ str,
521
+ typer.Argument(
522
+ help="The ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).",
523
+ ),
524
+ ]
525
+
526
+
527
+ RepoTypeOpt = Annotated[
528
+ RepoType,
529
+ typer.Option(
530
+ "--type",
531
+ "--repo-type",
532
+ help="The type of repository (model, dataset, or space).",
533
+ ),
534
+ ]
535
+
536
+ TokenOpt = Annotated[
537
+ str | None,
538
+ typer.Option(
539
+ help="A User Access Token generated from https://huggingface.co/settings/tokens.",
540
+ ),
541
+ ]
542
+
543
+ PrivateOpt = Annotated[
544
+ bool | None,
545
+ typer.Option(
546
+ help="Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already exists.",
547
+ ),
548
+ ]
549
+
550
+ RevisionOpt = Annotated[
551
+ str | None,
552
+ typer.Option(
553
+ help="Git revision id which can be a branch name, a tag, or a commit hash.",
554
+ ),
555
+ ]
556
+
557
+
558
+ LimitOpt = Annotated[
559
+ int,
560
+ typer.Option(help="Limit the number of results."),
561
+ ]
562
+
563
+ AuthorOpt = Annotated[
564
+ str | None,
565
+ typer.Option(help="Filter by author or organization."),
566
+ ]
567
+
568
+ FilterOpt = Annotated[
569
+ list[str] | None,
570
+ typer.Option(help="Filter by tags (e.g. 'text-classification'). Can be used multiple times."),
571
+ ]
572
+
573
+ SearchOpt = Annotated[
574
+ str | None,
575
+ typer.Option(help="Search query."),
576
+ ]
577
+
578
+
579
+ # --- Env / Secrets shared options and parsing helpers (used by jobs, repos, etc.) ---
580
+
581
+ EnvOpt = Annotated[
582
+ list[str] | None,
583
+ typer.Option(
584
+ "-e",
585
+ "--env",
586
+ help="Set environment variables. E.g. --env ENV=value",
587
+ ),
588
+ ]
589
+
590
+ SecretsOpt = Annotated[
591
+ list[str] | None,
592
+ typer.Option(
593
+ "-s",
594
+ "--secrets",
595
+ help=(
596
+ "Set secret environment variables. E.g. --secrets SECRET=value"
597
+ " or `--secrets HF_TOKEN` to pass your Hugging Face token."
598
+ ),
599
+ ),
600
+ ]
601
+
602
+ EnvFileOpt = Annotated[
603
+ str | None,
604
+ typer.Option(
605
+ "--env-file",
606
+ help="Read in a file of environment variables.",
607
+ ),
608
+ ]
609
+
610
+ SecretsFileOpt = Annotated[
611
+ str | None,
612
+ typer.Option(
613
+ help="Read in a file of secret environment variables.",
614
+ ),
615
+ ]
616
+
617
+
618
+ def _get_extended_environ() -> dict[str, str]:
619
+ """Return a copy of ``os.environ`` with the user's HF token injected (if available)."""
620
+ from huggingface_hub import get_token
621
+
622
+ extended_environ = os.environ.copy()
623
+ if (token := get_token()) is not None:
624
+ extended_environ["HF_TOKEN"] = token
625
+ return extended_environ
626
+
627
+
628
+ def parse_env_map(
629
+ env: list[str] | None = None,
630
+ env_file: str | None = None,
631
+ ) -> dict[str, str | None]:
632
+ """Parse ``-e``/``--env``/``-s``/``--secrets`` and ``--env-file``/``--secrets-file`` CLI args into a dict.
633
+
634
+ Uses an extended environment that includes the user's HF token so that
635
+ bare ``--secrets HF_TOKEN`` resolves correctly.
636
+ """
637
+ extended_environ = _get_extended_environ()
638
+ env_map: dict[str, str | None] = {}
639
+ if env_file:
640
+ env_map.update(load_dotenv(Path(env_file).read_text(), environ=extended_environ))
641
+ for env_value in env or []:
642
+ env_map.update(load_dotenv(env_value, environ=extended_environ))
643
+ return env_map
644
+
645
+
646
+ def env_map_to_key_value_list(env_map: dict[str, str | None]) -> list[dict[str, str]] | None:
647
+ """Convert an env/secrets dict to the ``[{"key": ..., "value": ...}]`` format used by the Hub API."""
648
+ if not env_map:
649
+ return None
650
+ return [{"key": k, "value": v or ""} for k, v in env_map.items()]
651
+
652
+
653
+ VolumesOpt = Annotated[
654
+ list[str] | None,
655
+ typer.Option(
656
+ "-v",
657
+ "--volume",
658
+ help="Mount a volume. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. "
659
+ "TYPE is one of: models, datasets, spaces, buckets. "
660
+ "TYPE defaults to models if omitted. "
661
+ "models, datasets and spaces are always mounted read-only. buckets are read+write by default."
662
+ "E.g. -v hf://gpt2:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro",
663
+ ),
664
+ ]
665
+
666
+ _HF_PREFIX = "hf://"
667
+ _HF_VOLUME_TYPES = {
668
+ "models": constants.REPO_TYPE_MODEL,
669
+ "datasets": constants.REPO_TYPE_DATASET,
670
+ "spaces": constants.REPO_TYPE_SPACE,
671
+ "buckets": "bucket",
672
+ }
673
+
674
+
675
+ def parse_volumes(volumes: list[str] | None) -> "list[Volume] | None":
676
+ """Parse volume specs from CLI arguments.
677
+
678
+ Format: hf://[TYPE/]SOURCE[/PATH]:/MOUNT_PATH[:ro|:rw]
679
+ Where TYPE is one of: models, datasets, spaces, buckets (defaults to models if omitted).
680
+ SOURCE is the repo/bucket identifier (e.g. 'username/my-model').
681
+ PATH is an optional subfolder inside the repo/bucket.
682
+ MOUNT_PATH starts with '/'.
683
+ Optional ':ro' or ':rw' suffix for read-only or read-write.
684
+
685
+ Examples:
686
+ hf://gpt2:/data (model, implicit type)
687
+ hf://my-org/my-model:/data (model, implicit type)
688
+ hf://models/my-org/my-model:/data (model, explicit type)
689
+ hf://datasets/my-org/my-dataset:/data:ro
690
+ hf://buckets/my-org/my-bucket:/mnt
691
+ hf://spaces/my-org/my-space:/app
692
+ hf://datasets/org/ds/train:/data (with path inside repo)
693
+ hf://buckets/org/b/sub/dir:/mnt (with path inside bucket)
694
+ """
695
+
696
+ if not volumes:
697
+ return None
698
+
699
+ result: list[Volume] = []
700
+ for raw_spec in volumes:
701
+ # Strip :ro/:rw suffix
702
+ spec = raw_spec
703
+ read_only = None
704
+ if spec.endswith(":ro"):
705
+ read_only = True
706
+ spec = spec[:-3]
707
+ elif spec.endswith(":rw"):
708
+ read_only = False
709
+ spec = spec[:-3]
710
+
711
+ # Validate hf:// prefix
712
+ if not spec.startswith(_HF_PREFIX):
713
+ raise CLIError(
714
+ f"Invalid volume format: '{raw_spec}'. Source must start with 'hf://'. "
715
+ f"Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://gpt2:/data"
716
+ )
717
+ spec = spec[len(_HF_PREFIX) :]
718
+
719
+ # Find the mount path: look for :/ pattern
720
+ colon_slash_idx = spec.find(":/")
721
+ if colon_slash_idx == -1:
722
+ raise CLIError(
723
+ f"Invalid volume format: '{raw_spec}'. Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://gpt2:/data"
724
+ )
725
+ source_part = spec[:colon_slash_idx]
726
+ mount_path = spec[colon_slash_idx + 1 :]
727
+
728
+ # Parse type from source_part (first segment before /)
729
+ # Then split remaining into source (namespace/name or name) and optional path.
730
+ slash_idx = source_part.find("/")
731
+ if slash_idx == -1:
732
+ # No slash: bare source like "gpt2" -> model type
733
+ vol_type_str = constants.REPO_TYPE_MODEL
734
+ source = source_part
735
+ path = None
736
+ else:
737
+ first_segment = source_part[:slash_idx]
738
+ if first_segment in _HF_VOLUME_TYPES:
739
+ vol_type_str = _HF_VOLUME_TYPES[first_segment]
740
+ remaining = source_part[slash_idx + 1 :]
741
+ else:
742
+ # First segment isn't a known type -> model type
743
+ vol_type_str = constants.REPO_TYPE_MODEL
744
+ remaining = source_part
745
+
746
+ # Split remaining into source (namespace/name) and optional path.
747
+ # Repo/bucket IDs are "namespace/name" (2 segments) or "name" (1 segment).
748
+ # Any extra segments are the path inside the repo/bucket.
749
+ parts = remaining.split("/", 2)
750
+ if len(parts) >= 3:
751
+ source = parts[0] + "/" + parts[1]
752
+ path = parts[2]
753
+ else:
754
+ source = remaining
755
+ path = None
756
+
757
+ result.append(
758
+ Volume(
759
+ type=vol_type_str,
760
+ source=source,
761
+ mount_path=mount_path,
762
+ read_only=read_only,
763
+ path=path,
764
+ )
765
+ )
766
+ return result
767
+
768
+
769
+ class OutputFormat(str, Enum):
770
+ """Output format for CLI list commands."""
771
+
772
+ table = "table"
773
+ json = "json"
774
+
775
+
776
+ FormatOpt = Annotated[
777
+ OutputFormat,
778
+ typer.Option(
779
+ help="Output format (table or json).",
780
+ ),
781
+ ]
782
+
783
+
784
+ def _set_output_mode(value: OutputFormatWithAuto) -> OutputFormatWithAuto:
785
+ out.set_mode(value)
786
+ return value
787
+
788
+
789
+ FormatWithAutoOpt = Annotated[
790
+ OutputFormatWithAuto,
791
+ typer.Option(
792
+ help="Output format.",
793
+ callback=_set_output_mode,
794
+ ),
795
+ ]
796
+
797
+ QuietOpt = Annotated[
798
+ bool,
799
+ typer.Option(
800
+ "-q",
801
+ "--quiet",
802
+ help="Print only IDs (one per line).",
803
+ ),
804
+ ]
805
+
806
+
807
+ def _to_header(name: str) -> str:
808
+ """Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE to be used as table header."""
809
+ s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
810
+ return s.upper()
811
+
812
+
813
+ def _format_value(value: Any) -> str:
814
+ """Convert a value to string for terminal display."""
815
+ if not value:
816
+ return ""
817
+ if isinstance(value, bool):
818
+ return "✔" if value else ""
819
+ if isinstance(value, datetime.datetime):
820
+ return value.strftime("%Y-%m-%d")
821
+ if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}T", value):
822
+ return value[:10]
823
+ if isinstance(value, list):
824
+ return ", ".join(_format_value(v) for v in value)
825
+ elif isinstance(value, dict):
826
+ if "name" in value: # Likely to be a user or org => print name
827
+ return str(value["name"])
828
+ # TODO: extend if needed
829
+ return json.dumps(value)
830
+ return str(value)
831
+
832
+
833
+ def _format_cell(value: Any, max_len: int = _MAX_CELL_LENGTH) -> str:
834
+ """Format a value + truncate it for table display."""
835
+ cell = _format_value(value)
836
+ if len(cell) > max_len:
837
+ cell = cell[: max_len - 3] + "..."
838
+ return cell
839
+
840
+
841
+ def print_as_table(
842
+ items: Sequence[dict[str, Any]],
843
+ headers: list[str],
844
+ row_fn: Callable[[dict[str, Any]], list[str]],
845
+ alignments: dict[str, str] | None = None,
846
+ ) -> None:
847
+ """Print items as a formatted table.
848
+
849
+ Args:
850
+ items: Sequence of dictionaries representing the items to display.
851
+ headers: List of column headers.
852
+ row_fn: Function that takes an item dict and returns a list of string values for each column.
853
+ alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
854
+ """
855
+ if not items:
856
+ print("No results found.")
857
+ return
858
+ rows = cast(list[list[Union[str, int]]], [row_fn(item) for item in items])
859
+ screaming_headers = [_to_header(h) for h in headers]
860
+ # Remap alignments keys to screaming case to match tabulate headers
861
+ screaming_alignments = {_to_header(k): v for k, v in (alignments or {}).items()}
862
+ print(tabulate(rows, headers=screaming_headers, alignments=screaming_alignments))
863
+
864
+
865
+ def print_list_output(
866
+ items: Sequence[dict[str, Any]],
867
+ format: OutputFormat,
868
+ quiet: bool,
869
+ id_key: str = "id",
870
+ headers: list[str] | None = None,
871
+ row_fn: Callable[[dict[str, Any]], list[str]] | None = None,
872
+ alignments: dict[str, str] | None = None,
873
+ ) -> None:
874
+ """Print list command output in the specified format.
875
+
876
+ Args:
877
+ items: Sequence of dictionaries representing the items to display.
878
+ format: Output format.
879
+ quiet: If True, print only IDs (one per line).
880
+ id_key: Key to use for extracting IDs in quiet mode.
881
+ headers: Optional list of column names for headers. If not provided, auto-detected from keys.
882
+ row_fn: Optional function to extract row values. If not provided, uses _format_cell on each column.
883
+ alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
884
+ """
885
+ if quiet:
886
+ for item in items:
887
+ print(item[id_key])
888
+ return
889
+
890
+ if format == OutputFormat.json:
891
+ print(json.dumps(list(items), indent=2, default=str))
892
+ return
893
+
894
+ if headers is None:
895
+ all_columns = list(items[0].keys()) if items else [id_key]
896
+ headers = [col for col in all_columns if any(_format_cell(item.get(col)) for item in items)]
897
+
898
+ if row_fn is None:
899
+
900
+ def row_fn(item: dict[str, Any]) -> list[str]:
901
+ return [_format_cell(item.get(col)) for col in headers] # type: ignore[union-attr]
902
+
903
+ print_as_table(items, headers=headers, row_fn=row_fn, alignments=alignments)
904
+
905
+
906
+ def _serialize_value(v: object) -> object:
907
+ """Recursively serialize a value to be JSON-compatible."""
908
+ if isinstance(v, datetime.datetime):
909
+ return v.isoformat()
910
+ elif isinstance(v, dict):
911
+ return {key: _serialize_value(val) for key, val in v.items() if val is not None}
912
+ elif isinstance(v, list):
913
+ return [_serialize_value(item) for item in v]
914
+ return v
915
+
916
+
917
+ def api_object_to_dict(info: Any) -> dict[str, Any]:
918
+ """Convert repo info dataclasses to json-serializable dicts."""
919
+ return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None}
920
+
921
+
922
+ def make_expand_properties_parser(valid_properties: Sequence[ExpandPropertyT]):
923
+ """Create a callback to parse and validate comma-separated expand properties."""
924
+
925
+ def _parse_expand_properties(value: str | None) -> list[ExpandPropertyT] | None:
926
+ if value is None:
927
+ return None
928
+ properties = [p.strip() for p in value.split(",")]
929
+ for prop in properties:
930
+ if prop not in valid_properties:
931
+ raise typer.BadParameter(
932
+ f"Invalid expand property: '{prop}'. Valid values are: {', '.join(valid_properties)}"
933
+ )
934
+ return [cast(ExpandPropertyT, prop) for prop in properties]
935
+
936
+ return _parse_expand_properties
937
+
938
+
939
+ ### PyPI VERSION CHECKER
940
+
941
+
942
+ def check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
943
+ """
944
+ Check whether a newer version of a library is available on PyPI.
945
+
946
+ If a newer version is found and stdin/stderr are attached to a TTY, prompt the user to update interactively.
947
+ Otherwise (non-TTY or update command cannot be determined), print a warning to stderr.
948
+
949
+ If current version is a pre-release (e.g. `1.0.0.rc1`), or a dev version (e.g. `1.0.0.dev1`), no check is performed.
950
+
951
+ This function is called at the entry point of the CLI. It only performs the check once every 24 hours, and any error
952
+ during the check is caught and logged, to avoid breaking the CLI.
953
+
954
+ Args:
955
+ library: The library to check for updates. Currently supports "huggingface_hub" and "transformers".
956
+ """
957
+ try:
958
+ _check_cli_update(library)
959
+ except Exception:
960
+ # We don't want the CLI to fail on version checks, no matter the reason.
961
+ logger.debug("Error while checking for CLI update.", exc_info=True)
962
+
963
+
964
+ def _check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
965
+ current_version = importlib.metadata.version(library)
966
+
967
+ # Skip if current version is a pre-release or dev version
968
+ if any(tag in current_version for tag in ["rc", "dev"]):
969
+ return
970
+
971
+ # Skip if already checked in the last 24 hours
972
+ if os.path.exists(constants.CHECK_FOR_UPDATE_DONE_PATH):
973
+ mtime = os.path.getmtime(constants.CHECK_FOR_UPDATE_DONE_PATH)
974
+ if (time.time() - mtime) < 24 * 3600:
975
+ return
976
+
977
+ # Touch the file to mark that we did the check now
978
+ Path(constants.CHECK_FOR_UPDATE_DONE_PATH).parent.mkdir(parents=True, exist_ok=True)
979
+ Path(constants.CHECK_FOR_UPDATE_DONE_PATH).touch()
980
+
981
+ # Check latest version from PyPI
982
+ response = get_session().get(f"https://pypi.org/pypi/{library}/json", timeout=2)
983
+ hf_raise_for_status(response)
984
+ data = response.json()
985
+ latest_version = data["info"]["version"]
986
+
987
+ if current_version == latest_version:
988
+ return
989
+
990
+ if library == "huggingface_hub":
991
+ update_command = _get_huggingface_hub_update_command()
992
+ else:
993
+ update_command = _get_transformers_update_command()
994
+
995
+ if sys.stdin.isatty() and sys.stderr.isatty() and update_command is not None:
996
+ _prompt_autoupdate(library, current_version, latest_version, update_command)
997
+ else:
998
+ display_cmd = " ".join(update_command) if update_command else None
999
+ update_hint = f"To update, run: {ANSI.bold(display_cmd)}" if display_cmd else ""
1000
+ click.echo(
1001
+ ANSI.yellow(
1002
+ f"A new version of {library} ({latest_version}) is available! "
1003
+ f"You are using version {current_version}." + (f"\n{update_hint}" if update_hint else "") + "\n"
1004
+ ),
1005
+ file=sys.stderr,
1006
+ )
1007
+
1008
+
1009
+ def _prompt_autoupdate(
1010
+ library: str,
1011
+ current_version: str,
1012
+ latest_version: str,
1013
+ update_command: list[str],
1014
+ ) -> None:
1015
+ """Interactively ask the user if they want to update, and run the update command if accepted.
1016
+
1017
+ After a successful update the CLI exits so the user can re-run their command with the new version.
1018
+ All output goes to stderr to keep stdout clean for command output.
1019
+ """
1020
+ display_cmd = " ".join(update_command)
1021
+
1022
+ click.echo("", file=sys.stderr)
1023
+ click.echo(
1024
+ ANSI.yellow(f" A new version of {library} is available: {current_version} → {latest_version}"),
1025
+ file=sys.stderr,
1026
+ )
1027
+ click.echo("", file=sys.stderr)
1028
+
1029
+ click.echo(
1030
+ ANSI.yellow(" Do you want to update now? [Y/n] ") + ANSI.gray(f"({display_cmd})") + " ",
1031
+ file=sys.stderr,
1032
+ nl=False,
1033
+ )
1034
+ try:
1035
+ raw_answer = sys.stdin.readline()
1036
+ except (EOFError, KeyboardInterrupt):
1037
+ click.echo("", file=sys.stderr)
1038
+ return
1039
+
1040
+ if raw_answer == "":
1041
+ # EOF (e.g. Ctrl+D) — treat as cancellation, not acceptance
1042
+ click.echo("", file=sys.stderr)
1043
+ return
1044
+
1045
+ answer = raw_answer.strip().lower() # Note: if user press 'Enter', raw_answer is `\n`
1046
+ if answer in ("", "y", "yes"):
1047
+ click.echo("", file=sys.stderr)
1048
+ click.echo(ANSI.gray(f" Running: {display_cmd}"), file=sys.stderr)
1049
+ click.echo("", file=sys.stderr)
1050
+ returncode = subprocess.call(update_command)
1051
+ if returncode == 0:
1052
+ click.echo("", file=sys.stderr)
1053
+ click.echo(
1054
+ ANSI.green(f" ✓ Successfully updated {library} to {latest_version}. Please re-run your command."),
1055
+ file=sys.stderr,
1056
+ )
1057
+ raise SystemExit(0)
1058
+ else:
1059
+ click.echo("", file=sys.stderr)
1060
+ click.echo(
1061
+ ANSI.red(f" ✗ Update failed (exit code {returncode}). Please update manually."),
1062
+ file=sys.stderr,
1063
+ )
1064
+ else:
1065
+ click.echo(
1066
+ ANSI.gray(f" Skipped. You can update later with: {display_cmd}"),
1067
+ file=sys.stderr,
1068
+ )
1069
+ click.echo("", file=sys.stderr)
1070
+
1071
+
1072
+ def _get_huggingface_hub_update_command() -> list[str] | None:
1073
+ """Return the command to update huggingface_hub as an argv list, or None if the installation method is unknown."""
1074
+ match installation_method():
1075
+ case "brew":
1076
+ return ["brew", "upgrade", "hf"]
1077
+ case "hf_installer" if os.name == "nt":
1078
+ return ["powershell", "-NoProfile", "-Command", "iwr -useb https://hf.co/cli/install.ps1 | iex"]
1079
+ case "hf_installer":
1080
+ return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -"]
1081
+ case "pip":
1082
+ return [sys.executable, "-m", "pip", "install", "-U", "huggingface_hub"]
1083
+ case _:
1084
+ return None
1085
+
1086
+
1087
+ def _get_transformers_update_command() -> list[str] | None:
1088
+ """Return the command to update transformers as an argv list, or None if the installation method is unknown."""
1089
+ match installation_method():
1090
+ case "hf_installer" if os.name == "nt":
1091
+ return [
1092
+ "powershell",
1093
+ "-NoProfile",
1094
+ "-Command",
1095
+ "iwr -useb https://hf.co/cli/install.ps1 | iex -WithTransformers",
1096
+ ]
1097
+ case "hf_installer":
1098
+ return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -s -- --with-transformers"]
1099
+ case "pip":
1100
+ return [sys.executable, "-m", "pip", "install", "-U", "transformers"]
1101
+ case _:
1102
+ return None
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_errors.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ """CLI error handling utilities."""
15
+
16
+ import traceback
17
+ from collections.abc import Callable
18
+
19
+ from huggingface_hub.errors import (
20
+ BucketNotFoundError,
21
+ CLIError,
22
+ CLIExtensionInstallError,
23
+ GatedRepoError,
24
+ HfHubHTTPError,
25
+ LocalTokenNotFoundError,
26
+ RemoteEntryNotFoundError,
27
+ RepositoryNotFoundError,
28
+ RevisionNotFoundError,
29
+ )
30
+
31
+
32
+ def _format_repo_not_found(error: RepositoryNotFoundError) -> str:
33
+ label = error.repo_type.capitalize() if error.repo_type else "Repository"
34
+ if error.repo_id:
35
+ msg = f"{label} '{error.repo_id}' not found."
36
+ else:
37
+ msg = f"{label} not found."
38
+ msg += " If the repo is private, make sure you are authenticated and your token has the required permissions."
39
+ return msg
40
+
41
+
42
+ def _format_gated_repo(error: GatedRepoError) -> str:
43
+ label = error.repo_type if error.repo_type else "repository"
44
+ if error.repo_id:
45
+ return f"Access denied. {label.capitalize()} '{error.repo_id}' requires approval."
46
+ return f"Access denied. This {label} requires approval."
47
+
48
+
49
+ def _format_bucket_not_found(error: BucketNotFoundError) -> str:
50
+ if error.bucket_id:
51
+ return f"Bucket '{error.bucket_id}' not found. If the bucket is private, make sure you are authenticated and your token has the required permissions."
52
+ return "Bucket not found. Check the bucket id (namespace/name). If the bucket is private, make sure you are authenticated and your token has the required permissions."
53
+
54
+
55
+ def _format_entry_not_found(error: RemoteEntryNotFoundError) -> str:
56
+ label = error.repo_type if error.repo_type else "repository"
57
+ url = str(error.response.url) if error.response else None
58
+ if error.repo_id:
59
+ msg = f"File not found in {label} '{error.repo_id}'."
60
+ else:
61
+ msg = f"File not found in {label}."
62
+ if url:
63
+ msg += f"\nURL: {url}"
64
+ return msg
65
+
66
+
67
+ def _format_revision_not_found(error: RevisionNotFoundError) -> str:
68
+ label = error.repo_type if error.repo_type else "repository"
69
+ if error.repo_id:
70
+ return f"Revision not found in {label} '{error.repo_id}'."
71
+ return f"Revision not found in {label}. Check the revision parameter."
72
+
73
+
74
+ def _format_cli_error(error: CLIError) -> str:
75
+ """No traceback, just the error message."""
76
+ return str(error)
77
+
78
+
79
+ def _format_cli_extension_install_error(error: CLIExtensionInstallError) -> str:
80
+ """Format a CLI extension installation error.
81
+
82
+ The error is likely to be a tricky subprocess error to investigate. In this specific case we want to format the
83
+ traceback of the root cause while keeping the "nicely formatted" error message of the CLIExtensionInstallError
84
+ as a 1-line message.
85
+ """
86
+ cause_tb = (
87
+ "".join(traceback.format_exception(type(error.__cause__), error.__cause__, error.__cause__.__traceback__))
88
+ if error.__cause__ is not None
89
+ else ""
90
+ )
91
+ return f"{cause_tb}\n{error}"
92
+
93
+
94
+ CLI_ERROR_MAPPINGS: dict[type[Exception], Callable[..., str]] = {
95
+ # GatedRepoError must come before RepositoryNotFoundError (it's a subclass).
96
+ GatedRepoError: _format_gated_repo,
97
+ BucketNotFoundError: _format_bucket_not_found,
98
+ RepositoryNotFoundError: _format_repo_not_found,
99
+ RevisionNotFoundError: _format_revision_not_found,
100
+ LocalTokenNotFoundError: lambda _: "Not logged in. Run 'hf auth login' first.",
101
+ RemoteEntryNotFoundError: _format_entry_not_found,
102
+ HfHubHTTPError: lambda error: str(error),
103
+ ValueError: lambda error: f"Invalid value. {error}",
104
+ CLIExtensionInstallError: _format_cli_extension_install_error,
105
+ CLIError: _format_cli_error,
106
+ }
107
+
108
+
109
+ def format_known_exception(error: Exception) -> str | None:
110
+ for exc_type, formatter in CLI_ERROR_MAPPINGS.items():
111
+ if isinstance(error, exc_type):
112
+ return formatter(error)
113
+ return None
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_output.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 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
+ """Output framework for the `hf` CLI."""
15
+
16
+ import dataclasses
17
+ import datetime
18
+ import json
19
+ import re
20
+ import sys
21
+ from collections.abc import Sequence
22
+ from enum import Enum
23
+ from typing import Any
24
+
25
+ from huggingface_hub.utils import ANSI, is_agent, tabulate
26
+
27
+
28
+ # TODO: remove OutputFormat in _cli_utils.py once all commands are migrated to OutputFormatWithAuto.
29
+ class OutputFormatWithAuto(str, Enum):
30
+ """Output format for CLI commands with auto detection of agent/human mode."""
31
+
32
+ agent = "agent"
33
+ auto = "auto"
34
+ human = "human"
35
+ json = "json"
36
+ quiet = "quiet"
37
+
38
+
39
+ class Output:
40
+ """Output sink for the `hf` CLI.
41
+
42
+ Mode is resolved once at init time based on `is_agent()` auto-detection
43
+ and can be overridden per-command via `set_mode()`.
44
+ """
45
+
46
+ mode: OutputFormatWithAuto
47
+
48
+ def __init__(self) -> None:
49
+ self.set_mode()
50
+
51
+ def set_mode(self, mode: OutputFormatWithAuto = OutputFormatWithAuto.auto) -> None:
52
+ """Override the output mode (called by commands that receive ``--format``)."""
53
+ if mode == OutputFormatWithAuto.auto:
54
+ mode = OutputFormatWithAuto.agent if is_agent() else OutputFormatWithAuto.human
55
+ self.mode = mode
56
+
57
+ def text(self, msg: str | None = None, *, human: str | None = None, agent: str | None = None) -> None:
58
+ """Print a free-form text message to stdout."""
59
+ if msg is not None:
60
+ if human is not None or agent is not None:
61
+ raise ValueError("Cannot mix 'msg' with 'human'/'agent'.")
62
+ human = msg
63
+ agent = _strip_ansi(msg)
64
+
65
+ match self.mode:
66
+ case OutputFormatWithAuto.human:
67
+ if human is not None:
68
+ print(human)
69
+ case OutputFormatWithAuto.agent:
70
+ if agent is not None:
71
+ print(agent)
72
+ # json/quiet: no-op
73
+
74
+ def table(
75
+ self,
76
+ items: Sequence[dict[str, Any]],
77
+ *,
78
+ headers: list[str] | None = None,
79
+ id_key: str | None = None,
80
+ alignments: dict[str, str] | None = None,
81
+ ) -> None:
82
+ """Print tabular data to stdout.
83
+
84
+ Args:
85
+ items: List of dicts. Headers are auto-detected from keys if not provided.
86
+ headers: Explicit column names. If None, derived from dict keys (all-None columns filtered).
87
+ id_key: Key to print in quiet mode. If None, uses the first header.
88
+ alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
89
+ """
90
+ if not items:
91
+ match self.mode:
92
+ case OutputFormatWithAuto.agent | OutputFormatWithAuto.human:
93
+ print("No results found.")
94
+ case OutputFormatWithAuto.json:
95
+ print("[]")
96
+ return
97
+
98
+ if headers is None:
99
+ all_columns = list(items[0].keys())
100
+ headers = [col for col in all_columns if any(item.get(col) is not None for item in items)]
101
+ rows = [[item.get(h) for h in headers] for item in items]
102
+
103
+ match self.mode:
104
+ case OutputFormatWithAuto.human: # padded table, truncated cells, SCREAMING_SNAKE headers
105
+ formatted_rows: list[list[str | int]] = [[_format_table_cell_human(v) for v in row] for row in rows]
106
+ screaming_headers = [_to_header(h) for h in headers]
107
+ screaming_alignments = {_to_header(k): v for k, v in (alignments or {}).items()}
108
+ print(tabulate(formatted_rows, headers=screaming_headers, alignments=screaming_alignments))
109
+ case OutputFormatWithAuto.agent: # TSV, no truncation, full timestamps
110
+ print("\t".join(headers))
111
+ for row in rows:
112
+ print("\t".join(_format_table_cell_agent(v) for v in row))
113
+ case OutputFormatWithAuto.json: # compact JSON array
114
+ print(json.dumps(list(items), default=str))
115
+ case OutputFormatWithAuto.quiet: # id_key column (or first column), one per line
116
+ quiet_key = id_key or headers[0]
117
+ for item in items:
118
+ print(item.get(quiet_key, ""))
119
+
120
+ def dict(self, data: Any) -> None:
121
+ """Print structured data as JSON in all modes (indented for human, compact otherwise).
122
+
123
+ Accepts a dict or a dataclass.
124
+ """
125
+ if dataclasses.is_dataclass(data) and not isinstance(data, type):
126
+ data = _dataclass_to_dict(data)
127
+ indent = 2 if self.mode == OutputFormatWithAuto.human else None
128
+ print(json.dumps(data, indent=indent, default=str))
129
+
130
+ def result(self, message: str, **data: Any) -> None:
131
+ """Print a success summary to stdout."""
132
+ match self.mode:
133
+ case OutputFormatWithAuto.human: # ✓ message + key: value lines
134
+ parts = [ANSI.green(f"✓ {message}")]
135
+ for k, v in data.items():
136
+ if v is not None:
137
+ parts.append(f" {k}: {v}")
138
+ print("\n".join(parts))
139
+ case OutputFormatWithAuto.agent: # key=val pairs, space-separated
140
+ parts = [f"{k}={v}" for k, v in data.items() if v is not None]
141
+ print(" ".join(parts) if parts else message)
142
+ case OutputFormatWithAuto.json: # json.dumps(data), message ignored
143
+ print(json.dumps(data, default=str) if data else "")
144
+ case OutputFormatWithAuto.quiet: # first value only
145
+ values = list(data.values())
146
+ if values:
147
+ print(values[0])
148
+
149
+ def warning(self, message: str) -> None:
150
+ """Print a non-fatal warning to stderr (all modes)."""
151
+ if self.mode == OutputFormatWithAuto.human:
152
+ print(ANSI.yellow(f"Warning: {message}"), file=sys.stderr)
153
+ else:
154
+ print(f"Warning: {message}", file=sys.stderr)
155
+
156
+ def error(self, message: str) -> None:
157
+ """Print an error to stderr (all modes)."""
158
+ if self.mode == OutputFormatWithAuto.human:
159
+ print(ANSI.red(f"Error: {message}"), file=sys.stderr)
160
+ else:
161
+ print(f"Error: {message}", file=sys.stderr)
162
+
163
+ def hint(self, message: str) -> None:
164
+ """Print a helpful hint to stderr (human: gray, agent/json: plain text)."""
165
+ if self.mode == OutputFormatWithAuto.human:
166
+ print(ANSI.gray(f"Hint: {message}"), file=sys.stderr)
167
+ else:
168
+ print(f"Hint: {message}", file=sys.stderr)
169
+
170
+
171
+ # HELPERS
172
+
173
+
174
+ def _serialize_value(v: object) -> object:
175
+ """Recursively serialize a value to be JSON-compatible."""
176
+ if isinstance(v, datetime.datetime):
177
+ return v.isoformat()
178
+ elif isinstance(v, dict):
179
+ return {key: _serialize_value(val) for key, val in v.items() if val is not None}
180
+ elif isinstance(v, list):
181
+ return [_serialize_value(item) for item in v]
182
+ return v
183
+
184
+
185
+ def _dataclass_to_dict(info: Any) -> dict[str, Any]:
186
+ """Convert a dataclass to a json-serializable dict."""
187
+ return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None}
188
+
189
+
190
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
191
+ _MAX_CELL_LENGTH = 35
192
+
193
+
194
+ def _strip_ansi(text: str) -> str:
195
+ return _ANSI_RE.sub("", text)
196
+
197
+
198
+ def _to_header(name: str) -> str:
199
+ """Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE."""
200
+ s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
201
+ return s.upper()
202
+
203
+
204
+ def _format_table_value_human(value: Any) -> str:
205
+ """Convert a value to string for terminal display."""
206
+ if value is None:
207
+ return ""
208
+ if isinstance(value, bool):
209
+ return "✔" if value else ""
210
+ if isinstance(value, datetime.datetime):
211
+ return value.strftime("%Y-%m-%d")
212
+ if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}T", value):
213
+ return value[:10]
214
+ if isinstance(value, list):
215
+ return ", ".join(_format_table_value_human(v) for v in value)
216
+ elif isinstance(value, dict):
217
+ if "name" in value: # Likely to be a user or org => print name
218
+ return str(value["name"])
219
+ return json.dumps(value)
220
+ return str(value)
221
+
222
+
223
+ def _format_table_cell_human(value: Any, max_len: int = _MAX_CELL_LENGTH) -> str:
224
+ """Format a value + truncate it for table display."""
225
+ cell = _format_table_value_human(value)
226
+ if len(cell) > max_len:
227
+ cell = cell[: max_len - 3] + "..."
228
+ return cell
229
+
230
+
231
+ def _format_table_cell_agent(value: Any) -> str:
232
+ """Format a cell value for agent TSV output (ISO timestamps, tabs escaped)."""
233
+ if isinstance(value, datetime.datetime):
234
+ return value.isoformat()
235
+ return str(value).replace("\t", " ")
236
+
237
+
238
+ out = Output()
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/_skills.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal helpers for Hugging Face marketplace skill installation and upgrades."""
2
+
3
+ import base64
4
+ import io
5
+ import json
6
+ import shutil
7
+ import tarfile
8
+ import tempfile
9
+ from dataclasses import dataclass, replace
10
+ from pathlib import Path, PurePosixPath
11
+ from typing import Any, Literal
12
+
13
+ from huggingface_hub.errors import CLIError
14
+ from huggingface_hub.utils import get_session
15
+
16
+
17
+ DEFAULT_SKILLS_REPO_ID = "huggingface/skills"
18
+ DEFAULT_SKILLS_REPO_OWNER, DEFAULT_SKILLS_REPO_NAME = DEFAULT_SKILLS_REPO_ID.split("/")
19
+ DEFAULT_SKILLS_REF = "main"
20
+ MARKETPLACE_PATH = ".claude-plugin/marketplace.json"
21
+ GITHUB_API_TIMEOUT = 10
22
+ SKILL_MANIFEST_FILENAME = ".hf-skill-manifest.json"
23
+ SKILL_MANIFEST_SCHEMA_VERSION = 1
24
+
25
+ SkillUpdateStatus = Literal[
26
+ "up_to_date",
27
+ "update_available",
28
+ "updated",
29
+ "unmanaged",
30
+ "invalid_metadata",
31
+ "source_unreachable",
32
+ ]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class MarketplaceSkill:
37
+ name: str
38
+ repo_path: str
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class InstalledSkillManifest:
43
+ schema_version: int
44
+ installed_revision: str
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class SkillUpdateInfo:
49
+ name: str
50
+ skill_dir: Path
51
+ status: SkillUpdateStatus
52
+ detail: str | None = None
53
+ current_revision: str | None = None
54
+ available_revision: str | None = None
55
+
56
+
57
+ def load_marketplace_skills() -> list[MarketplaceSkill]:
58
+ """Load skills from the default Hugging Face marketplace."""
59
+ payload = _load_marketplace_payload()
60
+ plugins = payload.get("plugins")
61
+ if not isinstance(plugins, list):
62
+ raise CLIError("Invalid marketplace payload: expected a top-level 'plugins' list.")
63
+
64
+ skills: list[MarketplaceSkill] = []
65
+ for plugin in plugins:
66
+ if not isinstance(plugin, dict):
67
+ continue
68
+ name = plugin.get("name")
69
+ source = plugin.get("source")
70
+ if not isinstance(name, str) or not isinstance(source, str):
71
+ continue
72
+ skills.append(MarketplaceSkill(name=name, repo_path=_normalize_repo_path(source)))
73
+ return skills
74
+
75
+
76
+ def get_marketplace_skill(selector: str) -> MarketplaceSkill:
77
+ """Resolve a marketplace skill by name."""
78
+ selected = _select_marketplace_skill(load_marketplace_skills(), selector)
79
+ if selected is None:
80
+ raise CLIError(
81
+ f"Skill '{selector}' not found in {DEFAULT_SKILLS_REPO_ID}. "
82
+ "Try `hf skills add` to install `hf-cli` or use a known skill name."
83
+ )
84
+ return selected
85
+
86
+
87
+ def install_marketplace_skill(skill: MarketplaceSkill, destination_root: Path, force: bool = False) -> Path:
88
+ """Install a marketplace skill into a local skills directory."""
89
+ destination_root = destination_root.expanduser().resolve()
90
+ destination_root.mkdir(parents=True, exist_ok=True)
91
+ install_dir = destination_root / skill.name
92
+
93
+ if install_dir.exists() and not force:
94
+ raise FileExistsError(f"Skill already exists: {install_dir}")
95
+
96
+ if install_dir.exists():
97
+ with tempfile.TemporaryDirectory(dir=destination_root, prefix=f".{install_dir.name}.install-") as tmp_dir_str:
98
+ tmp_dir = Path(tmp_dir_str)
99
+ staged_dir = tmp_dir / install_dir.name
100
+ _populate_install_dir(skill=skill, install_dir=staged_dir)
101
+ _atomic_replace_directory(existing_dir=install_dir, staged_dir=staged_dir)
102
+ return install_dir
103
+
104
+ try:
105
+ _populate_install_dir(skill=skill, install_dir=install_dir)
106
+ except Exception:
107
+ if install_dir.exists():
108
+ shutil.rmtree(install_dir)
109
+ raise
110
+ return install_dir
111
+
112
+
113
+ def check_for_updates(
114
+ roots: list[Path],
115
+ selector: str | None = None,
116
+ ) -> list[SkillUpdateInfo]:
117
+ """Check managed skill installs for newer upstream revisions."""
118
+ marketplace_skills = {skill.name.lower(): skill for skill in load_marketplace_skills()}
119
+ updates = [_evaluate_update(skill_dir, marketplace_skills) for skill_dir in _iter_unique_skill_dirs(roots)]
120
+ filtered = _filter_updates(updates, selector)
121
+ if selector is not None and not filtered:
122
+ raise CLIError(f"No installed skills match '{selector}'.")
123
+ return filtered
124
+
125
+
126
+ def apply_updates(
127
+ roots: list[Path],
128
+ selector: str | None = None,
129
+ ) -> list[SkillUpdateInfo]:
130
+ """Upgrade managed skills in place when the upstream revision changes."""
131
+ updates = check_for_updates(roots, selector)
132
+ results: list[SkillUpdateInfo] = []
133
+ for update in updates:
134
+ results.append(_apply_single_update(update))
135
+ return results
136
+
137
+
138
+ def read_installed_skill_manifest(skill_dir: Path) -> tuple[InstalledSkillManifest | None, str | None]:
139
+ """Read local skill metadata written by `hf skills add`."""
140
+ manifest_path = skill_dir / SKILL_MANIFEST_FILENAME
141
+ if not manifest_path.exists():
142
+ return None, None
143
+ try:
144
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
145
+ except Exception as exc: # noqa: BLE001
146
+ return None, f"invalid json: {exc}"
147
+ if not isinstance(payload, dict):
148
+ return None, "metadata root must be an object"
149
+ try:
150
+ return _parse_installed_skill_manifest(payload), None
151
+ except ValueError as exc:
152
+ return None, str(exc)
153
+
154
+
155
+ def write_installed_skill_manifest(skill_dir: Path, manifest: InstalledSkillManifest) -> None:
156
+ payload = {
157
+ "schema_version": manifest.schema_version,
158
+ "installed_revision": manifest.installed_revision,
159
+ }
160
+ (skill_dir / SKILL_MANIFEST_FILENAME).write_text(
161
+ json.dumps(payload, indent=2, sort_keys=True) + "\n",
162
+ encoding="utf-8",
163
+ )
164
+
165
+
166
+ def _load_marketplace_payload() -> dict[str, Any]:
167
+ response = _fetch_from_skills_repo(
168
+ f"contents/{MARKETPLACE_PATH}",
169
+ params={"ref": DEFAULT_SKILLS_REF},
170
+ )
171
+ try:
172
+ payload = response.json()
173
+ except Exception as exc: # noqa: BLE001
174
+ raise CLIError(f"Failed to decode GitHub API response for 'contents/{MARKETPLACE_PATH}': {exc}") from exc
175
+ if not isinstance(payload, dict):
176
+ raise CLIError("Invalid marketplace response: expected a JSON object.")
177
+
178
+ content = payload.get("content")
179
+ encoding = payload.get("encoding")
180
+ if not isinstance(content, str) or encoding != "base64":
181
+ raise CLIError("Invalid marketplace payload: expected base64-encoded content.")
182
+
183
+ try:
184
+ decoded = base64.b64decode(content).decode("utf-8")
185
+ parsed = json.loads(decoded)
186
+ except Exception as exc: # noqa: BLE001
187
+ raise CLIError(f"Failed to decode marketplace payload: {exc}") from exc
188
+
189
+ if not isinstance(parsed, dict):
190
+ raise CLIError("Invalid marketplace payload: expected a JSON object.")
191
+ return parsed
192
+
193
+
194
+ def _select_marketplace_skill(skills: list[MarketplaceSkill], selector: str) -> MarketplaceSkill | None:
195
+ selector_lower = selector.strip().lower()
196
+ for skill in skills:
197
+ if skill.name.lower() == selector_lower:
198
+ return skill
199
+ return None
200
+
201
+
202
+ def _normalize_repo_path(path: str) -> str:
203
+ normalized = path.strip()
204
+ while normalized.startswith("./"):
205
+ normalized = normalized[2:]
206
+ normalized = normalized.strip("/")
207
+ if not normalized:
208
+ raise CLIError("Invalid marketplace entry: empty source path.")
209
+ return normalized
210
+
211
+
212
+ def _populate_install_dir(skill: MarketplaceSkill, install_dir: Path) -> None:
213
+ installed_revision = _resolve_available_revision(skill)
214
+ install_dir.mkdir(parents=True, exist_ok=True)
215
+ _extract_remote_github_path(
216
+ revision=installed_revision,
217
+ source_path=skill.repo_path,
218
+ install_dir=install_dir,
219
+ )
220
+ _validate_installed_skill_dir(install_dir)
221
+ write_installed_skill_manifest(
222
+ install_dir,
223
+ InstalledSkillManifest(
224
+ schema_version=SKILL_MANIFEST_SCHEMA_VERSION,
225
+ installed_revision=installed_revision,
226
+ ),
227
+ )
228
+
229
+
230
+ def _validate_installed_skill_dir(skill_dir: Path) -> None:
231
+ skill_file = skill_dir / "SKILL.md"
232
+ if not skill_file.is_file():
233
+ raise RuntimeError(f"Installed skill is missing SKILL.md: {skill_file}")
234
+
235
+
236
+ def _extract_remote_github_path(revision: str, source_path: str, install_dir: Path) -> None:
237
+ tar_bytes = _fetch_from_skills_repo(f"tarball/{revision}").content
238
+ _extract_tar_subpath(tar_bytes, source_path=source_path, install_dir=install_dir)
239
+
240
+
241
+ def _extract_tar_subpath(tar_bytes: bytes, source_path: str, install_dir: Path) -> None:
242
+ """Extract a skill subdirectory from a tar archive.
243
+
244
+ GitHub tarballs include a leading `<repo>-<revision>/` directory. The helper also
245
+ accepts archives that start directly at `skills/<name>/...` to keep tests simple.
246
+ """
247
+ source_parts = PurePosixPath(source_path).parts
248
+ with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:*") as archive:
249
+ members = archive.getmembers()
250
+ matched = False
251
+ for member in members:
252
+ relative_parts = _member_relative_parts(member_name=member.name, source_parts=source_parts)
253
+ if relative_parts is None:
254
+ continue
255
+ if not relative_parts:
256
+ matched = True
257
+ continue
258
+ matched = True
259
+ relative_path = Path(*relative_parts)
260
+ if ".." in relative_path.parts:
261
+ raise RuntimeError(f"Invalid path found in archive for {source_path}.")
262
+ destination_path = install_dir / relative_path
263
+ if member.isdir():
264
+ destination_path.mkdir(parents=True, exist_ok=True)
265
+ continue
266
+ if not member.isfile():
267
+ continue
268
+ destination_path.parent.mkdir(parents=True, exist_ok=True)
269
+ extracted = archive.extractfile(member)
270
+ if extracted is None:
271
+ raise RuntimeError(f"Failed to extract {member.name}.")
272
+ destination_path.write_bytes(extracted.read())
273
+ if not matched:
274
+ raise FileNotFoundError(f"Path '{source_path}' not found in source archive.")
275
+
276
+
277
+ def _member_relative_parts(member_name: str, source_parts: tuple[str, ...]) -> tuple[str, ...] | None:
278
+ path_parts = PurePosixPath(member_name).parts
279
+ if tuple(path_parts[: len(source_parts)]) == source_parts:
280
+ return path_parts[len(source_parts) :]
281
+ if len(path_parts) > len(source_parts) and tuple(path_parts[1 : 1 + len(source_parts)]) == source_parts:
282
+ return path_parts[1 + len(source_parts) :]
283
+ return None
284
+
285
+
286
+ def _atomic_replace_directory(existing_dir: Path, staged_dir: Path) -> None:
287
+ backup_dir = staged_dir.parent / f"{existing_dir.name}.backup"
288
+ try:
289
+ existing_dir.rename(backup_dir)
290
+ staged_dir.rename(existing_dir)
291
+ shutil.rmtree(backup_dir)
292
+ except Exception:
293
+ if backup_dir.exists() and not existing_dir.exists():
294
+ backup_dir.rename(existing_dir)
295
+ raise
296
+
297
+
298
+ def _iter_unique_skill_dirs(roots: list[Path]) -> list[Path]:
299
+ seen: set[Path] = set()
300
+ discovered: list[Path] = []
301
+ for root in roots:
302
+ root = root.expanduser().resolve()
303
+ if not root.is_dir():
304
+ continue
305
+ for child in sorted(root.iterdir()):
306
+ if child.name.startswith("."):
307
+ continue
308
+ if not child.is_dir() and not child.is_symlink():
309
+ continue
310
+ resolved = child.resolve()
311
+ if resolved in seen or not resolved.is_dir():
312
+ continue
313
+ seen.add(resolved)
314
+ discovered.append(resolved)
315
+ return discovered
316
+
317
+
318
+ def _evaluate_update(skill_dir: Path, marketplace_skills: dict[str, MarketplaceSkill]) -> SkillUpdateInfo:
319
+ base = SkillUpdateInfo(name=skill_dir.name, skill_dir=skill_dir, status="unmanaged")
320
+
321
+ manifest, error = read_installed_skill_manifest(skill_dir)
322
+ if manifest is None:
323
+ return replace(base, status="invalid_metadata" if error else "unmanaged", detail=error)
324
+
325
+ skill = marketplace_skills.get(skill_dir.name.lower())
326
+ if skill is None:
327
+ return replace(
328
+ base,
329
+ status="source_unreachable",
330
+ detail=f"Skill '{skill_dir.name}' is no longer available in {DEFAULT_SKILLS_REPO_ID}.",
331
+ current_revision=manifest.installed_revision,
332
+ )
333
+
334
+ current_revision = manifest.installed_revision
335
+ try:
336
+ available_revision = _resolve_available_revision(skill)
337
+ except Exception as exc:
338
+ return replace(base, status="source_unreachable", detail=str(exc), current_revision=current_revision)
339
+
340
+ status: SkillUpdateStatus = "up_to_date" if available_revision == current_revision else "update_available"
341
+ return replace(
342
+ base,
343
+ status=status,
344
+ detail="update available" if status == "update_available" else None,
345
+ current_revision=current_revision,
346
+ available_revision=available_revision,
347
+ )
348
+
349
+
350
+ def _apply_single_update(update: SkillUpdateInfo) -> SkillUpdateInfo:
351
+ if update.status != "update_available":
352
+ return update
353
+
354
+ try:
355
+ skill = get_marketplace_skill(update.skill_dir.name)
356
+ install_marketplace_skill(skill, update.skill_dir.parent, force=True)
357
+ except Exception as exc:
358
+ return replace(update, status="source_unreachable", detail=str(exc))
359
+
360
+ return replace(update, status="updated", detail="updated")
361
+
362
+
363
+ def _filter_updates(updates: list[SkillUpdateInfo], selector: str | None) -> list[SkillUpdateInfo]:
364
+ if selector is None:
365
+ return updates
366
+ selector_lower = selector.strip().lower()
367
+ return [update for update in updates if update.name.lower() == selector_lower]
368
+
369
+
370
+ def _resolve_available_revision(skill: MarketplaceSkill) -> str:
371
+ response = _fetch_from_skills_repo(
372
+ "commits",
373
+ params={"sha": DEFAULT_SKILLS_REF, "path": skill.repo_path, "per_page": 1},
374
+ )
375
+ try:
376
+ payload = response.json()
377
+ except Exception as exc: # noqa: BLE001
378
+ raise CLIError(f"Failed to decode GitHub API response for 'commits': {exc}") from exc
379
+ if not isinstance(payload, list) or not payload:
380
+ raise CLIError(f"Unable to resolve the current revision for skill '{skill.name}'.")
381
+
382
+ latest = payload[0]
383
+ if not isinstance(latest, dict):
384
+ raise CLIError(f"Invalid commit response while resolving skill '{skill.name}'.")
385
+
386
+ revision = latest.get("sha")
387
+ if not isinstance(revision, str) or not revision:
388
+ raise CLIError(f"Invalid commit response while resolving skill '{skill.name}'.")
389
+ return revision
390
+
391
+
392
+ def _parse_installed_skill_manifest(payload: dict[str, Any]) -> InstalledSkillManifest:
393
+ if payload.get("schema_version") != SKILL_MANIFEST_SCHEMA_VERSION:
394
+ raise ValueError(f"unsupported schema_version: {payload.get('schema_version')}")
395
+
396
+ installed_revision = payload.get("installed_revision")
397
+ if not isinstance(installed_revision, str) or not installed_revision:
398
+ raise ValueError("missing installed_revision")
399
+
400
+ return InstalledSkillManifest(
401
+ schema_version=SKILL_MANIFEST_SCHEMA_VERSION,
402
+ installed_revision=installed_revision,
403
+ )
404
+
405
+
406
+ def _fetch_from_skills_repo(endpoint: str, params: dict[str, Any] | None = None) -> Any:
407
+ url = f"https://api.github.com/repos/{DEFAULT_SKILLS_REPO_OWNER}/{DEFAULT_SKILLS_REPO_NAME}/{endpoint.lstrip('/')}"
408
+ try:
409
+ response = get_session().get(
410
+ url,
411
+ params=params,
412
+ headers={"Accept": "application/vnd.github+json"},
413
+ follow_redirects=True,
414
+ timeout=GITHUB_API_TIMEOUT,
415
+ )
416
+ response.raise_for_status()
417
+ except Exception as exc: # noqa: BLE001
418
+ raise CLIError(f"Failed to fetch '{endpoint}' from {DEFAULT_SKILLS_REPO_ID}: {exc}") from exc
419
+ return response
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/__init__.py ADDED
File without changes
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/_async_client.py ADDED
The diff for this file is too large to render. See raw diff
 
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/__init__.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ChatCompletionInputJSONSchema,
28
+ ChatCompletionInputMessage,
29
+ ChatCompletionInputMessageChunk,
30
+ ChatCompletionInputMessageChunkType,
31
+ ChatCompletionInputResponseFormatJSONObject,
32
+ ChatCompletionInputResponseFormatJSONSchema,
33
+ ChatCompletionInputResponseFormatText,
34
+ ChatCompletionInputStreamOptions,
35
+ ChatCompletionInputTool,
36
+ ChatCompletionInputToolCall,
37
+ ChatCompletionInputToolChoiceClass,
38
+ ChatCompletionInputToolChoiceEnum,
39
+ ChatCompletionInputURL,
40
+ ChatCompletionOutput,
41
+ ChatCompletionOutputComplete,
42
+ ChatCompletionOutputFunctionDefinition,
43
+ ChatCompletionOutputLogprob,
44
+ ChatCompletionOutputLogprobs,
45
+ ChatCompletionOutputMessage,
46
+ ChatCompletionOutputToolCall,
47
+ ChatCompletionOutputTopLogprob,
48
+ ChatCompletionOutputUsage,
49
+ ChatCompletionStreamOutput,
50
+ ChatCompletionStreamOutputChoice,
51
+ ChatCompletionStreamOutputDelta,
52
+ ChatCompletionStreamOutputDeltaToolCall,
53
+ ChatCompletionStreamOutputFunction,
54
+ ChatCompletionStreamOutputLogprob,
55
+ ChatCompletionStreamOutputLogprobs,
56
+ ChatCompletionStreamOutputTopLogprob,
57
+ ChatCompletionStreamOutputUsage,
58
+ )
59
+ from .depth_estimation import DepthEstimationInput, DepthEstimationOutput
60
+ from .document_question_answering import (
61
+ DocumentQuestionAnsweringInput,
62
+ DocumentQuestionAnsweringInputData,
63
+ DocumentQuestionAnsweringOutputElement,
64
+ DocumentQuestionAnsweringParameters,
65
+ )
66
+ from .feature_extraction import FeatureExtractionInput, FeatureExtractionInputTruncationDirection
67
+ from .fill_mask import FillMaskInput, FillMaskOutputElement, FillMaskParameters
68
+ from .image_classification import (
69
+ ImageClassificationInput,
70
+ ImageClassificationOutputElement,
71
+ ImageClassificationOutputTransform,
72
+ ImageClassificationParameters,
73
+ )
74
+ from .image_segmentation import (
75
+ ImageSegmentationInput,
76
+ ImageSegmentationOutputElement,
77
+ ImageSegmentationParameters,
78
+ ImageSegmentationSubtask,
79
+ )
80
+ from .image_text_to_image import (
81
+ ImageTextToImageInput,
82
+ ImageTextToImageOutput,
83
+ ImageTextToImageParameters,
84
+ ImageTextToImageTargetSize,
85
+ )
86
+ from .image_text_to_video import (
87
+ ImageTextToVideoInput,
88
+ ImageTextToVideoOutput,
89
+ ImageTextToVideoParameters,
90
+ ImageTextToVideoTargetSize,
91
+ )
92
+ from .image_to_image import ImageToImageInput, ImageToImageOutput, ImageToImageParameters, ImageToImageTargetSize
93
+ from .image_to_text import (
94
+ ImageToTextEarlyStoppingEnum,
95
+ ImageToTextGenerationParameters,
96
+ ImageToTextInput,
97
+ ImageToTextOutput,
98
+ ImageToTextParameters,
99
+ )
100
+ from .image_to_video import ImageToVideoInput, ImageToVideoOutput, ImageToVideoParameters, ImageToVideoTargetSize
101
+ from .object_detection import (
102
+ ObjectDetectionBoundingBox,
103
+ ObjectDetectionInput,
104
+ ObjectDetectionOutputElement,
105
+ ObjectDetectionParameters,
106
+ )
107
+ from .question_answering import (
108
+ QuestionAnsweringInput,
109
+ QuestionAnsweringInputData,
110
+ QuestionAnsweringOutputElement,
111
+ QuestionAnsweringParameters,
112
+ )
113
+ from .sentence_similarity import SentenceSimilarityInput, SentenceSimilarityInputData
114
+ from .summarization import (
115
+ SummarizationInput,
116
+ SummarizationOutput,
117
+ SummarizationParameters,
118
+ SummarizationTruncationStrategy,
119
+ )
120
+ from .table_question_answering import (
121
+ Padding,
122
+ TableQuestionAnsweringInput,
123
+ TableQuestionAnsweringInputData,
124
+ TableQuestionAnsweringOutputElement,
125
+ TableQuestionAnsweringParameters,
126
+ )
127
+ from .text2text_generation import (
128
+ Text2TextGenerationInput,
129
+ Text2TextGenerationOutput,
130
+ Text2TextGenerationParameters,
131
+ Text2TextGenerationTruncationStrategy,
132
+ )
133
+ from .text_classification import (
134
+ TextClassificationInput,
135
+ TextClassificationOutputElement,
136
+ TextClassificationOutputTransform,
137
+ TextClassificationParameters,
138
+ )
139
+ from .text_generation import (
140
+ TextGenerationInput,
141
+ TextGenerationInputGenerateParameters,
142
+ TextGenerationInputGrammarType,
143
+ TextGenerationOutput,
144
+ TextGenerationOutputBestOfSequence,
145
+ TextGenerationOutputDetails,
146
+ TextGenerationOutputFinishReason,
147
+ TextGenerationOutputPrefillToken,
148
+ TextGenerationOutputToken,
149
+ TextGenerationStreamOutput,
150
+ TextGenerationStreamOutputStreamDetails,
151
+ TextGenerationStreamOutputToken,
152
+ TypeEnum,
153
+ )
154
+ from .text_to_audio import (
155
+ TextToAudioEarlyStoppingEnum,
156
+ TextToAudioGenerationParameters,
157
+ TextToAudioInput,
158
+ TextToAudioOutput,
159
+ TextToAudioParameters,
160
+ )
161
+ from .text_to_image import TextToImageInput, TextToImageOutput, TextToImageParameters
162
+ from .text_to_speech import (
163
+ TextToSpeechEarlyStoppingEnum,
164
+ TextToSpeechGenerationParameters,
165
+ TextToSpeechInput,
166
+ TextToSpeechOutput,
167
+ TextToSpeechParameters,
168
+ )
169
+ from .text_to_video import TextToVideoInput, TextToVideoOutput, TextToVideoParameters
170
+ from .token_classification import (
171
+ TokenClassificationAggregationStrategy,
172
+ TokenClassificationInput,
173
+ TokenClassificationOutputElement,
174
+ TokenClassificationParameters,
175
+ )
176
+ from .translation import TranslationInput, TranslationOutput, TranslationParameters, TranslationTruncationStrategy
177
+ from .video_classification import (
178
+ VideoClassificationInput,
179
+ VideoClassificationOutputElement,
180
+ VideoClassificationOutputTransform,
181
+ VideoClassificationParameters,
182
+ )
183
+ from .visual_question_answering import (
184
+ VisualQuestionAnsweringInput,
185
+ VisualQuestionAnsweringInputData,
186
+ VisualQuestionAnsweringOutputElement,
187
+ VisualQuestionAnsweringParameters,
188
+ )
189
+ from .zero_shot_classification import (
190
+ ZeroShotClassificationInput,
191
+ ZeroShotClassificationOutputElement,
192
+ ZeroShotClassificationParameters,
193
+ )
194
+ from .zero_shot_image_classification import (
195
+ ZeroShotImageClassificationInput,
196
+ ZeroShotImageClassificationOutputElement,
197
+ ZeroShotImageClassificationParameters,
198
+ )
199
+ from .zero_shot_object_detection import (
200
+ ZeroShotObjectDetectionBoundingBox,
201
+ ZeroShotObjectDetectionInput,
202
+ ZeroShotObjectDetectionOutputElement,
203
+ ZeroShotObjectDetectionParameters,
204
+ )
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/audio_classification.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ AudioClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class AudioClassificationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Audio Classification"""
17
+
18
+ function_to_apply: Optional["AudioClassificationOutputTransform"] = None
19
+ """The function to apply to the model outputs in order to retrieve the scores."""
20
+ top_k: int | None = None
21
+ """When specified, limits the output to the top K most probable classes."""
22
+
23
+
24
+ @dataclass_with_extra
25
+ class AudioClassificationInput(BaseInferenceType):
26
+ """Inputs for Audio Classification inference"""
27
+
28
+ inputs: str
29
+ """The input audio data as a base64-encoded string. If no `parameters` are provided, you can
30
+ also provide the audio data as a raw bytes payload.
31
+ """
32
+ parameters: AudioClassificationParameters | None = None
33
+ """Additional inference parameters for Audio Classification"""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class AudioClassificationOutputElement(BaseInferenceType):
38
+ """Outputs for Audio Classification inference"""
39
+
40
+ label: str
41
+ """The predicted class label."""
42
+ score: float
43
+ """The corresponding probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/audio_to_audio.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class AudioToAudioInput(BaseInferenceType):
13
+ """Inputs for Audio to Audio inference"""
14
+
15
+ inputs: Any
16
+ """The input audio data"""
17
+
18
+
19
+ @dataclass_with_extra
20
+ class AudioToAudioOutputElement(BaseInferenceType):
21
+ """Outputs of inference for the Audio To Audio task
22
+ A generated audio file with its label.
23
+ """
24
+
25
+ blob: Any
26
+ """The generated audio file."""
27
+ content_type: str
28
+ """The content type of audio file."""
29
+ label: str
30
+ """The label of the audio file."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/automatic_speech_recognition.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Union
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ AutomaticSpeechRecognitionEarlyStoppingEnum = Literal["never"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class AutomaticSpeechRecognitionGenerationParameters(BaseInferenceType):
16
+ """Parametrization of the text generation process"""
17
+
18
+ do_sample: bool | None = None
19
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
20
+ early_stopping: Union[bool, "AutomaticSpeechRecognitionEarlyStoppingEnum"] | None = None
21
+ """Controls the stopping condition for beam-based methods."""
22
+ epsilon_cutoff: float | None = None
23
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
24
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
25
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
26
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
27
+ """
28
+ eta_cutoff: float | None = None
29
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
30
+ float strictly between 0 and 1, a token is only considered if it is greater than either
31
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
32
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
33
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
34
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
35
+ for more details.
36
+ """
37
+ max_length: int | None = None
38
+ """The maximum length (in tokens) of the generated text, including the input."""
39
+ max_new_tokens: int | None = None
40
+ """The maximum number of tokens to generate. Takes precedence over max_length."""
41
+ min_length: int | None = None
42
+ """The minimum length (in tokens) of the generated text, including the input."""
43
+ min_new_tokens: int | None = None
44
+ """The minimum number of tokens to generate. Takes precedence over min_length."""
45
+ num_beam_groups: int | None = None
46
+ """Number of groups to divide num_beams into in order to ensure diversity among different
47
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
48
+ """
49
+ num_beams: int | None = None
50
+ """Number of beams to use for beam search."""
51
+ penalty_alpha: float | None = None
52
+ """The value balances the model confidence and the degeneration penalty in contrastive
53
+ search decoding.
54
+ """
55
+ temperature: float | None = None
56
+ """The value used to modulate the next token probabilities."""
57
+ top_k: int | None = None
58
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
59
+ top_p: float | None = None
60
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
61
+ that add up to top_p or higher are kept for generation.
62
+ """
63
+ typical_p: float | None = None
64
+ """Local typicality measures how similar the conditional probability of predicting a target
65
+ token next is to the expected conditional probability of predicting a random token next,
66
+ given the partial text already generated. If set to float < 1, the smallest set of the
67
+ most locally typical tokens with probabilities that add up to typical_p or higher are
68
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
69
+ """
70
+ use_cache: bool | None = None
71
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
72
+
73
+
74
+ @dataclass_with_extra
75
+ class AutomaticSpeechRecognitionParameters(BaseInferenceType):
76
+ """Additional inference parameters for Automatic Speech Recognition"""
77
+
78
+ generation_parameters: AutomaticSpeechRecognitionGenerationParameters | None = None
79
+ """Parametrization of the text generation process"""
80
+ return_timestamps: bool | None = None
81
+ """Whether to output corresponding timestamps with the generated text"""
82
+
83
+
84
+ @dataclass_with_extra
85
+ class AutomaticSpeechRecognitionInput(BaseInferenceType):
86
+ """Inputs for Automatic Speech Recognition inference"""
87
+
88
+ inputs: str
89
+ """The input audio data as a base64-encoded string. If no `parameters` are provided, you can
90
+ also provide the audio data as a raw bytes payload.
91
+ """
92
+ parameters: AutomaticSpeechRecognitionParameters | None = None
93
+ """Additional inference parameters for Automatic Speech Recognition"""
94
+
95
+
96
+ @dataclass_with_extra
97
+ class AutomaticSpeechRecognitionOutputChunk(BaseInferenceType):
98
+ text: str
99
+ """A chunk of text identified by the model"""
100
+ timestamp: list[float]
101
+ """The start and end timestamps corresponding with the text"""
102
+
103
+
104
+ @dataclass_with_extra
105
+ class AutomaticSpeechRecognitionOutput(BaseInferenceType):
106
+ """Outputs of inference for the Automatic Speech Recognition task"""
107
+
108
+ text: str
109
+ """The recognized text."""
110
+ chunks: list[AutomaticSpeechRecognitionOutputChunk] | None = None
111
+ """When returnTimestamps is enabled, chunks contains a list of audio chunks identified by
112
+ the model.
113
+ """
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/base.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import types
19
+ from dataclasses import asdict, dataclass
20
+ from typing import Any, TypeVar, get_args
21
+
22
+ from typing_extensions import dataclass_transform
23
+
24
+
25
+ T = TypeVar("T", bound="BaseInferenceType")
26
+
27
+
28
+ def _repr_with_extra(self):
29
+ fields = list(self.__dataclass_fields__.keys())
30
+ other_fields = list(k for k in self.__dict__ if k not in fields)
31
+ return f"{self.__class__.__name__}({', '.join(f'{k}={self.__dict__[k]!r}' for k in fields + other_fields)})"
32
+
33
+
34
+ @dataclass_transform()
35
+ def dataclass_with_extra(cls: type[T]) -> type[T]:
36
+ """Decorator to add a custom __repr__ method to a dataclass, showing all fields, including extra ones.
37
+
38
+ This decorator only works with dataclasses that inherit from `BaseInferenceType`.
39
+ """
40
+ cls = dataclass(cls)
41
+ cls.__repr__ = _repr_with_extra # type: ignore[method-assign]
42
+ return cls
43
+
44
+
45
+ @dataclass
46
+ class BaseInferenceType(dict):
47
+ """Base class for all inference types.
48
+
49
+ Object is a dataclass and a dict for backward compatibility but plan is to remove the dict part in the future.
50
+
51
+ Handle parsing from dict, list and json strings in a permissive way to ensure future-compatibility (e.g. all fields
52
+ are made optional, and non-expected fields are added as dict attributes).
53
+ """
54
+
55
+ @classmethod
56
+ def parse_obj_as_list(cls: type[T], data: bytes | str | list | dict) -> list[T]:
57
+ """Alias to parse server response and return a single instance.
58
+
59
+ See `parse_obj` for more details.
60
+ """
61
+ output = cls.parse_obj(data)
62
+ if not isinstance(output, list):
63
+ raise ValueError(f"Invalid input data for {cls}. Expected a list, but got {type(output)}.")
64
+ return output
65
+
66
+ @classmethod
67
+ def parse_obj_as_instance(cls: type[T], data: bytes | str | list | dict) -> T:
68
+ """Alias to parse server response and return a single instance.
69
+
70
+ See `parse_obj` for more details.
71
+ """
72
+ output = cls.parse_obj(data)
73
+ if isinstance(output, list):
74
+ raise ValueError(f"Invalid input data for {cls}. Expected a single instance, but got a list.")
75
+ return output
76
+
77
+ @classmethod
78
+ def parse_obj(cls: type[T], data: bytes | str | list | dict) -> list[T] | T:
79
+ """Parse server response as a dataclass or list of dataclasses.
80
+
81
+ To enable future-compatibility, we want to handle cases where the server return more fields than expected.
82
+ In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
83
+ added as dict attributes.
84
+ """
85
+ # Parse server response (from bytes)
86
+ if isinstance(data, bytes):
87
+ data = data.decode()
88
+ if isinstance(data, str):
89
+ data = json.loads(data)
90
+
91
+ # If a list, parse each item individually
92
+ if isinstance(data, list):
93
+ return [cls.parse_obj(d) for d in data] # type: ignore
94
+
95
+ # At this point, we expect a dict
96
+ if not isinstance(data, dict):
97
+ raise ValueError(f"Invalid data type: {type(data)}")
98
+
99
+ init_values = {}
100
+ other_values = {}
101
+ for key, value in data.items():
102
+ key = normalize_key(key)
103
+ if key in cls.__dataclass_fields__ and cls.__dataclass_fields__[key].init:
104
+ if isinstance(value, dict) or isinstance(value, list):
105
+ field_type = cls.__dataclass_fields__[key].type
106
+
107
+ # if `field_type` is a `BaseInferenceType`, parse it
108
+ if inspect.isclass(field_type) and issubclass(field_type, BaseInferenceType):
109
+ value = field_type.parse_obj(value)
110
+
111
+ # otherwise, recursively parse nested dataclasses (if possible)
112
+ # `get_args` returns handle Union and Optional for us
113
+ else:
114
+ expected_types = get_args(field_type)
115
+ for expected_type in expected_types:
116
+ if (
117
+ isinstance(expected_type, types.GenericAlias) and expected_type.__origin__ is list
118
+ ) or getattr(expected_type, "_name", None) == "List":
119
+ expected_type = get_args(expected_type)[
120
+ 0
121
+ ] # assume same type for all items in the list
122
+ if inspect.isclass(expected_type) and issubclass(expected_type, BaseInferenceType):
123
+ value = expected_type.parse_obj(value)
124
+ break
125
+ init_values[key] = value
126
+ else:
127
+ other_values[key] = value
128
+
129
+ # Make all missing fields default to None
130
+ # => ensure that dataclass initialization will never fail even if the server does not return all fields.
131
+ for key in cls.__dataclass_fields__:
132
+ if key not in init_values:
133
+ init_values[key] = None
134
+
135
+ # Initialize dataclass with expected values
136
+ item = cls(**init_values)
137
+
138
+ # Add remaining fields as dict attributes
139
+ item.update(other_values)
140
+
141
+ # Add remaining fields as extra dataclass fields.
142
+ # They won't be part of the dataclass fields but will be accessible as attributes.
143
+ # Use @dataclass_with_extra to show them in __repr__.
144
+ item.__dict__.update(other_values)
145
+ return item
146
+
147
+ def __post_init__(self):
148
+ self.update(asdict(self))
149
+
150
+ def __setitem__(self, __key: Any, __value: Any) -> None:
151
+ # Hacky way to keep dataclass values in sync when dict is updated
152
+ super().__setitem__(__key, __value)
153
+ if __key in self.__dataclass_fields__ and getattr(self, __key, None) != __value:
154
+ self.__setattr__(__key, __value)
155
+ return
156
+
157
+ def __setattr__(self, __name: str, __value: Any) -> None:
158
+ # Hacky way to keep dict values is sync when dataclass is updated
159
+ super().__setattr__(__name, __value)
160
+ if self.get(__name) != __value:
161
+ self[__name] = __value
162
+ return
163
+
164
+
165
+ def normalize_key(key: str) -> str:
166
+ # e.g "content-type" -> "content_type", "Accept" -> "accept"
167
+ return key.replace("-", "_").replace(" ", "_").lower()
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/chat_completion.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Union
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class ChatCompletionInputURL(BaseInferenceType):
13
+ url: str
14
+
15
+
16
+ ChatCompletionInputMessageChunkType = Literal["text", "image_url"]
17
+
18
+
19
+ @dataclass_with_extra
20
+ class ChatCompletionInputMessageChunk(BaseInferenceType):
21
+ type: "ChatCompletionInputMessageChunkType"
22
+ image_url: ChatCompletionInputURL | None = None
23
+ text: str | None = None
24
+
25
+
26
+ @dataclass_with_extra
27
+ class ChatCompletionInputFunctionDefinition(BaseInferenceType):
28
+ name: str
29
+ parameters: Any
30
+ description: str | None = None
31
+
32
+
33
+ @dataclass_with_extra
34
+ class ChatCompletionInputToolCall(BaseInferenceType):
35
+ function: ChatCompletionInputFunctionDefinition
36
+ id: str
37
+ type: str
38
+
39
+
40
+ @dataclass_with_extra
41
+ class ChatCompletionInputMessage(BaseInferenceType):
42
+ role: str
43
+ content: list[ChatCompletionInputMessageChunk] | str | None = None
44
+ name: str | None = None
45
+ tool_calls: list[ChatCompletionInputToolCall] | None = None
46
+
47
+
48
+ @dataclass_with_extra
49
+ class ChatCompletionInputJSONSchema(BaseInferenceType):
50
+ name: str
51
+ """
52
+ The name of the response format.
53
+ """
54
+ description: str | None = None
55
+ """
56
+ A description of what the response format is for, used by the model to determine
57
+ how to respond in the format.
58
+ """
59
+ schema: dict[str, object] | None = None
60
+ """
61
+ The schema for the response format, described as a JSON Schema object. Learn how
62
+ to build JSON schemas [here](https://json-schema.org/).
63
+ """
64
+ strict: bool | None = None
65
+ """
66
+ Whether to enable strict schema adherence when generating the output. If set to
67
+ true, the model will always follow the exact schema defined in the `schema`
68
+ field.
69
+ """
70
+
71
+
72
+ @dataclass_with_extra
73
+ class ChatCompletionInputResponseFormatText(BaseInferenceType):
74
+ type: Literal["text"]
75
+
76
+
77
+ @dataclass_with_extra
78
+ class ChatCompletionInputResponseFormatJSONSchema(BaseInferenceType):
79
+ type: Literal["json_schema"]
80
+ json_schema: ChatCompletionInputJSONSchema
81
+
82
+
83
+ @dataclass_with_extra
84
+ class ChatCompletionInputResponseFormatJSONObject(BaseInferenceType):
85
+ type: Literal["json_object"]
86
+
87
+
88
+ ChatCompletionInputGrammarType = Union[
89
+ ChatCompletionInputResponseFormatText,
90
+ ChatCompletionInputResponseFormatJSONSchema,
91
+ ChatCompletionInputResponseFormatJSONObject,
92
+ ]
93
+
94
+
95
+ @dataclass_with_extra
96
+ class ChatCompletionInputStreamOptions(BaseInferenceType):
97
+ include_usage: bool | None = None
98
+ """If set, an additional chunk will be streamed before the data: [DONE] message. The usage
99
+ field on this chunk shows the token usage statistics for the entire request, and the
100
+ choices field will always be an empty array. All other chunks will also include a usage
101
+ field, but with a null value.
102
+ """
103
+
104
+
105
+ @dataclass_with_extra
106
+ class ChatCompletionInputFunctionName(BaseInferenceType):
107
+ name: str
108
+
109
+
110
+ @dataclass_with_extra
111
+ class ChatCompletionInputToolChoiceClass(BaseInferenceType):
112
+ function: ChatCompletionInputFunctionName
113
+
114
+
115
+ ChatCompletionInputToolChoiceEnum = Literal["auto", "none", "required"]
116
+
117
+
118
+ @dataclass_with_extra
119
+ class ChatCompletionInputTool(BaseInferenceType):
120
+ function: ChatCompletionInputFunctionDefinition
121
+ type: str
122
+
123
+
124
+ @dataclass_with_extra
125
+ class ChatCompletionInput(BaseInferenceType):
126
+ """Chat Completion Input.
127
+ Auto-generated from TGI specs.
128
+ For more details, check out
129
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
130
+ """
131
+
132
+ messages: list[ChatCompletionInputMessage]
133
+ """A list of messages comprising the conversation so far."""
134
+ frequency_penalty: float | None = None
135
+ """Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing
136
+ frequency in the text so far,
137
+ decreasing the model's likelihood to repeat the same line verbatim.
138
+ """
139
+ logit_bias: list[float] | None = None
140
+ """UNUSED
141
+ Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON
142
+ object that maps tokens
143
+ (specified by their token ID in the tokenizer) to an associated bias value from -100 to
144
+ 100. Mathematically,
145
+ the bias is added to the logits generated by the model prior to sampling. The exact
146
+ effect will vary per model,
147
+ but values between -1 and 1 should decrease or increase likelihood of selection; values
148
+ like -100 or 100 should
149
+ result in a ban or exclusive selection of the relevant token.
150
+ """
151
+ logprobs: bool | None = None
152
+ """Whether to return log probabilities of the output tokens or not. If true, returns the log
153
+ probabilities of each
154
+ output token returned in the content of message.
155
+ """
156
+ max_tokens: int | None = None
157
+ """The maximum number of tokens that can be generated in the chat completion."""
158
+ model: str | None = None
159
+ """[UNUSED] ID of the model to use. See the model endpoint compatibility table for details
160
+ on which models work with the Chat API.
161
+ """
162
+ n: int | None = None
163
+ """UNUSED
164
+ How many chat completion choices to generate for each input message. Note that you will
165
+ be charged based on the
166
+ number of generated tokens across all of the choices. Keep n as 1 to minimize costs.
167
+ """
168
+ presence_penalty: float | None = None
169
+ """Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they
170
+ appear in the text so far,
171
+ increasing the model's likelihood to talk about new topics
172
+ """
173
+ response_format: ChatCompletionInputGrammarType | None = None
174
+ seed: int | None = None
175
+ stop: list[str] | None = None
176
+ """Up to 4 sequences where the API will stop generating further tokens."""
177
+ stream: bool | None = None
178
+ stream_options: ChatCompletionInputStreamOptions | None = None
179
+ temperature: float | None = None
180
+ """What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the
181
+ output more random, while
182
+ lower values like 0.2 will make it more focused and deterministic.
183
+ We generally recommend altering this or `top_p` but not both.
184
+ """
185
+ tool_choice: Union[ChatCompletionInputToolChoiceClass, "ChatCompletionInputToolChoiceEnum"] | None = None
186
+ tool_prompt: str | None = None
187
+ """A prompt to be appended before the tools"""
188
+ tools: list[ChatCompletionInputTool] | None = None
189
+ """A list of tools the model may call. Currently, only functions are supported as a tool.
190
+ Use this to provide a list of
191
+ functions the model may generate JSON inputs for.
192
+ """
193
+ top_logprobs: int | None = None
194
+ """An integer between 0 and 5 specifying the number of most likely tokens to return at each
195
+ token position, each with
196
+ an associated log probability. logprobs must be set to true if this parameter is used.
197
+ """
198
+ top_p: float | None = None
199
+ """An alternative to sampling with temperature, called nucleus sampling, where the model
200
+ considers the results of the
201
+ tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%
202
+ probability mass are considered.
203
+ """
204
+
205
+
206
+ @dataclass_with_extra
207
+ class ChatCompletionOutputTopLogprob(BaseInferenceType):
208
+ logprob: float
209
+ token: str
210
+
211
+
212
+ @dataclass_with_extra
213
+ class ChatCompletionOutputLogprob(BaseInferenceType):
214
+ logprob: float
215
+ token: str
216
+ top_logprobs: list[ChatCompletionOutputTopLogprob]
217
+
218
+
219
+ @dataclass_with_extra
220
+ class ChatCompletionOutputLogprobs(BaseInferenceType):
221
+ content: list[ChatCompletionOutputLogprob]
222
+
223
+
224
+ @dataclass_with_extra
225
+ class ChatCompletionOutputFunctionDefinition(BaseInferenceType):
226
+ arguments: str
227
+ name: str
228
+ description: str | None = None
229
+
230
+
231
+ @dataclass_with_extra
232
+ class ChatCompletionOutputToolCall(BaseInferenceType):
233
+ function: ChatCompletionOutputFunctionDefinition
234
+ id: str
235
+ type: str
236
+
237
+
238
+ @dataclass_with_extra
239
+ class ChatCompletionOutputMessage(BaseInferenceType):
240
+ role: str
241
+ content: str | None = None
242
+ reasoning: str | None = None
243
+ tool_call_id: str | None = None
244
+ tool_calls: list[ChatCompletionOutputToolCall] | None = None
245
+
246
+
247
+ @dataclass_with_extra
248
+ class ChatCompletionOutputComplete(BaseInferenceType):
249
+ finish_reason: str
250
+ index: int
251
+ message: ChatCompletionOutputMessage
252
+ logprobs: ChatCompletionOutputLogprobs | None = None
253
+
254
+
255
+ @dataclass_with_extra
256
+ class ChatCompletionOutputUsage(BaseInferenceType):
257
+ completion_tokens: int
258
+ prompt_tokens: int
259
+ total_tokens: int
260
+
261
+
262
+ @dataclass_with_extra
263
+ class ChatCompletionOutput(BaseInferenceType):
264
+ """Chat Completion Output.
265
+ Auto-generated from TGI specs.
266
+ For more details, check out
267
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
268
+ """
269
+
270
+ choices: list[ChatCompletionOutputComplete]
271
+ created: int
272
+ id: str
273
+ model: str
274
+ system_fingerprint: str
275
+ usage: ChatCompletionOutputUsage
276
+
277
+
278
+ @dataclass_with_extra
279
+ class ChatCompletionStreamOutputFunction(BaseInferenceType):
280
+ arguments: str
281
+ name: str | None = None
282
+
283
+
284
+ @dataclass_with_extra
285
+ class ChatCompletionStreamOutputDeltaToolCall(BaseInferenceType):
286
+ function: ChatCompletionStreamOutputFunction
287
+ id: str
288
+ index: int
289
+ type: str
290
+
291
+
292
+ @dataclass_with_extra
293
+ class ChatCompletionStreamOutputDelta(BaseInferenceType):
294
+ role: str
295
+ content: str | None = None
296
+ reasoning: str | None = None
297
+ tool_call_id: str | None = None
298
+ tool_calls: list[ChatCompletionStreamOutputDeltaToolCall] | None = None
299
+
300
+
301
+ @dataclass_with_extra
302
+ class ChatCompletionStreamOutputTopLogprob(BaseInferenceType):
303
+ logprob: float
304
+ token: str
305
+
306
+
307
+ @dataclass_with_extra
308
+ class ChatCompletionStreamOutputLogprob(BaseInferenceType):
309
+ logprob: float
310
+ token: str
311
+ top_logprobs: list[ChatCompletionStreamOutputTopLogprob]
312
+
313
+
314
+ @dataclass_with_extra
315
+ class ChatCompletionStreamOutputLogprobs(BaseInferenceType):
316
+ content: list[ChatCompletionStreamOutputLogprob]
317
+
318
+
319
+ @dataclass_with_extra
320
+ class ChatCompletionStreamOutputChoice(BaseInferenceType):
321
+ delta: ChatCompletionStreamOutputDelta
322
+ index: int
323
+ finish_reason: str | None = None
324
+ logprobs: ChatCompletionStreamOutputLogprobs | None = None
325
+
326
+
327
+ @dataclass_with_extra
328
+ class ChatCompletionStreamOutputUsage(BaseInferenceType):
329
+ completion_tokens: int
330
+ prompt_tokens: int
331
+ total_tokens: int
332
+
333
+
334
+ @dataclass_with_extra
335
+ class ChatCompletionStreamOutput(BaseInferenceType):
336
+ """Chat Completion Stream Output.
337
+ Auto-generated from TGI specs.
338
+ For more details, check out
339
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
340
+ """
341
+
342
+ choices: list[ChatCompletionStreamOutputChoice]
343
+ created: int
344
+ id: str
345
+ model: str
346
+ system_fingerprint: str
347
+ usage: ChatCompletionStreamOutputUsage | None = None
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/depth_estimation.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class DepthEstimationInput(BaseInferenceType):
13
+ """Inputs for Depth Estimation inference"""
14
+
15
+ inputs: Any
16
+ """The input image data"""
17
+ parameters: dict[str, Any] | None = None
18
+ """Additional inference parameters for Depth Estimation"""
19
+
20
+
21
+ @dataclass_with_extra
22
+ class DepthEstimationOutput(BaseInferenceType):
23
+ """Outputs of inference for the Depth Estimation task"""
24
+
25
+ depth: Any
26
+ """The predicted depth as an image"""
27
+ predicted_depth: Any
28
+ """The predicted depth as a tensor"""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/document_question_answering.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class DocumentQuestionAnsweringInputData(BaseInferenceType):
13
+ """One (document, question) pair to answer"""
14
+
15
+ image: Any
16
+ """The image on which the question is asked"""
17
+ question: str
18
+ """A question to ask of the document"""
19
+
20
+
21
+ @dataclass_with_extra
22
+ class DocumentQuestionAnsweringParameters(BaseInferenceType):
23
+ """Additional inference parameters for Document Question Answering"""
24
+
25
+ doc_stride: int | None = None
26
+ """If the words in the document are too long to fit with the question for the model, it will
27
+ be split in several chunks with some overlap. This argument controls the size of that
28
+ overlap.
29
+ """
30
+ handle_impossible_answer: bool | None = None
31
+ """Whether to accept impossible as an answer"""
32
+ lang: str | None = None
33
+ """Language to use while running OCR. Defaults to english."""
34
+ max_answer_len: int | None = None
35
+ """The maximum length of predicted answers (e.g., only answers with a shorter length are
36
+ considered).
37
+ """
38
+ max_question_len: int | None = None
39
+ """The maximum length of the question after tokenization. It will be truncated if needed."""
40
+ max_seq_len: int | None = None
41
+ """The maximum length of the total sentence (context + question) in tokens of each chunk
42
+ passed to the model. The context will be split in several chunks (using doc_stride as
43
+ overlap) if needed.
44
+ """
45
+ top_k: int | None = None
46
+ """The number of answers to return (will be chosen by order of likelihood). Can return less
47
+ than top_k answers if there are not enough options available within the context.
48
+ """
49
+ word_boxes: list[list[float] | str] | None = None
50
+ """A list of words and bounding boxes (normalized 0->1000). If provided, the inference will
51
+ skip the OCR step and use the provided bounding boxes instead.
52
+ """
53
+
54
+
55
+ @dataclass_with_extra
56
+ class DocumentQuestionAnsweringInput(BaseInferenceType):
57
+ """Inputs for Document Question Answering inference"""
58
+
59
+ inputs: DocumentQuestionAnsweringInputData
60
+ """One (document, question) pair to answer"""
61
+ parameters: DocumentQuestionAnsweringParameters | None = None
62
+ """Additional inference parameters for Document Question Answering"""
63
+
64
+
65
+ @dataclass_with_extra
66
+ class DocumentQuestionAnsweringOutputElement(BaseInferenceType):
67
+ """Outputs of inference for the Document Question Answering task"""
68
+
69
+ answer: str
70
+ """The answer to the question."""
71
+ end: int
72
+ """The end word index of the answer (in the OCR’d version of the input or provided word
73
+ boxes).
74
+ """
75
+ score: float
76
+ """The probability associated to the answer."""
77
+ start: int
78
+ """The start word index of the answer (in the OCR’d version of the input or provided word
79
+ boxes).
80
+ """
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/feature_extraction.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ FeatureExtractionInputTruncationDirection = Literal["left", "right"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class FeatureExtractionInput(BaseInferenceType):
16
+ """Feature Extraction Input.
17
+ Auto-generated from TEI specs.
18
+ For more details, check out
19
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tei-import.ts.
20
+ """
21
+
22
+ inputs: list[str] | str
23
+ """The text or list of texts to embed."""
24
+ normalize: bool | None = None
25
+ prompt_name: str | None = None
26
+ """The name of the prompt that should be used by for encoding. If not set, no prompt
27
+ will be applied.
28
+ Must be a key in the `sentence-transformers` configuration `prompts` dictionary.
29
+ For example if ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ",
30
+ ...},
31
+ then the sentence "What is the capital of France?" will be encoded as
32
+ "query: What is the capital of France?" because the prompt text will be prepended before
33
+ any text to encode.
34
+ """
35
+ truncate: bool | None = None
36
+ truncation_direction: Optional["FeatureExtractionInputTruncationDirection"] = None
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/fill_mask.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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class FillMaskParameters(BaseInferenceType):
13
+ """Additional inference parameters for Fill Mask"""
14
+
15
+ targets: list[str] | None = None
16
+ """When passed, the model will limit the scores to the passed targets instead of looking up
17
+ in the whole vocabulary. If the provided targets are not in the model vocab, they will be
18
+ tokenized and the first resulting token will be used (with a warning, and that might be
19
+ slower).
20
+ """
21
+ top_k: int | None = None
22
+ """When passed, overrides the number of predictions to return."""
23
+
24
+
25
+ @dataclass_with_extra
26
+ class FillMaskInput(BaseInferenceType):
27
+ """Inputs for Fill Mask inference"""
28
+
29
+ inputs: str
30
+ """The text with masked tokens"""
31
+ parameters: FillMaskParameters | None = None
32
+ """Additional inference parameters for Fill Mask"""
33
+
34
+
35
+ @dataclass_with_extra
36
+ class FillMaskOutputElement(BaseInferenceType):
37
+ """Outputs of inference for the Fill Mask task"""
38
+
39
+ score: float
40
+ """The corresponding probability"""
41
+ sequence: str
42
+ """The corresponding input with the mask token prediction."""
43
+ token: int
44
+ """The predicted token id (to replace the masked one)."""
45
+ token_str: Any
46
+ fill_mask_output_token_str: str | None = None
47
+ """The predicted token (to replace the masked one)."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_classification.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ ImageClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class ImageClassificationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Image Classification"""
17
+
18
+ function_to_apply: Optional["ImageClassificationOutputTransform"] = None
19
+ """The function to apply to the model outputs in order to retrieve the scores."""
20
+ top_k: int | None = None
21
+ """When specified, limits the output to the top K most probable classes."""
22
+
23
+
24
+ @dataclass_with_extra
25
+ class ImageClassificationInput(BaseInferenceType):
26
+ """Inputs for Image Classification inference"""
27
+
28
+ inputs: str
29
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
30
+ also provide the image data as a raw bytes payload.
31
+ """
32
+ parameters: ImageClassificationParameters | None = None
33
+ """Additional inference parameters for Image Classification"""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class ImageClassificationOutputElement(BaseInferenceType):
38
+ """Outputs of inference for the Image Classification task"""
39
+
40
+ label: str
41
+ """The predicted class label."""
42
+ score: float
43
+ """The corresponding probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_segmentation.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ ImageSegmentationSubtask = Literal["instance", "panoptic", "semantic"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class ImageSegmentationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Image Segmentation"""
17
+
18
+ mask_threshold: float | None = None
19
+ """Threshold to use when turning the predicted masks into binary values."""
20
+ overlap_mask_area_threshold: float | None = None
21
+ """Mask overlap threshold to eliminate small, disconnected segments."""
22
+ subtask: Optional["ImageSegmentationSubtask"] = None
23
+ """Segmentation task to be performed, depending on model capabilities."""
24
+ threshold: float | None = None
25
+ """Probability threshold to filter out predicted masks."""
26
+
27
+
28
+ @dataclass_with_extra
29
+ class ImageSegmentationInput(BaseInferenceType):
30
+ """Inputs for Image Segmentation inference"""
31
+
32
+ inputs: str
33
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
34
+ also provide the image data as a raw bytes payload.
35
+ """
36
+ parameters: ImageSegmentationParameters | None = None
37
+ """Additional inference parameters for Image Segmentation"""
38
+
39
+
40
+ @dataclass_with_extra
41
+ class ImageSegmentationOutputElement(BaseInferenceType):
42
+ """Outputs of inference for the Image Segmentation task
43
+ A predicted mask / segment
44
+ """
45
+
46
+ label: str
47
+ """The label of the predicted segment."""
48
+ mask: str
49
+ """The corresponding mask as a black-and-white image (base64-encoded)."""
50
+ score: float | None = None
51
+ """The score or confidence degree the model has."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_text_to_image.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class ImageTextToImageTargetSize(BaseInferenceType):
13
+ """The size in pixels of the output image. This parameter is only supported by some
14
+ providers and for specific models. It will be ignored when unsupported.
15
+ """
16
+
17
+ height: int
18
+ width: int
19
+
20
+
21
+ @dataclass_with_extra
22
+ class ImageTextToImageParameters(BaseInferenceType):
23
+ """Additional inference parameters for Image Text To Image"""
24
+
25
+ guidance_scale: float | None = None
26
+ """For diffusion models. A higher guidance scale value encourages the model to generate
27
+ images closely linked to the text prompt at the expense of lower image quality.
28
+ """
29
+ negative_prompt: str | None = None
30
+ """One prompt to guide what NOT to include in image generation."""
31
+ num_inference_steps: int | None = None
32
+ """For diffusion models. The number of denoising steps. More denoising steps usually lead to
33
+ a higher quality image at the expense of slower inference.
34
+ """
35
+ prompt: str | None = None
36
+ """The text prompt to guide the image generation. Either this or inputs (image) must be
37
+ provided.
38
+ """
39
+ seed: int | None = None
40
+ """Seed for the random number generator."""
41
+ target_size: ImageTextToImageTargetSize | None = None
42
+ """The size in pixels of the output image. This parameter is only supported by some
43
+ providers and for specific models. It will be ignored when unsupported.
44
+ """
45
+
46
+
47
+ @dataclass_with_extra
48
+ class ImageTextToImageInput(BaseInferenceType):
49
+ """Inputs for Image Text To Image inference. Either inputs (image) or prompt (in parameters)
50
+ must be provided, or both.
51
+ """
52
+
53
+ inputs: str | None = None
54
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
55
+ also provide the image data as a raw bytes payload. Either this or prompt must be
56
+ provided.
57
+ """
58
+ parameters: ImageTextToImageParameters | None = None
59
+ """Additional inference parameters for Image Text To Image"""
60
+
61
+
62
+ @dataclass_with_extra
63
+ class ImageTextToImageOutput(BaseInferenceType):
64
+ """Outputs of inference for the Image Text To Image task"""
65
+
66
+ image: Any
67
+ """The generated image returned as raw bytes in the payload."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_text_to_video.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class ImageTextToVideoTargetSize(BaseInferenceType):
13
+ """The size in pixel of the output video frames."""
14
+
15
+ height: int
16
+ width: int
17
+
18
+
19
+ @dataclass_with_extra
20
+ class ImageTextToVideoParameters(BaseInferenceType):
21
+ """Additional inference parameters for Image Text To Video"""
22
+
23
+ guidance_scale: float | None = None
24
+ """For diffusion models. A higher guidance scale value encourages the model to generate
25
+ videos closely linked to the text prompt at the expense of lower image quality.
26
+ """
27
+ negative_prompt: str | None = None
28
+ """One prompt to guide what NOT to include in video generation."""
29
+ num_frames: float | None = None
30
+ """The num_frames parameter determines how many video frames are generated."""
31
+ num_inference_steps: int | None = None
32
+ """The number of denoising steps. More denoising steps usually lead to a higher quality
33
+ video at the expense of slower inference.
34
+ """
35
+ prompt: str | None = None
36
+ """The text prompt to guide the video generation. Either this or inputs (image) must be
37
+ provided.
38
+ """
39
+ seed: int | None = None
40
+ """Seed for the random number generator."""
41
+ target_size: ImageTextToVideoTargetSize | None = None
42
+ """The size in pixel of the output video frames."""
43
+
44
+
45
+ @dataclass_with_extra
46
+ class ImageTextToVideoInput(BaseInferenceType):
47
+ """Inputs for Image Text To Video inference. Either inputs (image) or prompt (in parameters)
48
+ must be provided, or both.
49
+ """
50
+
51
+ inputs: str | None = None
52
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
53
+ also provide the image data as a raw bytes payload. Either this or prompt must be
54
+ provided.
55
+ """
56
+ parameters: ImageTextToVideoParameters | None = None
57
+ """Additional inference parameters for Image Text To Video"""
58
+
59
+
60
+ @dataclass_with_extra
61
+ class ImageTextToVideoOutput(BaseInferenceType):
62
+ """Outputs of inference for the Image Text To Video task"""
63
+
64
+ video: Any
65
+ """The generated video returned as raw bytes in the payload."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_to_image.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class ImageToImageTargetSize(BaseInferenceType):
13
+ """The size in pixels of the output image. This parameter is only supported by some
14
+ providers and for specific models. It will be ignored when unsupported.
15
+ """
16
+
17
+ height: int
18
+ width: int
19
+
20
+
21
+ @dataclass_with_extra
22
+ class ImageToImageParameters(BaseInferenceType):
23
+ """Additional inference parameters for Image To Image"""
24
+
25
+ guidance_scale: float | None = None
26
+ """For diffusion models. A higher guidance scale value encourages the model to generate
27
+ images closely linked to the text prompt at the expense of lower image quality.
28
+ """
29
+ negative_prompt: str | None = None
30
+ """One prompt to guide what NOT to include in image generation."""
31
+ num_inference_steps: int | None = None
32
+ """For diffusion models. The number of denoising steps. More denoising steps usually lead to
33
+ a higher quality image at the expense of slower inference.
34
+ """
35
+ prompt: str | None = None
36
+ """The text prompt to guide the image generation."""
37
+ target_size: ImageToImageTargetSize | None = None
38
+ """The size in pixels of the output image. This parameter is only supported by some
39
+ providers and for specific models. It will be ignored when unsupported.
40
+ """
41
+
42
+
43
+ @dataclass_with_extra
44
+ class ImageToImageInput(BaseInferenceType):
45
+ """Inputs for Image To Image inference"""
46
+
47
+ inputs: str
48
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
49
+ also provide the image data as a raw bytes payload.
50
+ """
51
+ parameters: ImageToImageParameters | None = None
52
+ """Additional inference parameters for Image To Image"""
53
+
54
+
55
+ @dataclass_with_extra
56
+ class ImageToImageOutput(BaseInferenceType):
57
+ """Outputs of inference for the Image To Image task"""
58
+
59
+ image: Any
60
+ """The output image returned as raw bytes in the payload."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_to_text.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Union
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ ImageToTextEarlyStoppingEnum = Literal["never"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class ImageToTextGenerationParameters(BaseInferenceType):
16
+ """Parametrization of the text generation process"""
17
+
18
+ do_sample: bool | None = None
19
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
20
+ early_stopping: Union[bool, "ImageToTextEarlyStoppingEnum"] | None = None
21
+ """Controls the stopping condition for beam-based methods."""
22
+ epsilon_cutoff: float | None = None
23
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
24
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
25
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
26
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
27
+ """
28
+ eta_cutoff: float | None = None
29
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
30
+ float strictly between 0 and 1, a token is only considered if it is greater than either
31
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
32
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
33
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
34
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
35
+ for more details.
36
+ """
37
+ max_length: int | None = None
38
+ """The maximum length (in tokens) of the generated text, including the input."""
39
+ max_new_tokens: int | None = None
40
+ """The maximum number of tokens to generate. Takes precedence over max_length."""
41
+ min_length: int | None = None
42
+ """The minimum length (in tokens) of the generated text, including the input."""
43
+ min_new_tokens: int | None = None
44
+ """The minimum number of tokens to generate. Takes precedence over min_length."""
45
+ num_beam_groups: int | None = None
46
+ """Number of groups to divide num_beams into in order to ensure diversity among different
47
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
48
+ """
49
+ num_beams: int | None = None
50
+ """Number of beams to use for beam search."""
51
+ penalty_alpha: float | None = None
52
+ """The value balances the model confidence and the degeneration penalty in contrastive
53
+ search decoding.
54
+ """
55
+ temperature: float | None = None
56
+ """The value used to modulate the next token probabilities."""
57
+ top_k: int | None = None
58
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
59
+ top_p: float | None = None
60
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
61
+ that add up to top_p or higher are kept for generation.
62
+ """
63
+ typical_p: float | None = None
64
+ """Local typicality measures how similar the conditional probability of predicting a target
65
+ token next is to the expected conditional probability of predicting a random token next,
66
+ given the partial text already generated. If set to float < 1, the smallest set of the
67
+ most locally typical tokens with probabilities that add up to typical_p or higher are
68
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
69
+ """
70
+ use_cache: bool | None = None
71
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
72
+
73
+
74
+ @dataclass_with_extra
75
+ class ImageToTextParameters(BaseInferenceType):
76
+ """Additional inference parameters for Image To Text"""
77
+
78
+ generation_parameters: ImageToTextGenerationParameters | None = None
79
+ """Parametrization of the text generation process"""
80
+ max_new_tokens: int | None = None
81
+ """The amount of maximum tokens to generate."""
82
+
83
+
84
+ @dataclass_with_extra
85
+ class ImageToTextInput(BaseInferenceType):
86
+ """Inputs for Image To Text inference"""
87
+
88
+ inputs: Any
89
+ """The input image data"""
90
+ parameters: ImageToTextParameters | None = None
91
+ """Additional inference parameters for Image To Text"""
92
+
93
+
94
+ @dataclass_with_extra
95
+ class ImageToTextOutput(BaseInferenceType):
96
+ """Outputs of inference for the Image To Text task"""
97
+
98
+ generated_text: Any
99
+ image_to_text_output_generated_text: str | None = None
100
+ """The generated text."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/image_to_video.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class ImageToVideoTargetSize(BaseInferenceType):
13
+ """The size in pixel of the output video frames."""
14
+
15
+ height: int
16
+ width: int
17
+
18
+
19
+ @dataclass_with_extra
20
+ class ImageToVideoParameters(BaseInferenceType):
21
+ """Additional inference parameters for Image To Video"""
22
+
23
+ guidance_scale: float | None = None
24
+ """For diffusion models. A higher guidance scale value encourages the model to generate
25
+ videos closely linked to the text prompt at the expense of lower image quality.
26
+ """
27
+ negative_prompt: str | None = None
28
+ """One prompt to guide what NOT to include in video generation."""
29
+ num_frames: float | None = None
30
+ """The num_frames parameter determines how many video frames are generated."""
31
+ num_inference_steps: int | None = None
32
+ """The number of denoising steps. More denoising steps usually lead to a higher quality
33
+ video at the expense of slower inference.
34
+ """
35
+ prompt: str | None = None
36
+ """The text prompt to guide the video generation."""
37
+ seed: int | None = None
38
+ """Seed for the random number generator."""
39
+ target_size: ImageToVideoTargetSize | None = None
40
+ """The size in pixel of the output video frames."""
41
+
42
+
43
+ @dataclass_with_extra
44
+ class ImageToVideoInput(BaseInferenceType):
45
+ """Inputs for Image To Video inference"""
46
+
47
+ inputs: str
48
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
49
+ also provide the image data as a raw bytes payload.
50
+ """
51
+ parameters: ImageToVideoParameters | None = None
52
+ """Additional inference parameters for Image To Video"""
53
+
54
+
55
+ @dataclass_with_extra
56
+ class ImageToVideoOutput(BaseInferenceType):
57
+ """Outputs of inference for the Image To Video task"""
58
+
59
+ video: Any
60
+ """The generated video returned as raw bytes in the payload."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/object_detection.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 .base import BaseInferenceType, dataclass_with_extra
7
+
8
+
9
+ @dataclass_with_extra
10
+ class ObjectDetectionParameters(BaseInferenceType):
11
+ """Additional inference parameters for Object Detection"""
12
+
13
+ threshold: float | None = None
14
+ """The probability necessary to make a prediction."""
15
+
16
+
17
+ @dataclass_with_extra
18
+ class ObjectDetectionInput(BaseInferenceType):
19
+ """Inputs for Object Detection inference"""
20
+
21
+ inputs: str
22
+ """The input image data as a base64-encoded string. If no `parameters` are provided, you can
23
+ also provide the image data as a raw bytes payload.
24
+ """
25
+ parameters: ObjectDetectionParameters | None = None
26
+ """Additional inference parameters for Object Detection"""
27
+
28
+
29
+ @dataclass_with_extra
30
+ class ObjectDetectionBoundingBox(BaseInferenceType):
31
+ """The predicted bounding box. Coordinates are relative to the top left corner of the input
32
+ image.
33
+ """
34
+
35
+ xmax: int
36
+ """The x-coordinate of the bottom-right corner of the bounding box."""
37
+ xmin: int
38
+ """The x-coordinate of the top-left corner of the bounding box."""
39
+ ymax: int
40
+ """The y-coordinate of the bottom-right corner of the bounding box."""
41
+ ymin: int
42
+ """The y-coordinate of the top-left corner of the bounding box."""
43
+
44
+
45
+ @dataclass_with_extra
46
+ class ObjectDetectionOutputElement(BaseInferenceType):
47
+ """Outputs of inference for the Object Detection task"""
48
+
49
+ box: ObjectDetectionBoundingBox
50
+ """The predicted bounding box. Coordinates are relative to the top left corner of the input
51
+ image.
52
+ """
53
+ label: str
54
+ """The predicted label for the bounding box."""
55
+ score: float
56
+ """The associated score / probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/question_answering.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .base import BaseInferenceType, dataclass_with_extra
7
+
8
+
9
+ @dataclass_with_extra
10
+ class QuestionAnsweringInputData(BaseInferenceType):
11
+ """One (context, question) pair to answer"""
12
+
13
+ context: str
14
+ """The context to be used for answering the question"""
15
+ question: str
16
+ """The question to be answered"""
17
+
18
+
19
+ @dataclass_with_extra
20
+ class QuestionAnsweringParameters(BaseInferenceType):
21
+ """Additional inference parameters for Question Answering"""
22
+
23
+ align_to_words: bool | None = None
24
+ """Attempts to align the answer to real words. Improves quality on space separated
25
+ languages. Might hurt on non-space-separated languages (like Japanese or Chinese)
26
+ """
27
+ doc_stride: int | None = None
28
+ """If the context is too long to fit with the question for the model, it will be split in
29
+ several chunks with some overlap. This argument controls the size of that overlap.
30
+ """
31
+ handle_impossible_answer: bool | None = None
32
+ """Whether to accept impossible as an answer."""
33
+ max_answer_len: int | None = None
34
+ """The maximum length of predicted answers (e.g., only answers with a shorter length are
35
+ considered).
36
+ """
37
+ max_question_len: int | None = None
38
+ """The maximum length of the question after tokenization. It will be truncated if needed."""
39
+ max_seq_len: int | None = None
40
+ """The maximum length of the total sentence (context + question) in tokens of each chunk
41
+ passed to the model. The context will be split in several chunks (using docStride as
42
+ overlap) if needed.
43
+ """
44
+ top_k: int | None = None
45
+ """The number of answers to return (will be chosen by order of likelihood). Note that we
46
+ return less than topk answers if there are not enough options available within the
47
+ context.
48
+ """
49
+
50
+
51
+ @dataclass_with_extra
52
+ class QuestionAnsweringInput(BaseInferenceType):
53
+ """Inputs for Question Answering inference"""
54
+
55
+ inputs: QuestionAnsweringInputData
56
+ """One (context, question) pair to answer"""
57
+ parameters: QuestionAnsweringParameters | None = None
58
+ """Additional inference parameters for Question Answering"""
59
+
60
+
61
+ @dataclass_with_extra
62
+ class QuestionAnsweringOutputElement(BaseInferenceType):
63
+ """Outputs of inference for the Question Answering task"""
64
+
65
+ answer: str
66
+ """The answer to the question."""
67
+ end: int
68
+ """The character position in the input where the answer ends."""
69
+ score: float
70
+ """The probability associated to the answer."""
71
+ start: int
72
+ """The character position in the input where the answer begins."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/sentence_similarity.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class SentenceSimilarityInputData(BaseInferenceType):
13
+ sentences: list[str]
14
+ """A list of strings which will be compared against the source_sentence."""
15
+ source_sentence: str
16
+ """The string that you wish to compare the other strings with. This can be a phrase,
17
+ sentence, or longer passage, depending on the model being used.
18
+ """
19
+
20
+
21
+ @dataclass_with_extra
22
+ class SentenceSimilarityInput(BaseInferenceType):
23
+ """Inputs for Sentence similarity inference"""
24
+
25
+ inputs: SentenceSimilarityInputData
26
+ parameters: dict[str, Any] | None = None
27
+ """Additional inference parameters for Sentence Similarity"""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/summarization.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ SummarizationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class SummarizationParameters(BaseInferenceType):
16
+ """Additional inference parameters for summarization."""
17
+
18
+ clean_up_tokenization_spaces: bool | None = None
19
+ """Whether to clean up the potential extra spaces in the text output."""
20
+ generate_parameters: dict[str, Any] | None = None
21
+ """Additional parametrization of the text generation algorithm."""
22
+ truncation: Optional["SummarizationTruncationStrategy"] = None
23
+ """The truncation strategy to use."""
24
+
25
+
26
+ @dataclass_with_extra
27
+ class SummarizationInput(BaseInferenceType):
28
+ """Inputs for Summarization inference"""
29
+
30
+ inputs: str
31
+ """The input text to summarize."""
32
+ parameters: SummarizationParameters | None = None
33
+ """Additional inference parameters for summarization."""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class SummarizationOutput(BaseInferenceType):
38
+ """Outputs of inference for the Summarization task"""
39
+
40
+ summary_text: str
41
+ """The summarized text."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/table_question_answering.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class TableQuestionAnsweringInputData(BaseInferenceType):
13
+ """One (table, question) pair to answer"""
14
+
15
+ question: str
16
+ """The question to be answered about the table"""
17
+ table: dict[str, list[str]]
18
+ """The table to serve as context for the questions"""
19
+
20
+
21
+ Padding = Literal["do_not_pad", "longest", "max_length"]
22
+
23
+
24
+ @dataclass_with_extra
25
+ class TableQuestionAnsweringParameters(BaseInferenceType):
26
+ """Additional inference parameters for Table Question Answering"""
27
+
28
+ padding: Optional["Padding"] = None
29
+ """Activates and controls padding."""
30
+ sequential: bool | None = None
31
+ """Whether to do inference sequentially or as a batch. Batching is faster, but models like
32
+ SQA require the inference to be done sequentially to extract relations within sequences,
33
+ given their conversational nature.
34
+ """
35
+ truncation: bool | None = None
36
+ """Activates and controls truncation."""
37
+
38
+
39
+ @dataclass_with_extra
40
+ class TableQuestionAnsweringInput(BaseInferenceType):
41
+ """Inputs for Table Question Answering inference"""
42
+
43
+ inputs: TableQuestionAnsweringInputData
44
+ """One (table, question) pair to answer"""
45
+ parameters: TableQuestionAnsweringParameters | None = None
46
+ """Additional inference parameters for Table Question Answering"""
47
+
48
+
49
+ @dataclass_with_extra
50
+ class TableQuestionAnsweringOutputElement(BaseInferenceType):
51
+ """Outputs of inference for the Table Question Answering task"""
52
+
53
+ answer: str
54
+ """The answer of the question given the table. If there is an aggregator, the answer will be
55
+ preceded by `AGGREGATOR >`.
56
+ """
57
+ cells: list[str]
58
+ """list of strings made up of the answer cell values."""
59
+ coordinates: list[list[int]]
60
+ """Coordinates of the cells of the answers."""
61
+ aggregator: str | None = None
62
+ """If the model has an aggregator, this returns the aggregator."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text2text_generation.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ Text2TextGenerationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class Text2TextGenerationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Text2text Generation"""
17
+
18
+ clean_up_tokenization_spaces: bool | None = None
19
+ """Whether to clean up the potential extra spaces in the text output."""
20
+ generate_parameters: dict[str, Any] | None = None
21
+ """Additional parametrization of the text generation algorithm"""
22
+ truncation: Optional["Text2TextGenerationTruncationStrategy"] = None
23
+ """The truncation strategy to use"""
24
+
25
+
26
+ @dataclass_with_extra
27
+ class Text2TextGenerationInput(BaseInferenceType):
28
+ """Inputs for Text2text Generation inference"""
29
+
30
+ inputs: str
31
+ """The input text data"""
32
+ parameters: Text2TextGenerationParameters | None = None
33
+ """Additional inference parameters for Text2text Generation"""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class Text2TextGenerationOutput(BaseInferenceType):
38
+ """Outputs of inference for the Text2text Generation task"""
39
+
40
+ generated_text: Any
41
+ text2_text_generation_output_generated_text: str | None = None
42
+ """The generated text."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_classification.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ TextClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class TextClassificationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Text Classification"""
17
+
18
+ function_to_apply: Optional["TextClassificationOutputTransform"] = None
19
+ """The function to apply to the model outputs in order to retrieve the scores."""
20
+ top_k: int | None = None
21
+ """When specified, limits the output to the top K most probable classes."""
22
+
23
+
24
+ @dataclass_with_extra
25
+ class TextClassificationInput(BaseInferenceType):
26
+ """Inputs for Text Classification inference"""
27
+
28
+ inputs: str
29
+ """The text to classify"""
30
+ parameters: TextClassificationParameters | None = None
31
+ """Additional inference parameters for Text Classification"""
32
+
33
+
34
+ @dataclass_with_extra
35
+ class TextClassificationOutputElement(BaseInferenceType):
36
+ """Outputs of inference for the Text Classification task"""
37
+
38
+ label: str
39
+ """The predicted class label."""
40
+ score: float
41
+ """The corresponding probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_generation.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ TypeEnum = Literal["json", "regex", "json_schema"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class TextGenerationInputGrammarType(BaseInferenceType):
16
+ type: "TypeEnum"
17
+ value: Any
18
+ """A string that represents a [JSON Schema](https://json-schema.org/).
19
+ JSON Schema is a declarative language that allows to annotate JSON documents
20
+ with types and descriptions.
21
+ """
22
+
23
+
24
+ @dataclass_with_extra
25
+ class TextGenerationInputGenerateParameters(BaseInferenceType):
26
+ adapter_id: str | None = None
27
+ """Lora adapter id"""
28
+ best_of: int | None = None
29
+ """Generate best_of sequences and return the one if the highest token logprobs."""
30
+ decoder_input_details: bool | None = None
31
+ """Whether to return decoder input token logprobs and ids."""
32
+ details: bool | None = None
33
+ """Whether to return generation details."""
34
+ do_sample: bool | None = None
35
+ """Activate logits sampling."""
36
+ frequency_penalty: float | None = None
37
+ """The parameter for frequency penalty. 1.0 means no penalty
38
+ Penalize new tokens based on their existing frequency in the text so far,
39
+ decreasing the model's likelihood to repeat the same line verbatim.
40
+ """
41
+ grammar: TextGenerationInputGrammarType | None = None
42
+ max_new_tokens: int | None = None
43
+ """Maximum number of tokens to generate."""
44
+ repetition_penalty: float | None = None
45
+ """The parameter for repetition penalty. 1.0 means no penalty.
46
+ See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
47
+ """
48
+ return_full_text: bool | None = None
49
+ """Whether to prepend the prompt to the generated text"""
50
+ seed: int | None = None
51
+ """Random sampling seed."""
52
+ stop: list[str] | None = None
53
+ """Stop generating tokens if a member of `stop` is generated."""
54
+ temperature: float | None = None
55
+ """The value used to module the logits distribution."""
56
+ top_k: int | None = None
57
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
58
+ top_n_tokens: int | None = None
59
+ """The number of highest probability vocabulary tokens to keep for top-n-filtering."""
60
+ top_p: float | None = None
61
+ """Top-p value for nucleus sampling."""
62
+ truncate: int | None = None
63
+ """Truncate inputs tokens to the given size."""
64
+ typical_p: float | None = None
65
+ """Typical Decoding mass
66
+ See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666)
67
+ for more information.
68
+ """
69
+ watermark: bool | None = None
70
+ """Watermarking with [A Watermark for Large Language
71
+ Models](https://arxiv.org/abs/2301.10226).
72
+ """
73
+
74
+
75
+ @dataclass_with_extra
76
+ class TextGenerationInput(BaseInferenceType):
77
+ """Text Generation Input.
78
+ Auto-generated from TGI specs.
79
+ For more details, check out
80
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
81
+ """
82
+
83
+ inputs: str
84
+ parameters: TextGenerationInputGenerateParameters | None = None
85
+ stream: bool | None = None
86
+
87
+
88
+ TextGenerationOutputFinishReason = Literal["length", "eos_token", "stop_sequence"]
89
+
90
+
91
+ @dataclass_with_extra
92
+ class TextGenerationOutputPrefillToken(BaseInferenceType):
93
+ id: int
94
+ logprob: float
95
+ text: str
96
+
97
+
98
+ @dataclass_with_extra
99
+ class TextGenerationOutputToken(BaseInferenceType):
100
+ id: int
101
+ logprob: float
102
+ special: bool
103
+ text: str
104
+
105
+
106
+ @dataclass_with_extra
107
+ class TextGenerationOutputBestOfSequence(BaseInferenceType):
108
+ finish_reason: "TextGenerationOutputFinishReason"
109
+ generated_text: str
110
+ generated_tokens: int
111
+ prefill: list[TextGenerationOutputPrefillToken]
112
+ tokens: list[TextGenerationOutputToken]
113
+ seed: int | None = None
114
+ top_tokens: list[list[TextGenerationOutputToken]] | None = None
115
+
116
+
117
+ @dataclass_with_extra
118
+ class TextGenerationOutputDetails(BaseInferenceType):
119
+ finish_reason: "TextGenerationOutputFinishReason"
120
+ generated_tokens: int
121
+ prefill: list[TextGenerationOutputPrefillToken]
122
+ tokens: list[TextGenerationOutputToken]
123
+ best_of_sequences: list[TextGenerationOutputBestOfSequence] | None = None
124
+ seed: int | None = None
125
+ top_tokens: list[list[TextGenerationOutputToken]] | None = None
126
+
127
+
128
+ @dataclass_with_extra
129
+ class TextGenerationOutput(BaseInferenceType):
130
+ """Text Generation Output.
131
+ Auto-generated from TGI specs.
132
+ For more details, check out
133
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
134
+ """
135
+
136
+ generated_text: str
137
+ details: TextGenerationOutputDetails | None = None
138
+
139
+
140
+ @dataclass_with_extra
141
+ class TextGenerationStreamOutputStreamDetails(BaseInferenceType):
142
+ finish_reason: "TextGenerationOutputFinishReason"
143
+ generated_tokens: int
144
+ input_length: int
145
+ seed: int | None = None
146
+
147
+
148
+ @dataclass_with_extra
149
+ class TextGenerationStreamOutputToken(BaseInferenceType):
150
+ id: int
151
+ logprob: float
152
+ special: bool
153
+ text: str
154
+
155
+
156
+ @dataclass_with_extra
157
+ class TextGenerationStreamOutput(BaseInferenceType):
158
+ """Text Generation Stream Output.
159
+ Auto-generated from TGI specs.
160
+ For more details, check out
161
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
162
+ """
163
+
164
+ index: int
165
+ token: TextGenerationStreamOutputToken
166
+ details: TextGenerationStreamOutputStreamDetails | None = None
167
+ generated_text: str | None = None
168
+ top_tokens: list[TextGenerationStreamOutputToken] | None = None
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_audio.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Union
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ TextToAudioEarlyStoppingEnum = Literal["never"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class TextToAudioGenerationParameters(BaseInferenceType):
16
+ """Parametrization of the text generation process"""
17
+
18
+ do_sample: bool | None = None
19
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
20
+ early_stopping: Union[bool, "TextToAudioEarlyStoppingEnum"] | None = None
21
+ """Controls the stopping condition for beam-based methods."""
22
+ epsilon_cutoff: float | None = None
23
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
24
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
25
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
26
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
27
+ """
28
+ eta_cutoff: float | None = None
29
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
30
+ float strictly between 0 and 1, a token is only considered if it is greater than either
31
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
32
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
33
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
34
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
35
+ for more details.
36
+ """
37
+ max_length: int | None = None
38
+ """The maximum length (in tokens) of the generated text, including the input."""
39
+ max_new_tokens: int | None = None
40
+ """The maximum number of tokens to generate. Takes precedence over max_length."""
41
+ min_length: int | None = None
42
+ """The minimum length (in tokens) of the generated text, including the input."""
43
+ min_new_tokens: int | None = None
44
+ """The minimum number of tokens to generate. Takes precedence over min_length."""
45
+ num_beam_groups: int | None = None
46
+ """Number of groups to divide num_beams into in order to ensure diversity among different
47
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
48
+ """
49
+ num_beams: int | None = None
50
+ """Number of beams to use for beam search."""
51
+ penalty_alpha: float | None = None
52
+ """The value balances the model confidence and the degeneration penalty in contrastive
53
+ search decoding.
54
+ """
55
+ temperature: float | None = None
56
+ """The value used to modulate the next token probabilities."""
57
+ top_k: int | None = None
58
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
59
+ top_p: float | None = None
60
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
61
+ that add up to top_p or higher are kept for generation.
62
+ """
63
+ typical_p: float | None = None
64
+ """Local typicality measures how similar the conditional probability of predicting a target
65
+ token next is to the expected conditional probability of predicting a random token next,
66
+ given the partial text already generated. If set to float < 1, the smallest set of the
67
+ most locally typical tokens with probabilities that add up to typical_p or higher are
68
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
69
+ """
70
+ use_cache: bool | None = None
71
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
72
+
73
+
74
+ @dataclass_with_extra
75
+ class TextToAudioParameters(BaseInferenceType):
76
+ """Additional inference parameters for Text To Audio"""
77
+
78
+ generation_parameters: TextToAudioGenerationParameters | None = None
79
+ """Parametrization of the text generation process"""
80
+
81
+
82
+ @dataclass_with_extra
83
+ class TextToAudioInput(BaseInferenceType):
84
+ """Inputs for Text To Audio inference"""
85
+
86
+ inputs: str
87
+ """The input text data"""
88
+ parameters: TextToAudioParameters | None = None
89
+ """Additional inference parameters for Text To Audio"""
90
+
91
+
92
+ @dataclass_with_extra
93
+ class TextToAudioOutput(BaseInferenceType):
94
+ """Outputs of inference for the Text To Audio task"""
95
+
96
+ audio: Any
97
+ """The generated audio waveform."""
98
+ sampling_rate: float
99
+ """The sampling rate of the generated audio waveform."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_image.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class TextToImageParameters(BaseInferenceType):
13
+ """Additional inference parameters for Text To Image"""
14
+
15
+ guidance_scale: float | None = None
16
+ """A higher guidance scale value encourages the model to generate images closely linked to
17
+ the text prompt, but values too high may cause saturation and other artifacts.
18
+ """
19
+ height: int | None = None
20
+ """The height in pixels of the output image"""
21
+ negative_prompt: str | None = None
22
+ """One prompt to guide what NOT to include in image generation."""
23
+ num_inference_steps: int | None = None
24
+ """The number of denoising steps. More denoising steps usually lead to a higher quality
25
+ image at the expense of slower inference.
26
+ """
27
+ scheduler: str | None = None
28
+ """Override the scheduler with a compatible one."""
29
+ seed: int | None = None
30
+ """Seed for the random number generator."""
31
+ width: int | None = None
32
+ """The width in pixels of the output image"""
33
+
34
+
35
+ @dataclass_with_extra
36
+ class TextToImageInput(BaseInferenceType):
37
+ """Inputs for Text To Image inference"""
38
+
39
+ inputs: str
40
+ """The input text data (sometimes called "prompt")"""
41
+ parameters: TextToImageParameters | None = None
42
+ """Additional inference parameters for Text To Image"""
43
+
44
+
45
+ @dataclass_with_extra
46
+ class TextToImageOutput(BaseInferenceType):
47
+ """Outputs of inference for the Text To Image task"""
48
+
49
+ image: Any
50
+ """The generated image returned as raw bytes in the payload."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_speech.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Union
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ TextToSpeechEarlyStoppingEnum = Literal["never"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class TextToSpeechGenerationParameters(BaseInferenceType):
16
+ """Parametrization of the text generation process"""
17
+
18
+ do_sample: bool | None = None
19
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
20
+ early_stopping: Union[bool, "TextToSpeechEarlyStoppingEnum"] | None = None
21
+ """Controls the stopping condition for beam-based methods."""
22
+ epsilon_cutoff: float | None = None
23
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
24
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
25
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
26
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
27
+ """
28
+ eta_cutoff: float | None = None
29
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
30
+ float strictly between 0 and 1, a token is only considered if it is greater than either
31
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
32
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
33
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
34
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
35
+ for more details.
36
+ """
37
+ max_length: int | None = None
38
+ """The maximum length (in tokens) of the generated text, including the input."""
39
+ max_new_tokens: int | None = None
40
+ """The maximum number of tokens to generate. Takes precedence over max_length."""
41
+ min_length: int | None = None
42
+ """The minimum length (in tokens) of the generated text, including the input."""
43
+ min_new_tokens: int | None = None
44
+ """The minimum number of tokens to generate. Takes precedence over min_length."""
45
+ num_beam_groups: int | None = None
46
+ """Number of groups to divide num_beams into in order to ensure diversity among different
47
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
48
+ """
49
+ num_beams: int | None = None
50
+ """Number of beams to use for beam search."""
51
+ penalty_alpha: float | None = None
52
+ """The value balances the model confidence and the degeneration penalty in contrastive
53
+ search decoding.
54
+ """
55
+ temperature: float | None = None
56
+ """The value used to modulate the next token probabilities."""
57
+ top_k: int | None = None
58
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
59
+ top_p: float | None = None
60
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
61
+ that add up to top_p or higher are kept for generation.
62
+ """
63
+ typical_p: float | None = None
64
+ """Local typicality measures how similar the conditional probability of predicting a target
65
+ token next is to the expected conditional probability of predicting a random token next,
66
+ given the partial text already generated. If set to float < 1, the smallest set of the
67
+ most locally typical tokens with probabilities that add up to typical_p or higher are
68
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
69
+ """
70
+ use_cache: bool | None = None
71
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
72
+
73
+
74
+ @dataclass_with_extra
75
+ class TextToSpeechParameters(BaseInferenceType):
76
+ """Additional inference parameters for Text To Speech"""
77
+
78
+ generation_parameters: TextToSpeechGenerationParameters | None = None
79
+ """Parametrization of the text generation process"""
80
+
81
+
82
+ @dataclass_with_extra
83
+ class TextToSpeechInput(BaseInferenceType):
84
+ """Inputs for Text To Speech inference"""
85
+
86
+ inputs: str
87
+ """The input text data"""
88
+ parameters: TextToSpeechParameters | None = None
89
+ """Additional inference parameters for Text To Speech"""
90
+
91
+
92
+ @dataclass_with_extra
93
+ class TextToSpeechOutput(BaseInferenceType):
94
+ """Outputs of inference for the Text To Speech task"""
95
+
96
+ audio: Any
97
+ """The generated audio"""
98
+ sampling_rate: float | None = None
99
+ """The sampling rate of the generated audio waveform."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/text_to_video.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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class TextToVideoParameters(BaseInferenceType):
13
+ """Additional inference parameters for Text To Video"""
14
+
15
+ guidance_scale: float | None = None
16
+ """A higher guidance scale value encourages the model to generate videos closely linked to
17
+ the text prompt, but values too high may cause saturation and other artifacts.
18
+ """
19
+ negative_prompt: list[str] | None = None
20
+ """One or several prompt to guide what NOT to include in video generation."""
21
+ num_frames: float | None = None
22
+ """The num_frames parameter determines how many video frames are generated."""
23
+ num_inference_steps: int | None = None
24
+ """The number of denoising steps. More denoising steps usually lead to a higher quality
25
+ video at the expense of slower inference.
26
+ """
27
+ seed: int | None = None
28
+ """Seed for the random number generator."""
29
+
30
+
31
+ @dataclass_with_extra
32
+ class TextToVideoInput(BaseInferenceType):
33
+ """Inputs for Text To Video inference"""
34
+
35
+ inputs: str
36
+ """The input text data (sometimes called "prompt")"""
37
+ parameters: TextToVideoParameters | None = None
38
+ """Additional inference parameters for Text To Video"""
39
+
40
+
41
+ @dataclass_with_extra
42
+ class TextToVideoOutput(BaseInferenceType):
43
+ """Outputs of inference for the Text To Video task"""
44
+
45
+ video: Any
46
+ """The generated video returned as raw bytes in the payload."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/token_classification.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ TokenClassificationAggregationStrategy = Literal["none", "simple", "first", "average", "max"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class TokenClassificationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Token Classification"""
17
+
18
+ aggregation_strategy: Optional["TokenClassificationAggregationStrategy"] = None
19
+ """The strategy used to fuse tokens based on model predictions"""
20
+ ignore_labels: list[str] | None = None
21
+ """A list of labels to ignore"""
22
+ stride: int | None = None
23
+ """The number of overlapping tokens between chunks when splitting the input text."""
24
+
25
+
26
+ @dataclass_with_extra
27
+ class TokenClassificationInput(BaseInferenceType):
28
+ """Inputs for Token Classification inference"""
29
+
30
+ inputs: str
31
+ """The input text data"""
32
+ parameters: TokenClassificationParameters | None = None
33
+ """Additional inference parameters for Token Classification"""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class TokenClassificationOutputElement(BaseInferenceType):
38
+ """Outputs of inference for the Token Classification task"""
39
+
40
+ end: int
41
+ """The character position in the input where this group ends."""
42
+ score: float
43
+ """The associated score / probability"""
44
+ start: int
45
+ """The character position in the input where this group begins."""
46
+ word: str
47
+ """The corresponding text"""
48
+ entity: str | None = None
49
+ """The predicted label for a single token"""
50
+ entity_group: str | None = None
51
+ """The predicted label for a group of one or more tokens"""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/translation.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any, Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ TranslationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class TranslationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Translation"""
17
+
18
+ clean_up_tokenization_spaces: bool | None = None
19
+ """Whether to clean up the potential extra spaces in the text output."""
20
+ generate_parameters: dict[str, Any] | None = None
21
+ """Additional parametrization of the text generation algorithm."""
22
+ src_lang: str | None = None
23
+ """The source language of the text. Required for models that can translate from multiple
24
+ languages.
25
+ """
26
+ tgt_lang: str | None = None
27
+ """Target language to translate to. Required for models that can translate to multiple
28
+ languages.
29
+ """
30
+ truncation: Optional["TranslationTruncationStrategy"] = None
31
+ """The truncation strategy to use."""
32
+
33
+
34
+ @dataclass_with_extra
35
+ class TranslationInput(BaseInferenceType):
36
+ """Inputs for Translation inference"""
37
+
38
+ inputs: str
39
+ """The text to translate."""
40
+ parameters: TranslationParameters | None = None
41
+ """Additional inference parameters for Translation"""
42
+
43
+
44
+ @dataclass_with_extra
45
+ class TranslationOutput(BaseInferenceType):
46
+ """Outputs of inference for the Translation task"""
47
+
48
+ translation_text: str
49
+ """The translated text."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/video_classification.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 typing import Any, Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ VideoClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class VideoClassificationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Video Classification"""
17
+
18
+ frame_sampling_rate: int | None = None
19
+ """The sampling rate used to select frames from the video."""
20
+ function_to_apply: Optional["VideoClassificationOutputTransform"] = None
21
+ """The function to apply to the model outputs in order to retrieve the scores."""
22
+ num_frames: int | None = None
23
+ """The number of sampled frames to consider for classification."""
24
+ top_k: int | None = None
25
+ """When specified, limits the output to the top K most probable classes."""
26
+
27
+
28
+ @dataclass_with_extra
29
+ class VideoClassificationInput(BaseInferenceType):
30
+ """Inputs for Video Classification inference"""
31
+
32
+ inputs: Any
33
+ """The input video data"""
34
+ parameters: VideoClassificationParameters | None = None
35
+ """Additional inference parameters for Video Classification"""
36
+
37
+
38
+ @dataclass_with_extra
39
+ class VideoClassificationOutputElement(BaseInferenceType):
40
+ """Outputs of inference for the Video Classification task"""
41
+
42
+ label: str
43
+ """The predicted class label."""
44
+ score: float
45
+ """The corresponding probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/visual_question_answering.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Any
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ @dataclass_with_extra
12
+ class VisualQuestionAnsweringInputData(BaseInferenceType):
13
+ """One (image, question) pair to answer"""
14
+
15
+ image: Any
16
+ """The image."""
17
+ question: str
18
+ """The question to answer based on the image."""
19
+
20
+
21
+ @dataclass_with_extra
22
+ class VisualQuestionAnsweringParameters(BaseInferenceType):
23
+ """Additional inference parameters for Visual Question Answering"""
24
+
25
+ top_k: int | None = None
26
+ """The number of answers to return (will be chosen by order of likelihood). Note that we
27
+ return less than topk answers if there are not enough options available within the
28
+ context.
29
+ """
30
+
31
+
32
+ @dataclass_with_extra
33
+ class VisualQuestionAnsweringInput(BaseInferenceType):
34
+ """Inputs for Visual Question Answering inference"""
35
+
36
+ inputs: VisualQuestionAnsweringInputData
37
+ """One (image, question) pair to answer"""
38
+ parameters: VisualQuestionAnsweringParameters | None = None
39
+ """Additional inference parameters for Visual Question Answering"""
40
+
41
+
42
+ @dataclass_with_extra
43
+ class VisualQuestionAnsweringOutputElement(BaseInferenceType):
44
+ """Outputs of inference for the Visual Question Answering task"""
45
+
46
+ score: float
47
+ """The associated score / probability"""
48
+ answer: str | None = None
49
+ """The answer to the question"""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/zero_shot_classification.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .base import BaseInferenceType, dataclass_with_extra
7
+
8
+
9
+ @dataclass_with_extra
10
+ class ZeroShotClassificationParameters(BaseInferenceType):
11
+ """Additional inference parameters for Zero Shot Classification"""
12
+
13
+ candidate_labels: list[str]
14
+ """The set of possible class labels to classify the text into."""
15
+ hypothesis_template: str | None = None
16
+ """The sentence used in conjunction with `candidate_labels` to attempt the text
17
+ classification by replacing the placeholder with the candidate labels.
18
+ """
19
+ multi_label: bool | None = None
20
+ """Whether multiple candidate labels can be true. If false, the scores are normalized such
21
+ that the sum of the label likelihoods for each sequence is 1. If true, the labels are
22
+ considered independent and probabilities are normalized for each candidate.
23
+ """
24
+
25
+
26
+ @dataclass_with_extra
27
+ class ZeroShotClassificationInput(BaseInferenceType):
28
+ """Inputs for Zero Shot Classification inference"""
29
+
30
+ inputs: str
31
+ """The text to classify"""
32
+ parameters: ZeroShotClassificationParameters
33
+ """Additional inference parameters for Zero Shot Classification"""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class ZeroShotClassificationOutputElement(BaseInferenceType):
38
+ """Outputs of inference for the Zero Shot Classification task"""
39
+
40
+ label: str
41
+ """The predicted class label."""
42
+ score: float
43
+ """The corresponding probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/zero_shot_image_classification.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .base import BaseInferenceType, dataclass_with_extra
7
+
8
+
9
+ @dataclass_with_extra
10
+ class ZeroShotImageClassificationParameters(BaseInferenceType):
11
+ """Additional inference parameters for Zero Shot Image Classification"""
12
+
13
+ candidate_labels: list[str]
14
+ """The candidate labels for this image"""
15
+ hypothesis_template: str | None = None
16
+ """The sentence used in conjunction with `candidate_labels` to attempt the image
17
+ classification by replacing the placeholder with the candidate labels.
18
+ """
19
+
20
+
21
+ @dataclass_with_extra
22
+ class ZeroShotImageClassificationInput(BaseInferenceType):
23
+ """Inputs for Zero Shot Image Classification inference"""
24
+
25
+ inputs: str
26
+ """The input image data to classify as a base64-encoded string."""
27
+ parameters: ZeroShotImageClassificationParameters
28
+ """Additional inference parameters for Zero Shot Image Classification"""
29
+
30
+
31
+ @dataclass_with_extra
32
+ class ZeroShotImageClassificationOutputElement(BaseInferenceType):
33
+ """Outputs of inference for the Zero Shot Image Classification task"""
34
+
35
+ label: str
36
+ """The predicted class label."""
37
+ score: float
38
+ """The corresponding probability."""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .base import BaseInferenceType, dataclass_with_extra
7
+
8
+
9
+ @dataclass_with_extra
10
+ class ZeroShotObjectDetectionParameters(BaseInferenceType):
11
+ """Additional inference parameters for Zero Shot Object Detection"""
12
+
13
+ candidate_labels: list[str]
14
+ """The candidate labels for this image"""
15
+
16
+
17
+ @dataclass_with_extra
18
+ class ZeroShotObjectDetectionInput(BaseInferenceType):
19
+ """Inputs for Zero Shot Object Detection inference"""
20
+
21
+ inputs: str
22
+ """The input image data as a base64-encoded string."""
23
+ parameters: ZeroShotObjectDetectionParameters
24
+ """Additional inference parameters for Zero Shot Object Detection"""
25
+
26
+
27
+ @dataclass_with_extra
28
+ class ZeroShotObjectDetectionBoundingBox(BaseInferenceType):
29
+ """The predicted bounding box. Coordinates are relative to the top left corner of the input
30
+ image.
31
+ """
32
+
33
+ xmax: int
34
+ xmin: int
35
+ ymax: int
36
+ ymin: int
37
+
38
+
39
+ @dataclass_with_extra
40
+ class ZeroShotObjectDetectionOutputElement(BaseInferenceType):
41
+ """Outputs of inference for the Zero Shot Object Detection task"""
42
+
43
+ box: ZeroShotObjectDetectionBoundingBox
44
+ """The predicted bounding box. Coordinates are relative to the top left corner of the input
45
+ image.
46
+ """
47
+ label: str
48
+ """A candidate label"""
49
+ score: float
50
+ """The associated score / probability"""
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_mcp/__init__.py ADDED
File without changes
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_mcp/_cli_hacks.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from functools import partial
4
+
5
+ import typer
6
+
7
+
8
+ def _patch_anyio_open_process():
9
+ """
10
+ Patch anyio.open_process to allow detached processes on Windows and Unix-like systems.
11
+
12
+ This is necessary to prevent the MCP client from being interrupted by Ctrl+C when running in the CLI.
13
+ """
14
+ import subprocess
15
+
16
+ import anyio
17
+
18
+ if getattr(anyio, "_tiny_agents_patched", False):
19
+ return
20
+ anyio._tiny_agents_patched = True # ty: ignore[invalid-assignment]
21
+
22
+ original_open_process = anyio.open_process
23
+
24
+ if sys.platform == "win32":
25
+ # On Windows, we need to set the creation flags to create a new process group
26
+
27
+ async def open_process_in_new_group(*args, **kwargs):
28
+ """
29
+ Wrapper for open_process to handle Windows-specific process creation flags.
30
+ """
31
+ # Ensure we pass the creation flags for Windows
32
+ kwargs.setdefault("creationflags", subprocess.CREATE_NEW_PROCESS_GROUP)
33
+ return await original_open_process(*args, **kwargs)
34
+
35
+ anyio.open_process = open_process_in_new_group # ty: ignore[invalid-assignment]
36
+ else:
37
+ # For Unix-like systems, we can use setsid to create a new session
38
+ async def open_process_in_new_group(*args, **kwargs):
39
+ """
40
+ Wrapper for open_process to handle Unix-like systems with start_new_session=True.
41
+ """
42
+ kwargs.setdefault("start_new_session", True)
43
+ return await original_open_process(*args, **kwargs)
44
+
45
+ anyio.open_process = open_process_in_new_group # ty: ignore[invalid-assignment]
46
+
47
+
48
+ async def _async_prompt(exit_event: asyncio.Event, prompt: str = "» ") -> str:
49
+ """
50
+ Asynchronous prompt function that reads input from stdin without blocking.
51
+
52
+ This function is designed to work in an asynchronous context, allowing the event loop to gracefully stop it (e.g. on Ctrl+C).
53
+
54
+ Alternatively, we could use https://github.com/vxgmichel/aioconsole but that would be an additional dependency.
55
+ """
56
+ loop = asyncio.get_event_loop()
57
+
58
+ if sys.platform == "win32":
59
+ # Windows: Use run_in_executor to avoid blocking the event loop
60
+ # Degraded solution: this is not ideal as user will have to CTRL+C once more to stop the prompt (and it'll not be graceful)
61
+ return await loop.run_in_executor(None, partial(typer.prompt, prompt, prompt_suffix=" "))
62
+ else:
63
+ # UNIX-like: Use loop.add_reader for non-blocking stdin read
64
+ future = loop.create_future()
65
+
66
+ def on_input():
67
+ line = sys.stdin.readline()
68
+ loop.remove_reader(sys.stdin)
69
+ future.set_result(line)
70
+
71
+ print(prompt, end=" ", flush=True)
72
+ loop.add_reader(sys.stdin, on_input) # not supported on Windows
73
+
74
+ # Wait for user input or exit event
75
+ # Wait until either the user hits enter or exit_event is set
76
+ exit_task = asyncio.create_task(exit_event.wait())
77
+ await asyncio.wait(
78
+ [future, exit_task],
79
+ return_when=asyncio.FIRST_COMPLETED,
80
+ )
81
+
82
+ # Check which one has been triggered
83
+ if exit_event.is_set():
84
+ future.cancel()
85
+ return ""
86
+
87
+ line = await future
88
+ return line.strip()
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/inference/_mcp/agent.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import AsyncGenerator, Iterable, Optional, Union
5
+
6
+ from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient
7
+
8
+ from .._providers import PROVIDER_OR_POLICY_T
9
+ from .constants import DEFAULT_SYSTEM_PROMPT, EXIT_LOOP_TOOLS, MAX_NUM_TURNS
10
+ from .types import ServerConfig
11
+
12
+
13
+ class Agent(MCPClient):
14
+ """
15
+ Implementation of a Simple Agent, which is a simple while loop built right on top of an [`MCPClient`].
16
+
17
+ > [!WARNING]
18
+ > This class is experimental and might be subject to breaking changes in the future without prior notice.
19
+
20
+ Args:
21
+ model (`str`, *optional*):
22
+ The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `meta-llama/Meta-Llama-3-8B-Instruct`
23
+ or a URL to a deployed Inference Endpoint or other local or remote endpoint.
24
+ servers (`Iterable[dict]`):
25
+ MCP servers to connect to. Each server is a dictionary containing a `type` key and a `config` key. The `type` key can be `"stdio"` or `"sse"`, and the `config` key is a dictionary of arguments for the server.
26
+ provider (`str`, *optional*):
27
+ Name of the provider to use for inference. Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers.
28
+ If model is a URL or `base_url` is passed, then `provider` is not used.
29
+ base_url (`str`, *optional*):
30
+ The base URL to run inference. Defaults to None.
31
+ api_key (`str`, *optional*):
32
+ Token to use for authentication. Will default to the locally Hugging Face saved token if not provided. You can also use your own provider API key to interact directly with the provider's service.
33
+ prompt (`str`, *optional*):
34
+ The system prompt to use for the agent. Defaults to the default system prompt in `constants.py`.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ *,
40
+ model: Optional[str] = None,
41
+ servers: Iterable[ServerConfig],
42
+ provider: Optional[PROVIDER_OR_POLICY_T] = None,
43
+ base_url: Optional[str] = None,
44
+ api_key: Optional[str] = None,
45
+ prompt: Optional[str] = None,
46
+ ):
47
+ super().__init__(model=model, provider=provider, base_url=base_url, api_key=api_key)
48
+ self._servers_cfg = list(servers)
49
+ self.messages: list[Union[dict, ChatCompletionInputMessage]] = [
50
+ {"role": "system", "content": prompt or DEFAULT_SYSTEM_PROMPT}
51
+ ]
52
+
53
+ async def load_tools(self) -> None:
54
+ for cfg in self._servers_cfg:
55
+ await self.add_mcp_server(**cfg)
56
+
57
+ async def run(
58
+ self,
59
+ user_input: str,
60
+ *,
61
+ abort_event: Optional[asyncio.Event] = None,
62
+ ) -> AsyncGenerator[Union[ChatCompletionStreamOutput, ChatCompletionInputMessage], None]:
63
+ """
64
+ Run the agent with the given user input.
65
+
66
+ Args:
67
+ user_input (`str`):
68
+ The user input to run the agent with.
69
+ abort_event (`asyncio.Event`, *optional*):
70
+ An event that can be used to abort the agent. If the event is set, the agent will stop running.
71
+ """
72
+ self.messages.append({"role": "user", "content": user_input})
73
+
74
+ num_turns: int = 0
75
+ next_turn_should_call_tools = True
76
+
77
+ while True:
78
+ if abort_event and abort_event.is_set():
79
+ return
80
+
81
+ async for item in self.process_single_turn_with_tools(
82
+ self.messages,
83
+ exit_loop_tools=EXIT_LOOP_TOOLS,
84
+ exit_if_first_chunk_no_tool=(num_turns > 0 and next_turn_should_call_tools),
85
+ ):
86
+ yield item
87
+
88
+ num_turns += 1
89
+ last = self.messages[-1]
90
+
91
+ if last.get("role") == "tool" and last.get("name") in {t.function.name for t in EXIT_LOOP_TOOLS}:
92
+ return
93
+
94
+ if last.get("role") != "tool" and num_turns > MAX_NUM_TURNS:
95
+ return
96
+
97
+ if last.get("role") != "tool" and next_turn_should_call_tools:
98
+ return
99
+
100
+ next_turn_should_call_tools = last.get("role") != "tool"