_common.py 15 KB

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