_common.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # Copyright 2023-present, the HuggingFace Inc. team.
  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 utilities used by both the sync and async inference clients."""
  15. import base64
  16. import io
  17. import json
  18. import logging
  19. import mimetypes
  20. from collections.abc import AsyncIterable, Iterable
  21. from dataclasses import dataclass
  22. from pathlib import Path
  23. from typing import TYPE_CHECKING, Any, BinaryIO, Literal, NoReturn, Union, overload
  24. import httpx
  25. from huggingface_hub.errors import (
  26. GenerationError,
  27. HfHubHTTPError,
  28. IncompleteGenerationError,
  29. OverloadedError,
  30. TextGenerationError,
  31. UnknownError,
  32. ValidationError,
  33. )
  34. from ..utils import get_session, is_numpy_available, is_pillow_available
  35. from ._generated.types import ChatCompletionStreamOutput, TextGenerationStreamOutput
  36. if TYPE_CHECKING:
  37. from PIL.Image import Image
  38. # TYPES
  39. UrlT = str
  40. PathT = Union[str, Path]
  41. ContentT = Union[bytes, BinaryIO, PathT, UrlT, "Image", bytearray, memoryview]
  42. # Use to set an Accept: image/png header
  43. TASKS_EXPECTING_IMAGES = {"text-to-image", "image-to-image"}
  44. logger = logging.getLogger(__name__)
  45. @dataclass
  46. class RequestParameters:
  47. url: str
  48. task: str
  49. model: str | None
  50. json: str | dict | list | None
  51. data: bytes | None
  52. headers: dict[str, Any]
  53. class MimeBytes(bytes):
  54. """
  55. A bytes object with a mime type.
  56. To be returned by `_prepare_payload_open_as_mime_bytes` in subclasses.
  57. Example:
  58. ```python
  59. >>> b = MimeBytes(b"hello", "text/plain")
  60. >>> isinstance(b, bytes)
  61. True
  62. >>> b.mime_type
  63. 'text/plain'
  64. ```
  65. """
  66. mime_type: str | None
  67. def __new__(cls, data: bytes, mime_type: str | None = None):
  68. obj = super().__new__(cls, data)
  69. obj.mime_type = mime_type
  70. if isinstance(data, MimeBytes) and mime_type is None:
  71. obj.mime_type = data.mime_type
  72. return obj
  73. ## IMPORT UTILS
  74. def _import_numpy():
  75. """Make sure `numpy` is installed on the machine."""
  76. if not is_numpy_available():
  77. raise ImportError("Please install numpy to use deal with embeddings (`pip install numpy`).")
  78. import numpy
  79. return numpy
  80. def _import_pil_image():
  81. """Make sure `PIL` is installed on the machine."""
  82. if not is_pillow_available():
  83. raise ImportError(
  84. "Please install Pillow to use deal with images (`pip install Pillow`). If you don't want the image to be"
  85. " post-processed, use `client.post(...)` and get the raw response from the server."
  86. )
  87. from PIL import Image
  88. return Image
  89. ## ENCODING / DECODING UTILS
  90. @overload
  91. def _open_as_mime_bytes(content: ContentT) -> MimeBytes: ... # means "if input is not None, output is not None"
  92. @overload
  93. def _open_as_mime_bytes(content: Literal[None]) -> Literal[None]: ... # means "if input is None, output is None"
  94. def _open_as_mime_bytes(content: ContentT | None) -> MimeBytes | None:
  95. """Open `content` as a binary file, either from a URL, a local path, raw bytes, or a PIL Image.
  96. Do nothing if `content` is None.
  97. """
  98. # If content is None, yield None
  99. if content is None:
  100. return None
  101. # If content is bytes, return it
  102. if isinstance(content, bytes):
  103. return MimeBytes(content)
  104. # If content is raw binary data (bytearray, memoryview)
  105. if isinstance(content, (bytearray, memoryview)):
  106. return MimeBytes(bytes(content))
  107. # If content is a binary file-like object
  108. if hasattr(content, "read"): # duck-typing instead of isinstance(content, BinaryIO)
  109. logger.debug("Reading content from BinaryIO")
  110. data = content.read()
  111. mime_type = mimetypes.guess_type(str(content.name))[0] if hasattr(content, "name") else None
  112. if isinstance(data, str):
  113. raise TypeError("Expected binary stream (bytes), but got text stream")
  114. return MimeBytes(data, mime_type=mime_type)
  115. # If content is a string => must be either a URL or a path
  116. if isinstance(content, str):
  117. if content.startswith("https://") or content.startswith("http://"):
  118. logger.debug(f"Downloading content from {content}")
  119. response = get_session().get(content)
  120. mime_type = response.headers.get("Content-Type")
  121. if mime_type is None:
  122. mime_type = mimetypes.guess_type(content)[0]
  123. return MimeBytes(response.content, mime_type=mime_type)
  124. content = Path(content)
  125. if not content.exists():
  126. raise FileNotFoundError(
  127. f"File not found at {content}. If `data` is a string, it must either be a URL or a path to a local"
  128. " file. To pass raw content, please encode it as bytes first."
  129. )
  130. # If content is a Path => open it
  131. if isinstance(content, Path):
  132. logger.debug(f"Opening content from {content}")
  133. return MimeBytes(content.read_bytes(), mime_type=mimetypes.guess_type(content)[0])
  134. # If content is a PIL Image => convert to bytes
  135. if is_pillow_available():
  136. from PIL import Image
  137. if isinstance(content, Image.Image):
  138. logger.debug("Converting PIL Image to bytes")
  139. buffer = io.BytesIO()
  140. format = content.format or "PNG"
  141. content.save(buffer, format=format)
  142. return MimeBytes(buffer.getvalue(), mime_type=f"image/{format.lower()}")
  143. # If nothing matched, raise error
  144. raise TypeError(
  145. f"Unsupported content type: {type(content)}. "
  146. "Expected one of: bytes, bytearray, BinaryIO, memoryview, Path, str (URL or file path), or PIL.Image.Image."
  147. )
  148. def _b64_encode(content: ContentT) -> str:
  149. """Encode a raw file (image, audio) into base64. Can be bytes, an opened file, a path or a URL."""
  150. raw_bytes = _open_as_mime_bytes(content)
  151. return base64.b64encode(raw_bytes).decode()
  152. def _as_url(content: ContentT, default_mime_type: str) -> str:
  153. if isinstance(content, str) and content.startswith(("http://", "https://", "data:")):
  154. return content
  155. # Convert content to bytes
  156. raw_bytes = _open_as_mime_bytes(content)
  157. # Get MIME type
  158. mime_type = raw_bytes.mime_type or default_mime_type
  159. # Encode content to base64
  160. encoded_data = base64.b64encode(raw_bytes).decode()
  161. # Build data URL
  162. return f"data:{mime_type};base64,{encoded_data}"
  163. def _b64_to_image(encoded_image: str) -> "Image":
  164. """Parse a base64-encoded string into a PIL Image."""
  165. Image = _import_pil_image()
  166. return Image.open(io.BytesIO(base64.b64decode(encoded_image)))
  167. def _bytes_to_list(content: bytes) -> list:
  168. """Parse bytes from a Response object into a Python list.
  169. Expects the response body to be JSON-encoded data.
  170. NOTE: This is exactly the same implementation as `_bytes_to_dict` and will not complain if the returned data is a
  171. dictionary. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect.
  172. """
  173. return json.loads(content.decode())
  174. def _bytes_to_dict(content: bytes) -> dict:
  175. """Parse bytes from a Response object into a Python dictionary.
  176. Expects the response body to be JSON-encoded data.
  177. NOTE: This is exactly the same implementation as `_bytes_to_list` and will not complain if the returned data is a
  178. list. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect.
  179. """
  180. return json.loads(content.decode())
  181. def _bytes_to_image(content: bytes) -> "Image":
  182. """Parse bytes from a Response object into a PIL Image.
  183. Expects the response body to be raw bytes. To deal with b64 encoded images, use `_b64_to_image` instead.
  184. """
  185. Image = _import_pil_image()
  186. return Image.open(io.BytesIO(content))
  187. def _as_dict(response: bytes | dict) -> dict:
  188. return json.loads(response) if isinstance(response, bytes) else response
  189. ## STREAMING UTILS
  190. def _stream_text_generation_response(
  191. output_lines: Iterable[str], details: bool
  192. ) -> Iterable[str] | Iterable[TextGenerationStreamOutput]:
  193. """Used in `InferenceClient.text_generation`."""
  194. # Parse ServerSentEvents
  195. for line in output_lines:
  196. try:
  197. output = _format_text_generation_stream_output(line, details)
  198. except StopIteration:
  199. break
  200. if output is not None:
  201. yield output
  202. async def _async_stream_text_generation_response(
  203. output_lines: AsyncIterable[str], details: bool
  204. ) -> AsyncIterable[str] | AsyncIterable[TextGenerationStreamOutput]:
  205. """Used in `AsyncInferenceClient.text_generation`."""
  206. # Parse ServerSentEvents
  207. async for line in output_lines:
  208. try:
  209. output = _format_text_generation_stream_output(line, details)
  210. except StopIteration:
  211. break
  212. if output is not None:
  213. yield output
  214. def _format_text_generation_stream_output(line: str, details: bool) -> str | TextGenerationStreamOutput | None:
  215. if not line.startswith("data:"):
  216. return None # empty line
  217. if line.strip() == "data: [DONE]":
  218. raise StopIteration("[DONE] signal received.")
  219. # Decode payload
  220. payload = line.lstrip("data:").rstrip("/n")
  221. json_payload = json.loads(payload)
  222. # Either an error as being returned
  223. if json_payload.get("error") is not None:
  224. raise _parse_text_generation_error(json_payload["error"], json_payload.get("error_type"))
  225. # Or parse token payload
  226. output = TextGenerationStreamOutput.parse_obj_as_instance(json_payload)
  227. return output.token.text if not details else output
  228. def _stream_chat_completion_response(
  229. lines: Iterable[str],
  230. ) -> Iterable[ChatCompletionStreamOutput]:
  231. """Used in `InferenceClient.chat_completion` if model is served with TGI."""
  232. for line in lines:
  233. try:
  234. output = _format_chat_completion_stream_output(line)
  235. except StopIteration:
  236. break
  237. if output is not None:
  238. yield output
  239. async def _async_stream_chat_completion_response(
  240. lines: AsyncIterable[str],
  241. ) -> AsyncIterable[ChatCompletionStreamOutput]:
  242. """Used in `AsyncInferenceClient.chat_completion`."""
  243. async for line in lines:
  244. try:
  245. output = _format_chat_completion_stream_output(line)
  246. except StopIteration:
  247. break
  248. if output is not None:
  249. yield output
  250. def _format_chat_completion_stream_output(
  251. line: str,
  252. ) -> ChatCompletionStreamOutput | None:
  253. if not line.startswith("data:"):
  254. return None # empty line
  255. if line.strip() == "data: [DONE]":
  256. raise StopIteration("[DONE] signal received.")
  257. # Decode payload
  258. json_payload = json.loads(line.lstrip("data:").strip())
  259. # Either an error as being returned
  260. if json_payload.get("error") is not None:
  261. raise _parse_text_generation_error(json_payload["error"], json_payload.get("error_type"))
  262. # Or parse token payload
  263. return ChatCompletionStreamOutput.parse_obj_as_instance(json_payload)
  264. async def _async_yield_from(client: httpx.AsyncClient, response: httpx.Response) -> AsyncIterable[str]:
  265. async for line in response.aiter_lines():
  266. yield line.strip()
  267. # "TGI servers" are servers running with the `text-generation-inference` backend.
  268. # This backend is the go-to solution to run large language models at scale. However,
  269. # for some smaller models (e.g. "gpt2") the default `transformers` + `api-inference`
  270. # solution is still in use.
  271. #
  272. # Both approaches have very similar APIs, but not exactly the same. What we do first in
  273. # the `text_generation` method is to assume the model is served via TGI. If we realize
  274. # it's not the case (i.e. we receive an HTTP 400 Bad Request), we fall back to the
  275. # default API with a warning message. When that's the case, We remember the unsupported
  276. # attributes for this model in the `_UNSUPPORTED_TEXT_GENERATION_KWARGS` global variable.
  277. #
  278. # In addition, TGI servers have a built-in API route for chat-completion, which is not
  279. # available on the default API. We use this route to provide a more consistent behavior
  280. # when available.
  281. #
  282. # For more details, see https://github.com/huggingface/text-generation-inference and
  283. # https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task.
  284. _UNSUPPORTED_TEXT_GENERATION_KWARGS: dict[str | None, list[str]] = {}
  285. def _set_unsupported_text_generation_kwargs(model: str | None, unsupported_kwargs: list[str]) -> None:
  286. _UNSUPPORTED_TEXT_GENERATION_KWARGS.setdefault(model, []).extend(unsupported_kwargs)
  287. def _get_unsupported_text_generation_kwargs(model: str | None) -> list[str]:
  288. return _UNSUPPORTED_TEXT_GENERATION_KWARGS.get(model, [])
  289. # TEXT GENERATION ERRORS
  290. # ----------------------
  291. # Text-generation errors are parsed separately to handle as much as possible the errors returned by the text generation
  292. # inference project (https://github.com/huggingface/text-generation-inference).
  293. # ----------------------
  294. def raise_text_generation_error(http_error: HfHubHTTPError) -> NoReturn:
  295. """
  296. Try to parse text-generation-inference error message and raise HTTPError in any case.
  297. Args:
  298. error (`HTTPError`):
  299. The HTTPError that have been raised.
  300. """
  301. # Try to parse a Text Generation Inference error
  302. if http_error.response is None:
  303. raise http_error
  304. try:
  305. # Hacky way to retrieve payload in case of aiohttp error
  306. payload = getattr(http_error, "response_error_payload", None) or http_error.response.json()
  307. error = payload.get("error")
  308. error_type = payload.get("error_type")
  309. except Exception: # no payload
  310. raise http_error
  311. # If error_type => more information than `hf_raise_for_status`
  312. if error_type is not None:
  313. exception = _parse_text_generation_error(error, error_type)
  314. raise exception from http_error
  315. # Otherwise, fallback to default error
  316. raise http_error
  317. def _parse_text_generation_error(error: str | None, error_type: str | None) -> TextGenerationError:
  318. if error_type == "generation":
  319. return GenerationError(error) # type: ignore
  320. if error_type == "incomplete_generation":
  321. return IncompleteGenerationError(error) # type: ignore
  322. if error_type == "overloaded":
  323. return OverloadedError(error) # type: ignore
  324. if error_type == "validation":
  325. return ValidationError(error) # type: ignore
  326. return UnknownError(error) # type: ignore