_client.py 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368
  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. #
  16. # Related resources:
  17. # https://huggingface.co/tasks
  18. # https://huggingface.co/docs/huggingface.js/inference/README
  19. # https://github.com/huggingface/huggingface.js/tree/main/packages/inference/src
  20. # https://github.com/huggingface/text-generation-inference/tree/main/clients/python
  21. # https://github.com/huggingface/text-generation-inference/blob/main/clients/python/text_generation/client.py
  22. # https://huggingface.slack.com/archives/C03E4DQ9LAJ/p1680169099087869
  23. # https://github.com/huggingface/unity-api#tasks
  24. #
  25. # Some TODO:
  26. # - add all tasks
  27. #
  28. # NOTE: the philosophy of this client is "let's make it as easy as possible to use it, even if less optimized". Some
  29. # examples of how it translates:
  30. # - Timeout / Server unavailable is handled by the client in a single "timeout" parameter.
  31. # - Files can be provided as bytes, file paths, or URLs and the client will try to "guess" the type.
  32. # - Images are parsed as PIL.Image for easier manipulation.
  33. # - Provides a "recommended model" for each task => suboptimal but user-wise quicker to get a first script running.
  34. # - Only the main parameters are publicly exposed. Power users can always read the docs for more options.
  35. import base64
  36. import logging
  37. import re
  38. import warnings
  39. from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Literal, Optional, Union, overload
  40. from requests import HTTPError
  41. from huggingface_hub import constants
  42. from huggingface_hub.errors import BadRequestError, InferenceTimeoutError
  43. from huggingface_hub.inference._common import (
  44. TASKS_EXPECTING_IMAGES,
  45. ContentT,
  46. RequestParameters,
  47. _b64_encode,
  48. _b64_to_image,
  49. _bytes_to_dict,
  50. _bytes_to_image,
  51. _bytes_to_list,
  52. _get_unsupported_text_generation_kwargs,
  53. _import_numpy,
  54. _set_unsupported_text_generation_kwargs,
  55. _stream_chat_completion_response,
  56. _stream_text_generation_response,
  57. raise_text_generation_error,
  58. )
  59. from huggingface_hub.inference._generated.types import (
  60. AudioClassificationOutputElement,
  61. AudioClassificationOutputTransform,
  62. AudioToAudioOutputElement,
  63. AutomaticSpeechRecognitionOutput,
  64. ChatCompletionInputGrammarType,
  65. ChatCompletionInputMessage,
  66. ChatCompletionInputStreamOptions,
  67. ChatCompletionInputTool,
  68. ChatCompletionInputToolChoiceClass,
  69. ChatCompletionInputToolChoiceEnum,
  70. ChatCompletionOutput,
  71. ChatCompletionStreamOutput,
  72. DocumentQuestionAnsweringOutputElement,
  73. FillMaskOutputElement,
  74. ImageClassificationOutputElement,
  75. ImageClassificationOutputTransform,
  76. ImageSegmentationOutputElement,
  77. ImageSegmentationSubtask,
  78. ImageToImageTargetSize,
  79. ImageToTextOutput,
  80. ImageToVideoTargetSize,
  81. ObjectDetectionOutputElement,
  82. Padding,
  83. QuestionAnsweringOutputElement,
  84. SummarizationOutput,
  85. SummarizationTruncationStrategy,
  86. TableQuestionAnsweringOutputElement,
  87. TextClassificationOutputElement,
  88. TextClassificationOutputTransform,
  89. TextGenerationInputGrammarType,
  90. TextGenerationOutput,
  91. TextGenerationStreamOutput,
  92. TextToSpeechEarlyStoppingEnum,
  93. TokenClassificationAggregationStrategy,
  94. TokenClassificationOutputElement,
  95. TranslationOutput,
  96. TranslationTruncationStrategy,
  97. VisualQuestionAnsweringOutputElement,
  98. ZeroShotClassificationOutputElement,
  99. ZeroShotImageClassificationOutputElement,
  100. )
  101. from huggingface_hub.inference._providers import PROVIDER_OR_POLICY_T, get_provider_helper
  102. from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
  103. from huggingface_hub.utils._auth import get_token
  104. if TYPE_CHECKING:
  105. import numpy as np
  106. from PIL.Image import Image
  107. logger = logging.getLogger(__name__)
  108. MODEL_KWARGS_NOT_USED_REGEX = re.compile(r"The following `model_kwargs` are not used by the model: \[(.*?)\]")
  109. class InferenceClient:
  110. """
  111. Initialize a new Inference Client.
  112. [`InferenceClient`] aims to provide a unified experience to perform inference. The client can be used
  113. seamlessly with either the (free) Inference API, self-hosted Inference Endpoints, or third-party Inference Providers.
  114. Args:
  115. model (`str`, `optional`):
  116. 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`
  117. or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is
  118. automatically selected for the task.
  119. Note: for better compatibility with OpenAI's client, `model` has been aliased as `base_url`. Those 2
  120. arguments are mutually exclusive. If a URL is passed as `model` or `base_url` for chat completion, the `(/v1)/chat/completions` suffix path will be appended to the URL.
  121. provider (`str`, *optional*):
  122. Name of the provider to use for inference. Can be `"black-forest-labs"`, `"cerebras"`, `"clarifai"`, `"cohere"`, `"fal-ai"`, `"featherless-ai"`, `"fireworks-ai"`, `"groq"`, `"hf-inference"`, `"hyperbolic"`, `"nebius"`, `"novita"`, `"nscale"`, `"openai"`, `publicai`, `"replicate"`, `"sambanova"`, `"scaleway"`, `"together"` or `"zai-org"`.
  123. 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.
  124. If model is a URL or `base_url` is passed, then `provider` is not used.
  125. token (`str`, *optional*):
  126. Hugging Face token. Will default to the locally saved token if not provided.
  127. Note: for better compatibility with OpenAI's client, `token` has been aliased as `api_key`. Those 2
  128. arguments are mutually exclusive and have the exact same behavior.
  129. timeout (`float`, `optional`):
  130. The maximum number of seconds to wait for a response from the server. Defaults to None, meaning it will loop until the server is available.
  131. headers (`Dict[str, str]`, `optional`):
  132. Additional headers to send to the server. By default only the authorization and user-agent headers are sent.
  133. Values in this dictionary will override the default values.
  134. bill_to (`str`, `optional`):
  135. The billing account to use for the requests. By default the requests are billed on the user's account.
  136. Requests can only be billed to an organization the user is a member of, and which has subscribed to Enterprise Hub.
  137. cookies (`Dict[str, str]`, `optional`):
  138. Additional cookies to send to the server.
  139. proxies (`Any`, `optional`):
  140. Proxies to use for the request.
  141. base_url (`str`, `optional`):
  142. Base URL to run inference. This is a duplicated argument from `model` to make [`InferenceClient`]
  143. follow the same pattern as `openai.OpenAI` client. Cannot be used if `model` is set. Defaults to None.
  144. api_key (`str`, `optional`):
  145. Token to use for authentication. This is a duplicated argument from `token` to make [`InferenceClient`]
  146. follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
  147. """
  148. def __init__(
  149. self,
  150. model: Optional[str] = None,
  151. *,
  152. provider: Optional[PROVIDER_OR_POLICY_T] = None,
  153. token: Optional[str] = None,
  154. timeout: Optional[float] = None,
  155. headers: Optional[Dict[str, str]] = None,
  156. cookies: Optional[Dict[str, str]] = None,
  157. proxies: Optional[Any] = None,
  158. bill_to: Optional[str] = None,
  159. # OpenAI compatibility
  160. base_url: Optional[str] = None,
  161. api_key: Optional[str] = None,
  162. ) -> None:
  163. if model is not None and base_url is not None:
  164. raise ValueError(
  165. "Received both `model` and `base_url` arguments. Please provide only one of them."
  166. " `base_url` is an alias for `model` to make the API compatible with OpenAI's client."
  167. " If using `base_url` for chat completion, the `/chat/completions` suffix path will be appended to the base url."
  168. " When passing a URL as `model`, the client will not append any suffix path to it."
  169. )
  170. if token is not None and api_key is not None:
  171. raise ValueError(
  172. "Received both `token` and `api_key` arguments. Please provide only one of them."
  173. " `api_key` is an alias for `token` to make the API compatible with OpenAI's client."
  174. " It has the exact same behavior as `token`."
  175. )
  176. token = token if token is not None else api_key
  177. if isinstance(token, bool):
  178. # Legacy behavior: previously is was possible to pass `token=False` to disable authentication. This is not
  179. # supported anymore as authentication is required. Better to explicitly raise here rather than risking
  180. # sending the locally saved token without the user knowing about it.
  181. if token is False:
  182. raise ValueError(
  183. "Cannot use `token=False` to disable authentication as authentication is required to run Inference."
  184. )
  185. warnings.warn(
  186. "Using `token=True` to automatically use the locally saved token is deprecated and will be removed in a future release. "
  187. "Please use `token=None` instead (default).",
  188. DeprecationWarning,
  189. )
  190. token = get_token()
  191. self.model: Optional[str] = base_url or model
  192. self.token: Optional[str] = token
  193. self.headers = {**headers} if headers is not None else {}
  194. if bill_to is not None:
  195. if (
  196. constants.HUGGINGFACE_HEADER_X_BILL_TO in self.headers
  197. and self.headers[constants.HUGGINGFACE_HEADER_X_BILL_TO] != bill_to
  198. ):
  199. warnings.warn(
  200. f"Overriding existing '{self.headers[constants.HUGGINGFACE_HEADER_X_BILL_TO]}' value in headers with '{bill_to}'.",
  201. UserWarning,
  202. )
  203. self.headers[constants.HUGGINGFACE_HEADER_X_BILL_TO] = bill_to
  204. if token is not None and not token.startswith("hf_"):
  205. warnings.warn(
  206. "You've provided an external provider's API key, so requests will be billed directly by the provider. "
  207. "The `bill_to` parameter is only applicable for Hugging Face billing and will be ignored.",
  208. UserWarning,
  209. )
  210. # Configure provider
  211. self.provider = provider
  212. self.cookies = cookies
  213. self.timeout = timeout
  214. self.proxies = proxies
  215. def __repr__(self):
  216. return f"<InferenceClient(model='{self.model if self.model else ''}', timeout={self.timeout})>"
  217. @overload
  218. def _inner_post( # type: ignore[misc]
  219. self, request_parameters: RequestParameters, *, stream: Literal[False] = ...
  220. ) -> bytes: ...
  221. @overload
  222. def _inner_post( # type: ignore[misc]
  223. self, request_parameters: RequestParameters, *, stream: Literal[True] = ...
  224. ) -> Iterable[bytes]: ...
  225. @overload
  226. def _inner_post(
  227. self, request_parameters: RequestParameters, *, stream: bool = False
  228. ) -> Union[bytes, Iterable[bytes]]: ...
  229. def _inner_post(
  230. self, request_parameters: RequestParameters, *, stream: bool = False
  231. ) -> Union[bytes, Iterable[bytes]]:
  232. """Make a request to the inference server."""
  233. # TODO: this should be handled in provider helpers directly
  234. if request_parameters.task in TASKS_EXPECTING_IMAGES and "Accept" not in request_parameters.headers:
  235. request_parameters.headers["Accept"] = "image/png"
  236. try:
  237. response = get_session().post(
  238. request_parameters.url,
  239. json=request_parameters.json,
  240. data=request_parameters.data,
  241. headers=request_parameters.headers,
  242. cookies=self.cookies,
  243. timeout=self.timeout,
  244. stream=stream,
  245. proxies=self.proxies,
  246. )
  247. except TimeoutError as error:
  248. # Convert any `TimeoutError` to a `InferenceTimeoutError`
  249. raise InferenceTimeoutError(f"Inference call timed out: {request_parameters.url}") from error # type: ignore
  250. try:
  251. hf_raise_for_status(response)
  252. return response.iter_lines() if stream else response.content
  253. except HTTPError as error:
  254. if error.response.status_code == 422 and request_parameters.task != "unknown":
  255. msg = str(error.args[0])
  256. if len(error.response.text) > 0:
  257. msg += f"\n{error.response.text}\n"
  258. error.args = (msg,) + error.args[1:]
  259. raise
  260. def audio_classification(
  261. self,
  262. audio: ContentT,
  263. *,
  264. model: Optional[str] = None,
  265. top_k: Optional[int] = None,
  266. function_to_apply: Optional["AudioClassificationOutputTransform"] = None,
  267. ) -> List[AudioClassificationOutputElement]:
  268. """
  269. Perform audio classification on the provided audio content.
  270. Args:
  271. audio (Union[str, Path, bytes, BinaryIO]):
  272. The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an
  273. audio file.
  274. model (`str`, *optional*):
  275. The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub
  276. or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
  277. audio classification will be used.
  278. top_k (`int`, *optional*):
  279. When specified, limits the output to the top K most probable classes.
  280. function_to_apply (`"AudioClassificationOutputTransform"`, *optional*):
  281. The function to apply to the model outputs in order to retrieve the scores.
  282. Returns:
  283. `List[AudioClassificationOutputElement]`: List of [`AudioClassificationOutputElement`] items containing the predicted labels and their confidence.
  284. Raises:
  285. [`InferenceTimeoutError`]:
  286. If the model is unavailable or the request times out.
  287. `HTTPError`:
  288. If the request fails with an HTTP error status code other than HTTP 503.
  289. Example:
  290. ```py
  291. >>> from huggingface_hub import InferenceClient
  292. >>> client = InferenceClient()
  293. >>> client.audio_classification("audio.flac")
  294. [
  295. AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
  296. AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
  297. ...
  298. ]
  299. ```
  300. """
  301. model_id = model or self.model
  302. provider_helper = get_provider_helper(self.provider, task="audio-classification", model=model_id)
  303. request_parameters = provider_helper.prepare_request(
  304. inputs=audio,
  305. parameters={"function_to_apply": function_to_apply, "top_k": top_k},
  306. headers=self.headers,
  307. model=model_id,
  308. api_key=self.token,
  309. )
  310. response = self._inner_post(request_parameters)
  311. return AudioClassificationOutputElement.parse_obj_as_list(response)
  312. def audio_to_audio(
  313. self,
  314. audio: ContentT,
  315. *,
  316. model: Optional[str] = None,
  317. ) -> List[AudioToAudioOutputElement]:
  318. """
  319. Performs multiple tasks related to audio-to-audio depending on the model (eg: speech enhancement, source separation).
  320. Args:
  321. audio (Union[str, Path, bytes, BinaryIO]):
  322. The audio content for the model. It can be raw audio bytes, a local audio file, or a URL pointing to an
  323. audio file.
  324. model (`str`, *optional*):
  325. The model can be any model which takes an audio file and returns another audio file. Can be a model ID hosted on the Hugging Face Hub
  326. or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
  327. audio_to_audio will be used.
  328. Returns:
  329. `List[AudioToAudioOutputElement]`: A list of [`AudioToAudioOutputElement`] items containing audios label, content-type, and audio content in blob.
  330. Raises:
  331. `InferenceTimeoutError`:
  332. If the model is unavailable or the request times out.
  333. `HTTPError`:
  334. If the request fails with an HTTP error status code other than HTTP 503.
  335. Example:
  336. ```py
  337. >>> from huggingface_hub import InferenceClient
  338. >>> client = InferenceClient()
  339. >>> audio_output = client.audio_to_audio("audio.flac")
  340. >>> for i, item in enumerate(audio_output):
  341. >>> with open(f"output_{i}.flac", "wb") as f:
  342. f.write(item.blob)
  343. ```
  344. """
  345. model_id = model or self.model
  346. provider_helper = get_provider_helper(self.provider, task="audio-to-audio", model=model_id)
  347. request_parameters = provider_helper.prepare_request(
  348. inputs=audio,
  349. parameters={},
  350. headers=self.headers,
  351. model=model_id,
  352. api_key=self.token,
  353. )
  354. response = self._inner_post(request_parameters)
  355. audio_output = AudioToAudioOutputElement.parse_obj_as_list(response)
  356. for item in audio_output:
  357. item.blob = base64.b64decode(item.blob)
  358. return audio_output
  359. def automatic_speech_recognition(
  360. self,
  361. audio: ContentT,
  362. *,
  363. model: Optional[str] = None,
  364. extra_body: Optional[Dict] = None,
  365. ) -> AutomaticSpeechRecognitionOutput:
  366. """
  367. Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.
  368. Args:
  369. audio (Union[str, Path, bytes, BinaryIO]):
  370. The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file.
  371. model (`str`, *optional*):
  372. The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  373. Inference Endpoint. If not provided, the default recommended model for ASR will be used.
  374. extra_body (`Dict`, *optional*):
  375. Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
  376. for supported parameters.
  377. Returns:
  378. [`AutomaticSpeechRecognitionOutput`]: An item containing the transcribed text and optionally the timestamp chunks.
  379. Raises:
  380. [`InferenceTimeoutError`]:
  381. If the model is unavailable or the request times out.
  382. `HTTPError`:
  383. If the request fails with an HTTP error status code other than HTTP 503.
  384. Example:
  385. ```py
  386. >>> from huggingface_hub import InferenceClient
  387. >>> client = InferenceClient()
  388. >>> client.automatic_speech_recognition("hello_world.flac").text
  389. "hello world"
  390. ```
  391. """
  392. model_id = model or self.model
  393. provider_helper = get_provider_helper(self.provider, task="automatic-speech-recognition", model=model_id)
  394. request_parameters = provider_helper.prepare_request(
  395. inputs=audio,
  396. parameters={**(extra_body or {})},
  397. headers=self.headers,
  398. model=model_id,
  399. api_key=self.token,
  400. )
  401. response = self._inner_post(request_parameters)
  402. return AutomaticSpeechRecognitionOutput.parse_obj_as_instance(response)
  403. @overload
  404. def chat_completion( # type: ignore
  405. self,
  406. messages: List[Union[Dict, ChatCompletionInputMessage]],
  407. *,
  408. model: Optional[str] = None,
  409. stream: Literal[False] = False,
  410. frequency_penalty: Optional[float] = None,
  411. logit_bias: Optional[List[float]] = None,
  412. logprobs: Optional[bool] = None,
  413. max_tokens: Optional[int] = None,
  414. n: Optional[int] = None,
  415. presence_penalty: Optional[float] = None,
  416. response_format: Optional[ChatCompletionInputGrammarType] = None,
  417. seed: Optional[int] = None,
  418. stop: Optional[List[str]] = None,
  419. stream_options: Optional[ChatCompletionInputStreamOptions] = None,
  420. temperature: Optional[float] = None,
  421. tool_choice: Optional[Union[ChatCompletionInputToolChoiceClass, "ChatCompletionInputToolChoiceEnum"]] = None,
  422. tool_prompt: Optional[str] = None,
  423. tools: Optional[List[ChatCompletionInputTool]] = None,
  424. top_logprobs: Optional[int] = None,
  425. top_p: Optional[float] = None,
  426. extra_body: Optional[Dict] = None,
  427. ) -> ChatCompletionOutput: ...
  428. @overload
  429. def chat_completion( # type: ignore
  430. self,
  431. messages: List[Union[Dict, ChatCompletionInputMessage]],
  432. *,
  433. model: Optional[str] = None,
  434. stream: Literal[True] = True,
  435. frequency_penalty: Optional[float] = None,
  436. logit_bias: Optional[List[float]] = None,
  437. logprobs: Optional[bool] = None,
  438. max_tokens: Optional[int] = None,
  439. n: Optional[int] = None,
  440. presence_penalty: Optional[float] = None,
  441. response_format: Optional[ChatCompletionInputGrammarType] = None,
  442. seed: Optional[int] = None,
  443. stop: Optional[List[str]] = None,
  444. stream_options: Optional[ChatCompletionInputStreamOptions] = None,
  445. temperature: Optional[float] = None,
  446. tool_choice: Optional[Union[ChatCompletionInputToolChoiceClass, "ChatCompletionInputToolChoiceEnum"]] = None,
  447. tool_prompt: Optional[str] = None,
  448. tools: Optional[List[ChatCompletionInputTool]] = None,
  449. top_logprobs: Optional[int] = None,
  450. top_p: Optional[float] = None,
  451. extra_body: Optional[Dict] = None,
  452. ) -> Iterable[ChatCompletionStreamOutput]: ...
  453. @overload
  454. def chat_completion(
  455. self,
  456. messages: List[Union[Dict, ChatCompletionInputMessage]],
  457. *,
  458. model: Optional[str] = None,
  459. stream: bool = False,
  460. frequency_penalty: Optional[float] = None,
  461. logit_bias: Optional[List[float]] = None,
  462. logprobs: Optional[bool] = None,
  463. max_tokens: Optional[int] = None,
  464. n: Optional[int] = None,
  465. presence_penalty: Optional[float] = None,
  466. response_format: Optional[ChatCompletionInputGrammarType] = None,
  467. seed: Optional[int] = None,
  468. stop: Optional[List[str]] = None,
  469. stream_options: Optional[ChatCompletionInputStreamOptions] = None,
  470. temperature: Optional[float] = None,
  471. tool_choice: Optional[Union[ChatCompletionInputToolChoiceClass, "ChatCompletionInputToolChoiceEnum"]] = None,
  472. tool_prompt: Optional[str] = None,
  473. tools: Optional[List[ChatCompletionInputTool]] = None,
  474. top_logprobs: Optional[int] = None,
  475. top_p: Optional[float] = None,
  476. extra_body: Optional[Dict] = None,
  477. ) -> Union[ChatCompletionOutput, Iterable[ChatCompletionStreamOutput]]: ...
  478. def chat_completion(
  479. self,
  480. messages: List[Union[Dict, ChatCompletionInputMessage]],
  481. *,
  482. model: Optional[str] = None,
  483. stream: bool = False,
  484. # Parameters from ChatCompletionInput (handled manually)
  485. frequency_penalty: Optional[float] = None,
  486. logit_bias: Optional[List[float]] = None,
  487. logprobs: Optional[bool] = None,
  488. max_tokens: Optional[int] = None,
  489. n: Optional[int] = None,
  490. presence_penalty: Optional[float] = None,
  491. response_format: Optional[ChatCompletionInputGrammarType] = None,
  492. seed: Optional[int] = None,
  493. stop: Optional[List[str]] = None,
  494. stream_options: Optional[ChatCompletionInputStreamOptions] = None,
  495. temperature: Optional[float] = None,
  496. tool_choice: Optional[Union[ChatCompletionInputToolChoiceClass, "ChatCompletionInputToolChoiceEnum"]] = None,
  497. tool_prompt: Optional[str] = None,
  498. tools: Optional[List[ChatCompletionInputTool]] = None,
  499. top_logprobs: Optional[int] = None,
  500. top_p: Optional[float] = None,
  501. extra_body: Optional[Dict] = None,
  502. ) -> Union[ChatCompletionOutput, Iterable[ChatCompletionStreamOutput]]:
  503. """
  504. A method for completing conversations using a specified language model.
  505. > [!TIP]
  506. > The `client.chat_completion` method is aliased as `client.chat.completions.create` for compatibility with OpenAI's client.
  507. > Inputs and outputs are strictly the same and using either syntax will yield the same results.
  508. > Check out the [Inference guide](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility)
  509. > for more details about OpenAI's compatibility.
  510. > [!TIP]
  511. > You can pass provider-specific parameters to the model by using the `extra_body` argument.
  512. Args:
  513. messages (List of [`ChatCompletionInputMessage`]):
  514. Conversation history consisting of roles and content pairs.
  515. model (`str`, *optional*):
  516. The model to use for chat-completion. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  517. Inference Endpoint. If not provided, the default recommended model for chat-based text-generation will be used.
  518. See https://huggingface.co/tasks/text-generation for more details.
  519. If `model` is a model ID, it is passed to the server as the `model` parameter. If you want to define a
  520. custom URL while setting `model` in the request payload, you must set `base_url` when initializing [`InferenceClient`].
  521. frequency_penalty (`float`, *optional*):
  522. Penalizes new tokens based on their existing frequency
  523. in the text so far. Range: [-2.0, 2.0]. Defaults to 0.0.
  524. logit_bias (`List[float]`, *optional*):
  525. Adjusts the likelihood of specific tokens appearing in the generated output.
  526. logprobs (`bool`, *optional*):
  527. Whether to return log probabilities of the output tokens or not. If true, returns the log
  528. probabilities of each output token returned in the content of message.
  529. max_tokens (`int`, *optional*):
  530. Maximum number of tokens allowed in the response. Defaults to 100.
  531. n (`int`, *optional*):
  532. The number of completions to generate for each prompt.
  533. presence_penalty (`float`, *optional*):
  534. Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the
  535. text so far, increasing the model's likelihood to talk about new topics.
  536. response_format ([`ChatCompletionInputGrammarType`], *optional*):
  537. Grammar constraints. Can be either a JSONSchema or a regex.
  538. seed (Optional[`int`], *optional*):
  539. Seed for reproducible control flow. Defaults to None.
  540. stop (`List[str]`, *optional*):
  541. Up to four strings which trigger the end of the response.
  542. Defaults to None.
  543. stream (`bool`, *optional*):
  544. Enable realtime streaming of responses. Defaults to False.
  545. stream_options ([`ChatCompletionInputStreamOptions`], *optional*):
  546. Options for streaming completions.
  547. temperature (`float`, *optional*):
  548. Controls randomness of the generations. Lower values ensure
  549. less random completions. Range: [0, 2]. Defaults to 1.0.
  550. top_logprobs (`int`, *optional*):
  551. An integer between 0 and 5 specifying the number of most likely tokens to return at each token
  552. position, each with an associated log probability. logprobs must be set to true if this parameter is
  553. used.
  554. top_p (`float`, *optional*):
  555. Fraction of the most likely next words to sample from.
  556. Must be between 0 and 1. Defaults to 1.0.
  557. tool_choice ([`ChatCompletionInputToolChoiceClass`] or [`ChatCompletionInputToolChoiceEnum`], *optional*):
  558. The tool to use for the completion. Defaults to "auto".
  559. tool_prompt (`str`, *optional*):
  560. A prompt to be appended before the tools.
  561. tools (List of [`ChatCompletionInputTool`], *optional*):
  562. A list of tools the model may call. Currently, only functions are supported as a tool. Use this to
  563. provide a list of functions the model may generate JSON inputs for.
  564. extra_body (`Dict`, *optional*):
  565. Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
  566. for supported parameters.
  567. Returns:
  568. [`ChatCompletionOutput`] or Iterable of [`ChatCompletionStreamOutput`]:
  569. Generated text returned from the server:
  570. - if `stream=False`, the generated text is returned as a [`ChatCompletionOutput`] (default).
  571. - if `stream=True`, the generated text is returned token by token as a sequence of [`ChatCompletionStreamOutput`].
  572. Raises:
  573. [`InferenceTimeoutError`]:
  574. If the model is unavailable or the request times out.
  575. `HTTPError`:
  576. If the request fails with an HTTP error status code other than HTTP 503.
  577. Example:
  578. ```py
  579. >>> from huggingface_hub import InferenceClient
  580. >>> messages = [{"role": "user", "content": "What is the capital of France?"}]
  581. >>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
  582. >>> client.chat_completion(messages, max_tokens=100)
  583. ChatCompletionOutput(
  584. choices=[
  585. ChatCompletionOutputComplete(
  586. finish_reason='eos_token',
  587. index=0,
  588. message=ChatCompletionOutputMessage(
  589. role='assistant',
  590. content='The capital of France is Paris.',
  591. name=None,
  592. tool_calls=None
  593. ),
  594. logprobs=None
  595. )
  596. ],
  597. created=1719907176,
  598. id='',
  599. model='meta-llama/Meta-Llama-3-8B-Instruct',
  600. object='text_completion',
  601. system_fingerprint='2.0.4-sha-f426a33',
  602. usage=ChatCompletionOutputUsage(
  603. completion_tokens=8,
  604. prompt_tokens=17,
  605. total_tokens=25
  606. )
  607. )
  608. ```
  609. Example using streaming:
  610. ```py
  611. >>> from huggingface_hub import InferenceClient
  612. >>> messages = [{"role": "user", "content": "What is the capital of France?"}]
  613. >>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
  614. >>> for token in client.chat_completion(messages, max_tokens=10, stream=True):
  615. ... print(token)
  616. ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
  617. ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
  618. (...)
  619. ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
  620. ```
  621. Example using OpenAI's syntax:
  622. ```py
  623. # instead of `from openai import OpenAI`
  624. from huggingface_hub import InferenceClient
  625. # instead of `client = OpenAI(...)`
  626. client = InferenceClient(
  627. base_url=...,
  628. api_key=...,
  629. )
  630. output = client.chat.completions.create(
  631. model="meta-llama/Meta-Llama-3-8B-Instruct",
  632. messages=[
  633. {"role": "system", "content": "You are a helpful assistant."},
  634. {"role": "user", "content": "Count to 10"},
  635. ],
  636. stream=True,
  637. max_tokens=1024,
  638. )
  639. for chunk in output:
  640. print(chunk.choices[0].delta.content)
  641. ```
  642. Example using a third-party provider directly with extra (provider-specific) parameters. Usage will be billed on your Together AI account.
  643. ```py
  644. >>> from huggingface_hub import InferenceClient
  645. >>> client = InferenceClient(
  646. ... provider="together", # Use Together AI provider
  647. ... api_key="<together_api_key>", # Pass your Together API key directly
  648. ... )
  649. >>> client.chat_completion(
  650. ... model="meta-llama/Meta-Llama-3-8B-Instruct",
  651. ... messages=[{"role": "user", "content": "What is the capital of France?"}],
  652. ... extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
  653. ... )
  654. ```
  655. Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
  656. ```py
  657. >>> from huggingface_hub import InferenceClient
  658. >>> client = InferenceClient(
  659. ... provider="sambanova", # Use Sambanova provider
  660. ... api_key="hf_...", # Pass your HF token
  661. ... )
  662. >>> client.chat_completion(
  663. ... model="meta-llama/Meta-Llama-3-8B-Instruct",
  664. ... messages=[{"role": "user", "content": "What is the capital of France?"}],
  665. ... )
  666. ```
  667. Example using Image + Text as input:
  668. ```py
  669. >>> from huggingface_hub import InferenceClient
  670. # provide a remote URL
  671. >>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
  672. # or a base64-encoded image
  673. >>> image_path = "/path/to/image.jpeg"
  674. >>> with open(image_path, "rb") as f:
  675. ... base64_image = base64.b64encode(f.read()).decode("utf-8")
  676. >>> image_url = f"data:image/jpeg;base64,{base64_image}"
  677. >>> client = InferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
  678. >>> output = client.chat.completions.create(
  679. ... messages=[
  680. ... {
  681. ... "role": "user",
  682. ... "content": [
  683. ... {
  684. ... "type": "image_url",
  685. ... "image_url": {"url": image_url},
  686. ... },
  687. ... {
  688. ... "type": "text",
  689. ... "text": "Describe this image in one sentence.",
  690. ... },
  691. ... ],
  692. ... },
  693. ... ],
  694. ... )
  695. >>> output
  696. The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
  697. ```
  698. Example using tools:
  699. ```py
  700. >>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
  701. >>> messages = [
  702. ... {
  703. ... "role": "system",
  704. ... "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
  705. ... },
  706. ... {
  707. ... "role": "user",
  708. ... "content": "What's the weather like the next 3 days in San Francisco, CA?",
  709. ... },
  710. ... ]
  711. >>> tools = [
  712. ... {
  713. ... "type": "function",
  714. ... "function": {
  715. ... "name": "get_current_weather",
  716. ... "description": "Get the current weather",
  717. ... "parameters": {
  718. ... "type": "object",
  719. ... "properties": {
  720. ... "location": {
  721. ... "type": "string",
  722. ... "description": "The city and state, e.g. San Francisco, CA",
  723. ... },
  724. ... "format": {
  725. ... "type": "string",
  726. ... "enum": ["celsius", "fahrenheit"],
  727. ... "description": "The temperature unit to use. Infer this from the users location.",
  728. ... },
  729. ... },
  730. ... "required": ["location", "format"],
  731. ... },
  732. ... },
  733. ... },
  734. ... {
  735. ... "type": "function",
  736. ... "function": {
  737. ... "name": "get_n_day_weather_forecast",
  738. ... "description": "Get an N-day weather forecast",
  739. ... "parameters": {
  740. ... "type": "object",
  741. ... "properties": {
  742. ... "location": {
  743. ... "type": "string",
  744. ... "description": "The city and state, e.g. San Francisco, CA",
  745. ... },
  746. ... "format": {
  747. ... "type": "string",
  748. ... "enum": ["celsius", "fahrenheit"],
  749. ... "description": "The temperature unit to use. Infer this from the users location.",
  750. ... },
  751. ... "num_days": {
  752. ... "type": "integer",
  753. ... "description": "The number of days to forecast",
  754. ... },
  755. ... },
  756. ... "required": ["location", "format", "num_days"],
  757. ... },
  758. ... },
  759. ... },
  760. ... ]
  761. >>> response = client.chat_completion(
  762. ... model="meta-llama/Meta-Llama-3-70B-Instruct",
  763. ... messages=messages,
  764. ... tools=tools,
  765. ... tool_choice="auto",
  766. ... max_tokens=500,
  767. ... )
  768. >>> response.choices[0].message.tool_calls[0].function
  769. ChatCompletionOutputFunctionDefinition(
  770. arguments={
  771. 'location': 'San Francisco, CA',
  772. 'format': 'fahrenheit',
  773. 'num_days': 3
  774. },
  775. name='get_n_day_weather_forecast',
  776. description=None
  777. )
  778. ```
  779. Example using response_format:
  780. ```py
  781. >>> from huggingface_hub import InferenceClient
  782. >>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
  783. >>> messages = [
  784. ... {
  785. ... "role": "user",
  786. ... "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I saw and when?",
  787. ... },
  788. ... ]
  789. >>> response_format = {
  790. ... "type": "json",
  791. ... "value": {
  792. ... "properties": {
  793. ... "location": {"type": "string"},
  794. ... "activity": {"type": "string"},
  795. ... "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
  796. ... "animals": {"type": "array", "items": {"type": "string"}},
  797. ... },
  798. ... "required": ["location", "activity", "animals_seen", "animals"],
  799. ... },
  800. ... }
  801. >>> response = client.chat_completion(
  802. ... messages=messages,
  803. ... response_format=response_format,
  804. ... max_tokens=500,
  805. ... )
  806. >>> response.choices[0].message.content
  807. '{\n\n"activity": "bike ride",\n"animals": ["puppy", "cat", "raccoon"],\n"animals_seen": 3,\n"location": "park"}'
  808. ```
  809. """
  810. # Since `chat_completion(..., model=xxx)` is also a payload parameter for the server, we need to handle 'model' differently.
  811. # `self.model` takes precedence over 'model' argument for building URL.
  812. # `model` takes precedence for payload value.
  813. model_id_or_url = self.model or model
  814. payload_model = model or self.model
  815. # Get the provider helper
  816. provider_helper = get_provider_helper(
  817. self.provider,
  818. task="conversational",
  819. model=model_id_or_url
  820. if model_id_or_url is not None and model_id_or_url.startswith(("http://", "https://"))
  821. else payload_model,
  822. )
  823. # Prepare the payload
  824. parameters = {
  825. "model": payload_model,
  826. "frequency_penalty": frequency_penalty,
  827. "logit_bias": logit_bias,
  828. "logprobs": logprobs,
  829. "max_tokens": max_tokens,
  830. "n": n,
  831. "presence_penalty": presence_penalty,
  832. "response_format": response_format,
  833. "seed": seed,
  834. "stop": stop,
  835. "temperature": temperature,
  836. "tool_choice": tool_choice,
  837. "tool_prompt": tool_prompt,
  838. "tools": tools,
  839. "top_logprobs": top_logprobs,
  840. "top_p": top_p,
  841. "stream": stream,
  842. "stream_options": stream_options,
  843. **(extra_body or {}),
  844. }
  845. request_parameters = provider_helper.prepare_request(
  846. inputs=messages,
  847. parameters=parameters,
  848. headers=self.headers,
  849. model=model_id_or_url,
  850. api_key=self.token,
  851. )
  852. data = self._inner_post(request_parameters, stream=stream)
  853. if stream:
  854. return _stream_chat_completion_response(data) # type: ignore[arg-type]
  855. return ChatCompletionOutput.parse_obj_as_instance(data) # type: ignore[arg-type]
  856. def document_question_answering(
  857. self,
  858. image: ContentT,
  859. question: str,
  860. *,
  861. model: Optional[str] = None,
  862. doc_stride: Optional[int] = None,
  863. handle_impossible_answer: Optional[bool] = None,
  864. lang: Optional[str] = None,
  865. max_answer_len: Optional[int] = None,
  866. max_question_len: Optional[int] = None,
  867. max_seq_len: Optional[int] = None,
  868. top_k: Optional[int] = None,
  869. word_boxes: Optional[List[Union[List[float], str]]] = None,
  870. ) -> List[DocumentQuestionAnsweringOutputElement]:
  871. """
  872. Answer questions on document images.
  873. Args:
  874. image (`Union[str, Path, bytes, BinaryIO]`):
  875. The input image for the context. It can be raw bytes, an image file, or a URL to an online image.
  876. question (`str`):
  877. Question to be answered.
  878. model (`str`, *optional*):
  879. The model to use for the document question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  880. a deployed Inference Endpoint. If not provided, the default recommended document question answering model will be used.
  881. Defaults to None.
  882. doc_stride (`int`, *optional*):
  883. If the words in the document are too long to fit with the question for the model, it will be split in
  884. several chunks with some overlap. This argument controls the size of that overlap.
  885. handle_impossible_answer (`bool`, *optional*):
  886. Whether to accept impossible as an answer
  887. lang (`str`, *optional*):
  888. Language to use while running OCR. Defaults to english.
  889. max_answer_len (`int`, *optional*):
  890. The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
  891. max_question_len (`int`, *optional*):
  892. The maximum length of the question after tokenization. It will be truncated if needed.
  893. max_seq_len (`int`, *optional*):
  894. The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
  895. model. The context will be split in several chunks (using doc_stride as overlap) if needed.
  896. top_k (`int`, *optional*):
  897. The number of answers to return (will be chosen by order of likelihood). Can return less than top_k
  898. answers if there are not enough options available within the context.
  899. word_boxes (`List[Union[List[float], str`, *optional*):
  900. A list of words and bounding boxes (normalized 0->1000). If provided, the inference will skip the OCR
  901. step and use the provided bounding boxes instead.
  902. Returns:
  903. `List[DocumentQuestionAnsweringOutputElement]`: a list of [`DocumentQuestionAnsweringOutputElement`] items containing the predicted label, associated probability, word ids, and page number.
  904. Raises:
  905. [`InferenceTimeoutError`]:
  906. If the model is unavailable or the request times out.
  907. `HTTPError`:
  908. If the request fails with an HTTP error status code other than HTTP 503.
  909. Example:
  910. ```py
  911. >>> from huggingface_hub import InferenceClient
  912. >>> client = InferenceClient()
  913. >>> client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
  914. [DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]
  915. ```
  916. """
  917. model_id = model or self.model
  918. provider_helper = get_provider_helper(self.provider, task="document-question-answering", model=model_id)
  919. inputs: Dict[str, Any] = {"question": question, "image": _b64_encode(image)}
  920. request_parameters = provider_helper.prepare_request(
  921. inputs=inputs,
  922. parameters={
  923. "doc_stride": doc_stride,
  924. "handle_impossible_answer": handle_impossible_answer,
  925. "lang": lang,
  926. "max_answer_len": max_answer_len,
  927. "max_question_len": max_question_len,
  928. "max_seq_len": max_seq_len,
  929. "top_k": top_k,
  930. "word_boxes": word_boxes,
  931. },
  932. headers=self.headers,
  933. model=model_id,
  934. api_key=self.token,
  935. )
  936. response = self._inner_post(request_parameters)
  937. return DocumentQuestionAnsweringOutputElement.parse_obj_as_list(response)
  938. def feature_extraction(
  939. self,
  940. text: str,
  941. *,
  942. normalize: Optional[bool] = None,
  943. prompt_name: Optional[str] = None,
  944. truncate: Optional[bool] = None,
  945. truncation_direction: Optional[Literal["Left", "Right"]] = None,
  946. model: Optional[str] = None,
  947. ) -> "np.ndarray":
  948. """
  949. Generate embeddings for a given text.
  950. Args:
  951. text (`str`):
  952. The text to embed.
  953. model (`str`, *optional*):
  954. The model to use for the feature extraction task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  955. a deployed Inference Endpoint. If not provided, the default recommended feature extraction model will be used.
  956. Defaults to None.
  957. normalize (`bool`, *optional*):
  958. Whether to normalize the embeddings or not.
  959. Only available on server powered by Text-Embedding-Inference.
  960. prompt_name (`str`, *optional*):
  961. The name of the prompt that should be used by for encoding. If not set, no prompt will be applied.
  962. Must be a key in the `Sentence Transformers` configuration `prompts` dictionary.
  963. For example if ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ",...},
  964. then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?"
  965. because the prompt text will be prepended before any text to encode.
  966. truncate (`bool`, *optional*):
  967. Whether to truncate the embeddings or not.
  968. Only available on server powered by Text-Embedding-Inference.
  969. truncation_direction (`Literal["Left", "Right"]`, *optional*):
  970. Which side of the input should be truncated when `truncate=True` is passed.
  971. Returns:
  972. `np.ndarray`: The embedding representing the input text as a float32 numpy array.
  973. Raises:
  974. [`InferenceTimeoutError`]:
  975. If the model is unavailable or the request times out.
  976. `HTTPError`:
  977. If the request fails with an HTTP error status code other than HTTP 503.
  978. Example:
  979. ```py
  980. >>> from huggingface_hub import InferenceClient
  981. >>> client = InferenceClient()
  982. >>> client.feature_extraction("Hi, who are you?")
  983. array([[ 2.424802 , 2.93384 , 1.1750331 , ..., 1.240499, -0.13776633, -0.7889173 ],
  984. [-0.42943227, -0.6364878 , -1.693462 , ..., 0.41978157, -2.4336355 , 0.6162071 ],
  985. ...,
  986. [ 0.28552425, -0.928395 , -1.2077185 , ..., 0.76810825, -2.1069427 , 0.6236161 ]], dtype=float32)
  987. ```
  988. """
  989. model_id = model or self.model
  990. provider_helper = get_provider_helper(self.provider, task="feature-extraction", model=model_id)
  991. request_parameters = provider_helper.prepare_request(
  992. inputs=text,
  993. parameters={
  994. "normalize": normalize,
  995. "prompt_name": prompt_name,
  996. "truncate": truncate,
  997. "truncation_direction": truncation_direction,
  998. },
  999. headers=self.headers,
  1000. model=model_id,
  1001. api_key=self.token,
  1002. )
  1003. response = self._inner_post(request_parameters)
  1004. np = _import_numpy()
  1005. return np.array(provider_helper.get_response(response), dtype="float32")
  1006. def fill_mask(
  1007. self,
  1008. text: str,
  1009. *,
  1010. model: Optional[str] = None,
  1011. targets: Optional[List[str]] = None,
  1012. top_k: Optional[int] = None,
  1013. ) -> List[FillMaskOutputElement]:
  1014. """
  1015. Fill in a hole with a missing word (token to be precise).
  1016. Args:
  1017. text (`str`):
  1018. a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask).
  1019. model (`str`, *optional*):
  1020. The model to use for the fill mask task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  1021. a deployed Inference Endpoint. If not provided, the default recommended fill mask model will be used.
  1022. targets (`List[str`, *optional*):
  1023. When passed, the model will limit the scores to the passed targets instead of looking up in the whole
  1024. vocabulary. If the provided targets are not in the model vocab, they will be tokenized and the first
  1025. resulting token will be used (with a warning, and that might be slower).
  1026. top_k (`int`, *optional*):
  1027. When passed, overrides the number of predictions to return.
  1028. Returns:
  1029. `List[FillMaskOutputElement]`: a list of [`FillMaskOutputElement`] items containing the predicted label, associated
  1030. probability, token reference, and completed text.
  1031. Raises:
  1032. [`InferenceTimeoutError`]:
  1033. If the model is unavailable or the request times out.
  1034. `HTTPError`:
  1035. If the request fails with an HTTP error status code other than HTTP 503.
  1036. Example:
  1037. ```py
  1038. >>> from huggingface_hub import InferenceClient
  1039. >>> client = InferenceClient()
  1040. >>> client.fill_mask("The goal of life is <mask>.")
  1041. [
  1042. FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
  1043. FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
  1044. ]
  1045. ```
  1046. """
  1047. model_id = model or self.model
  1048. provider_helper = get_provider_helper(self.provider, task="fill-mask", model=model_id)
  1049. request_parameters = provider_helper.prepare_request(
  1050. inputs=text,
  1051. parameters={"targets": targets, "top_k": top_k},
  1052. headers=self.headers,
  1053. model=model_id,
  1054. api_key=self.token,
  1055. )
  1056. response = self._inner_post(request_parameters)
  1057. return FillMaskOutputElement.parse_obj_as_list(response)
  1058. def image_classification(
  1059. self,
  1060. image: ContentT,
  1061. *,
  1062. model: Optional[str] = None,
  1063. function_to_apply: Optional["ImageClassificationOutputTransform"] = None,
  1064. top_k: Optional[int] = None,
  1065. ) -> List[ImageClassificationOutputElement]:
  1066. """
  1067. Perform image classification on the given image using the specified model.
  1068. Args:
  1069. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  1070. The image to classify. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  1071. model (`str`, *optional*):
  1072. The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a
  1073. deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used.
  1074. function_to_apply (`"ImageClassificationOutputTransform"`, *optional*):
  1075. The function to apply to the model outputs in order to retrieve the scores.
  1076. top_k (`int`, *optional*):
  1077. When specified, limits the output to the top K most probable classes.
  1078. Returns:
  1079. `List[ImageClassificationOutputElement]`: a list of [`ImageClassificationOutputElement`] items containing the predicted label and associated probability.
  1080. Raises:
  1081. [`InferenceTimeoutError`]:
  1082. If the model is unavailable or the request times out.
  1083. `HTTPError`:
  1084. If the request fails with an HTTP error status code other than HTTP 503.
  1085. Example:
  1086. ```py
  1087. >>> from huggingface_hub import InferenceClient
  1088. >>> client = InferenceClient()
  1089. >>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
  1090. [ImageClassificationOutputElement(label='Blenheim spaniel', score=0.9779096841812134), ...]
  1091. ```
  1092. """
  1093. model_id = model or self.model
  1094. provider_helper = get_provider_helper(self.provider, task="image-classification", model=model_id)
  1095. request_parameters = provider_helper.prepare_request(
  1096. inputs=image,
  1097. parameters={"function_to_apply": function_to_apply, "top_k": top_k},
  1098. headers=self.headers,
  1099. model=model_id,
  1100. api_key=self.token,
  1101. )
  1102. response = self._inner_post(request_parameters)
  1103. return ImageClassificationOutputElement.parse_obj_as_list(response)
  1104. def image_segmentation(
  1105. self,
  1106. image: ContentT,
  1107. *,
  1108. model: Optional[str] = None,
  1109. mask_threshold: Optional[float] = None,
  1110. overlap_mask_area_threshold: Optional[float] = None,
  1111. subtask: Optional["ImageSegmentationSubtask"] = None,
  1112. threshold: Optional[float] = None,
  1113. ) -> List[ImageSegmentationOutputElement]:
  1114. """
  1115. Perform image segmentation on the given image using the specified model.
  1116. > [!WARNING]
  1117. > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
  1118. Args:
  1119. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  1120. The image to segment. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  1121. model (`str`, *optional*):
  1122. The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a
  1123. deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used.
  1124. mask_threshold (`float`, *optional*):
  1125. Threshold to use when turning the predicted masks into binary values.
  1126. overlap_mask_area_threshold (`float`, *optional*):
  1127. Mask overlap threshold to eliminate small, disconnected segments.
  1128. subtask (`"ImageSegmentationSubtask"`, *optional*):
  1129. Segmentation task to be performed, depending on model capabilities.
  1130. threshold (`float`, *optional*):
  1131. Probability threshold to filter out predicted masks.
  1132. Returns:
  1133. `List[ImageSegmentationOutputElement]`: A list of [`ImageSegmentationOutputElement`] items containing the segmented masks and associated attributes.
  1134. Raises:
  1135. [`InferenceTimeoutError`]:
  1136. If the model is unavailable or the request times out.
  1137. `HTTPError`:
  1138. If the request fails with an HTTP error status code other than HTTP 503.
  1139. Example:
  1140. ```py
  1141. >>> from huggingface_hub import InferenceClient
  1142. >>> client = InferenceClient()
  1143. >>> client.image_segmentation("cat.jpg")
  1144. [ImageSegmentationOutputElement(score=0.989008, label='LABEL_184', mask=<PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>), ...]
  1145. ```
  1146. """
  1147. model_id = model or self.model
  1148. provider_helper = get_provider_helper(self.provider, task="image-segmentation", model=model_id)
  1149. request_parameters = provider_helper.prepare_request(
  1150. inputs=image,
  1151. parameters={
  1152. "mask_threshold": mask_threshold,
  1153. "overlap_mask_area_threshold": overlap_mask_area_threshold,
  1154. "subtask": subtask,
  1155. "threshold": threshold,
  1156. },
  1157. headers=self.headers,
  1158. model=model_id,
  1159. api_key=self.token,
  1160. )
  1161. response = self._inner_post(request_parameters)
  1162. output = ImageSegmentationOutputElement.parse_obj_as_list(response)
  1163. for item in output:
  1164. item.mask = _b64_to_image(item.mask) # type: ignore [assignment]
  1165. return output
  1166. def image_to_image(
  1167. self,
  1168. image: ContentT,
  1169. prompt: Optional[str] = None,
  1170. *,
  1171. negative_prompt: Optional[str] = None,
  1172. num_inference_steps: Optional[int] = None,
  1173. guidance_scale: Optional[float] = None,
  1174. model: Optional[str] = None,
  1175. target_size: Optional[ImageToImageTargetSize] = None,
  1176. **kwargs,
  1177. ) -> "Image":
  1178. """
  1179. Perform image-to-image translation using a specified model.
  1180. > [!WARNING]
  1181. > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
  1182. Args:
  1183. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  1184. The input image for translation. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  1185. prompt (`str`, *optional*):
  1186. The text prompt to guide the image generation.
  1187. negative_prompt (`str`, *optional*):
  1188. One prompt to guide what NOT to include in image generation.
  1189. num_inference_steps (`int`, *optional*):
  1190. For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher
  1191. quality image at the expense of slower inference.
  1192. guidance_scale (`float`, *optional*):
  1193. For diffusion models. A higher guidance scale value encourages the model to generate images closely
  1194. linked to the text prompt at the expense of lower image quality.
  1195. model (`str`, *optional*):
  1196. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  1197. Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
  1198. target_size (`ImageToImageTargetSize`, *optional*):
  1199. The size in pixels of the output image. This parameter is only supported by some providers and for
  1200. specific models. It will be ignored when unsupported.
  1201. Returns:
  1202. `Image`: The translated image.
  1203. Raises:
  1204. [`InferenceTimeoutError`]:
  1205. If the model is unavailable or the request times out.
  1206. `HTTPError`:
  1207. If the request fails with an HTTP error status code other than HTTP 503.
  1208. Example:
  1209. ```py
  1210. >>> from huggingface_hub import InferenceClient
  1211. >>> client = InferenceClient()
  1212. >>> image = client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
  1213. >>> image.save("tiger.jpg")
  1214. ```
  1215. """
  1216. model_id = model or self.model
  1217. provider_helper = get_provider_helper(self.provider, task="image-to-image", model=model_id)
  1218. request_parameters = provider_helper.prepare_request(
  1219. inputs=image,
  1220. parameters={
  1221. "prompt": prompt,
  1222. "negative_prompt": negative_prompt,
  1223. "target_size": target_size,
  1224. "num_inference_steps": num_inference_steps,
  1225. "guidance_scale": guidance_scale,
  1226. **kwargs,
  1227. },
  1228. headers=self.headers,
  1229. model=model_id,
  1230. api_key=self.token,
  1231. )
  1232. response = self._inner_post(request_parameters)
  1233. response = provider_helper.get_response(response, request_parameters)
  1234. return _bytes_to_image(response)
  1235. def image_to_video(
  1236. self,
  1237. image: ContentT,
  1238. *,
  1239. model: Optional[str] = None,
  1240. prompt: Optional[str] = None,
  1241. negative_prompt: Optional[str] = None,
  1242. num_frames: Optional[float] = None,
  1243. num_inference_steps: Optional[int] = None,
  1244. guidance_scale: Optional[float] = None,
  1245. seed: Optional[int] = None,
  1246. target_size: Optional[ImageToVideoTargetSize] = None,
  1247. **kwargs,
  1248. ) -> bytes:
  1249. """
  1250. Generate a video from an input image.
  1251. Args:
  1252. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  1253. The input image to generate a video from. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  1254. model (`str`, *optional*):
  1255. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  1256. Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
  1257. prompt (`str`, *optional*):
  1258. The text prompt to guide the video generation.
  1259. negative_prompt (`str`, *optional*):
  1260. One prompt to guide what NOT to include in video generation.
  1261. num_frames (`float`, *optional*):
  1262. The num_frames parameter determines how many video frames are generated.
  1263. num_inference_steps (`int`, *optional*):
  1264. For diffusion models. The number of denoising steps. More denoising steps usually lead to a higher
  1265. quality image at the expense of slower inference.
  1266. guidance_scale (`float`, *optional*):
  1267. For diffusion models. A higher guidance scale value encourages the model to generate videos closely
  1268. linked to the text prompt at the expense of lower image quality.
  1269. seed (`int`, *optional*):
  1270. The seed to use for the video generation.
  1271. target_size (`ImageToVideoTargetSize`, *optional*):
  1272. The size in pixel of the output video frames.
  1273. num_inference_steps (`int`, *optional*):
  1274. The number of denoising steps. More denoising steps usually lead to a higher quality video at the
  1275. expense of slower inference.
  1276. seed (`int`, *optional*):
  1277. Seed for the random number generator.
  1278. Returns:
  1279. `bytes`: The generated video.
  1280. Examples:
  1281. ```py
  1282. >>> from huggingface_hub import InferenceClient
  1283. >>> client = InferenceClient()
  1284. >>> video = client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
  1285. >>> with open("tiger.mp4", "wb") as f:
  1286. ... f.write(video)
  1287. ```
  1288. """
  1289. model_id = model or self.model
  1290. provider_helper = get_provider_helper(self.provider, task="image-to-video", model=model_id)
  1291. request_parameters = provider_helper.prepare_request(
  1292. inputs=image,
  1293. parameters={
  1294. "prompt": prompt,
  1295. "negative_prompt": negative_prompt,
  1296. "num_frames": num_frames,
  1297. "num_inference_steps": num_inference_steps,
  1298. "guidance_scale": guidance_scale,
  1299. "seed": seed,
  1300. "target_size": target_size,
  1301. **kwargs,
  1302. },
  1303. headers=self.headers,
  1304. model=model_id,
  1305. api_key=self.token,
  1306. )
  1307. response = self._inner_post(request_parameters)
  1308. response = provider_helper.get_response(response, request_parameters)
  1309. return response
  1310. def image_to_text(self, image: ContentT, *, model: Optional[str] = None) -> ImageToTextOutput:
  1311. """
  1312. Takes an input image and return text.
  1313. Models can have very different outputs depending on your use case (image captioning, optical character recognition
  1314. (OCR), Pix2Struct, etc). Please have a look to the model card to learn more about a model's specificities.
  1315. Args:
  1316. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  1317. The input image to caption. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  1318. model (`str`, *optional*):
  1319. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  1320. Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
  1321. Returns:
  1322. [`ImageToTextOutput`]: The generated text.
  1323. Raises:
  1324. [`InferenceTimeoutError`]:
  1325. If the model is unavailable or the request times out.
  1326. `HTTPError`:
  1327. If the request fails with an HTTP error status code other than HTTP 503.
  1328. Example:
  1329. ```py
  1330. >>> from huggingface_hub import InferenceClient
  1331. >>> client = InferenceClient()
  1332. >>> client.image_to_text("cat.jpg")
  1333. 'a cat standing in a grassy field '
  1334. >>> client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
  1335. 'a dog laying on the grass next to a flower pot '
  1336. ```
  1337. """
  1338. model_id = model or self.model
  1339. provider_helper = get_provider_helper(self.provider, task="image-to-text", model=model_id)
  1340. request_parameters = provider_helper.prepare_request(
  1341. inputs=image,
  1342. parameters={},
  1343. headers=self.headers,
  1344. model=model_id,
  1345. api_key=self.token,
  1346. )
  1347. response = self._inner_post(request_parameters)
  1348. output_list: List[ImageToTextOutput] = ImageToTextOutput.parse_obj_as_list(response)
  1349. return output_list[0]
  1350. def object_detection(
  1351. self, image: ContentT, *, model: Optional[str] = None, threshold: Optional[float] = None
  1352. ) -> List[ObjectDetectionOutputElement]:
  1353. """
  1354. Perform object detection on the given image using the specified model.
  1355. > [!WARNING]
  1356. > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
  1357. Args:
  1358. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  1359. The image to detect objects on. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  1360. model (`str`, *optional*):
  1361. The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a
  1362. deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used.
  1363. threshold (`float`, *optional*):
  1364. The probability necessary to make a prediction.
  1365. Returns:
  1366. `List[ObjectDetectionOutputElement]`: A list of [`ObjectDetectionOutputElement`] items containing the bounding boxes and associated attributes.
  1367. Raises:
  1368. [`InferenceTimeoutError`]:
  1369. If the model is unavailable or the request times out.
  1370. `HTTPError`:
  1371. If the request fails with an HTTP error status code other than HTTP 503.
  1372. `ValueError`:
  1373. If the request output is not a List.
  1374. Example:
  1375. ```py
  1376. >>> from huggingface_hub import InferenceClient
  1377. >>> client = InferenceClient()
  1378. >>> client.object_detection("people.jpg")
  1379. [ObjectDetectionOutputElement(score=0.9486683011054993, label='person', box=ObjectDetectionBoundingBox(xmin=59, ymin=39, xmax=420, ymax=510)), ...]
  1380. ```
  1381. """
  1382. model_id = model or self.model
  1383. provider_helper = get_provider_helper(self.provider, task="object-detection", model=model_id)
  1384. request_parameters = provider_helper.prepare_request(
  1385. inputs=image,
  1386. parameters={"threshold": threshold},
  1387. headers=self.headers,
  1388. model=model_id,
  1389. api_key=self.token,
  1390. )
  1391. response = self._inner_post(request_parameters)
  1392. return ObjectDetectionOutputElement.parse_obj_as_list(response)
  1393. def question_answering(
  1394. self,
  1395. question: str,
  1396. context: str,
  1397. *,
  1398. model: Optional[str] = None,
  1399. align_to_words: Optional[bool] = None,
  1400. doc_stride: Optional[int] = None,
  1401. handle_impossible_answer: Optional[bool] = None,
  1402. max_answer_len: Optional[int] = None,
  1403. max_question_len: Optional[int] = None,
  1404. max_seq_len: Optional[int] = None,
  1405. top_k: Optional[int] = None,
  1406. ) -> Union[QuestionAnsweringOutputElement, List[QuestionAnsweringOutputElement]]:
  1407. """
  1408. Retrieve the answer to a question from a given text.
  1409. Args:
  1410. question (`str`):
  1411. Question to be answered.
  1412. context (`str`):
  1413. The context of the question.
  1414. model (`str`):
  1415. The model to use for the question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  1416. a deployed Inference Endpoint.
  1417. align_to_words (`bool`, *optional*):
  1418. Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt
  1419. on non-space-separated languages (like Japanese or Chinese)
  1420. doc_stride (`int`, *optional*):
  1421. If the context is too long to fit with the question for the model, it will be split in several chunks
  1422. with some overlap. This argument controls the size of that overlap.
  1423. handle_impossible_answer (`bool`, *optional*):
  1424. Whether to accept impossible as an answer.
  1425. max_answer_len (`int`, *optional*):
  1426. The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
  1427. max_question_len (`int`, *optional*):
  1428. The maximum length of the question after tokenization. It will be truncated if needed.
  1429. max_seq_len (`int`, *optional*):
  1430. The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
  1431. model. The context will be split in several chunks (using docStride as overlap) if needed.
  1432. top_k (`int`, *optional*):
  1433. The number of answers to return (will be chosen by order of likelihood). Note that we return less than
  1434. topk answers if there are not enough options available within the context.
  1435. Returns:
  1436. Union[`QuestionAnsweringOutputElement`, List[`QuestionAnsweringOutputElement`]]:
  1437. When top_k is 1 or not provided, it returns a single `QuestionAnsweringOutputElement`.
  1438. When top_k is greater than 1, it returns a list of `QuestionAnsweringOutputElement`.
  1439. Raises:
  1440. [`InferenceTimeoutError`]:
  1441. If the model is unavailable or the request times out.
  1442. `HTTPError`:
  1443. If the request fails with an HTTP error status code other than HTTP 503.
  1444. Example:
  1445. ```py
  1446. >>> from huggingface_hub import InferenceClient
  1447. >>> client = InferenceClient()
  1448. >>> client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
  1449. QuestionAnsweringOutputElement(answer='Clara', end=16, score=0.9326565265655518, start=11)
  1450. ```
  1451. """
  1452. model_id = model or self.model
  1453. provider_helper = get_provider_helper(self.provider, task="question-answering", model=model_id)
  1454. request_parameters = provider_helper.prepare_request(
  1455. inputs={"question": question, "context": context},
  1456. parameters={
  1457. "align_to_words": align_to_words,
  1458. "doc_stride": doc_stride,
  1459. "handle_impossible_answer": handle_impossible_answer,
  1460. "max_answer_len": max_answer_len,
  1461. "max_question_len": max_question_len,
  1462. "max_seq_len": max_seq_len,
  1463. "top_k": top_k,
  1464. },
  1465. headers=self.headers,
  1466. model=model_id,
  1467. api_key=self.token,
  1468. )
  1469. response = self._inner_post(request_parameters)
  1470. # Parse the response as a single `QuestionAnsweringOutputElement` when top_k is 1 or not provided, or a list of `QuestionAnsweringOutputElement` to ensure backward compatibility.
  1471. output = QuestionAnsweringOutputElement.parse_obj(response)
  1472. return output
  1473. def sentence_similarity(
  1474. self, sentence: str, other_sentences: List[str], *, model: Optional[str] = None
  1475. ) -> List[float]:
  1476. """
  1477. Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings.
  1478. Args:
  1479. sentence (`str`):
  1480. The main sentence to compare to others.
  1481. other_sentences (`List[str]`):
  1482. The list of sentences to compare to.
  1483. model (`str`, *optional*):
  1484. The model to use for the sentence similarity task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  1485. a deployed Inference Endpoint. If not provided, the default recommended sentence similarity model will be used.
  1486. Defaults to None.
  1487. Returns:
  1488. `List[float]`: The similarity scores between the main sentence and the given comparison sentences.
  1489. Raises:
  1490. [`InferenceTimeoutError`]:
  1491. If the model is unavailable or the request times out.
  1492. `HTTPError`:
  1493. If the request fails with an HTTP error status code other than HTTP 503.
  1494. Example:
  1495. ```py
  1496. >>> from huggingface_hub import InferenceClient
  1497. >>> client = InferenceClient()
  1498. >>> client.sentence_similarity(
  1499. ... "Machine learning is so easy.",
  1500. ... other_sentences=[
  1501. ... "Deep learning is so straightforward.",
  1502. ... "This is so difficult, like rocket science.",
  1503. ... "I can't believe how much I struggled with this.",
  1504. ... ],
  1505. ... )
  1506. [0.7785726189613342, 0.45876261591911316, 0.2906220555305481]
  1507. ```
  1508. """
  1509. model_id = model or self.model
  1510. provider_helper = get_provider_helper(self.provider, task="sentence-similarity", model=model_id)
  1511. request_parameters = provider_helper.prepare_request(
  1512. inputs={"source_sentence": sentence, "sentences": other_sentences},
  1513. parameters={},
  1514. extra_payload={},
  1515. headers=self.headers,
  1516. model=model_id,
  1517. api_key=self.token,
  1518. )
  1519. response = self._inner_post(request_parameters)
  1520. return _bytes_to_list(response)
  1521. def summarization(
  1522. self,
  1523. text: str,
  1524. *,
  1525. model: Optional[str] = None,
  1526. clean_up_tokenization_spaces: Optional[bool] = None,
  1527. generate_parameters: Optional[Dict[str, Any]] = None,
  1528. truncation: Optional["SummarizationTruncationStrategy"] = None,
  1529. ) -> SummarizationOutput:
  1530. """
  1531. Generate a summary of a given text using a specified model.
  1532. Args:
  1533. text (`str`):
  1534. The input text to summarize.
  1535. model (`str`, *optional*):
  1536. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  1537. Inference Endpoint. If not provided, the default recommended model for summarization will be used.
  1538. clean_up_tokenization_spaces (`bool`, *optional*):
  1539. Whether to clean up the potential extra spaces in the text output.
  1540. generate_parameters (`Dict[str, Any]`, *optional*):
  1541. Additional parametrization of the text generation algorithm.
  1542. truncation (`"SummarizationTruncationStrategy"`, *optional*):
  1543. The truncation strategy to use.
  1544. Returns:
  1545. [`SummarizationOutput`]: The generated summary text.
  1546. Raises:
  1547. [`InferenceTimeoutError`]:
  1548. If the model is unavailable or the request times out.
  1549. `HTTPError`:
  1550. If the request fails with an HTTP error status code other than HTTP 503.
  1551. Example:
  1552. ```py
  1553. >>> from huggingface_hub import InferenceClient
  1554. >>> client = InferenceClient()
  1555. >>> client.summarization("The Eiffel tower...")
  1556. SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")
  1557. ```
  1558. """
  1559. parameters = {
  1560. "clean_up_tokenization_spaces": clean_up_tokenization_spaces,
  1561. "generate_parameters": generate_parameters,
  1562. "truncation": truncation,
  1563. }
  1564. model_id = model or self.model
  1565. provider_helper = get_provider_helper(self.provider, task="summarization", model=model_id)
  1566. request_parameters = provider_helper.prepare_request(
  1567. inputs=text,
  1568. parameters=parameters,
  1569. headers=self.headers,
  1570. model=model_id,
  1571. api_key=self.token,
  1572. )
  1573. response = self._inner_post(request_parameters)
  1574. return SummarizationOutput.parse_obj_as_list(response)[0]
  1575. def table_question_answering(
  1576. self,
  1577. table: Dict[str, Any],
  1578. query: str,
  1579. *,
  1580. model: Optional[str] = None,
  1581. padding: Optional["Padding"] = None,
  1582. sequential: Optional[bool] = None,
  1583. truncation: Optional[bool] = None,
  1584. ) -> TableQuestionAnsweringOutputElement:
  1585. """
  1586. Retrieve the answer to a question from information given in a table.
  1587. Args:
  1588. table (`str`):
  1589. A table of data represented as a dict of lists where entries are headers and the lists are all the
  1590. values, all lists must have the same size.
  1591. query (`str`):
  1592. The query in plain text that you want to ask the table.
  1593. model (`str`):
  1594. The model to use for the table-question-answering task. Can be a model ID hosted on the Hugging Face
  1595. Hub or a URL to a deployed Inference Endpoint.
  1596. padding (`"Padding"`, *optional*):
  1597. Activates and controls padding.
  1598. sequential (`bool`, *optional*):
  1599. Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
  1600. inference to be done sequentially to extract relations within sequences, given their conversational
  1601. nature.
  1602. truncation (`bool`, *optional*):
  1603. Activates and controls truncation.
  1604. Returns:
  1605. [`TableQuestionAnsweringOutputElement`]: a table question answering output containing the answer, coordinates, cells and the aggregator used.
  1606. Raises:
  1607. [`InferenceTimeoutError`]:
  1608. If the model is unavailable or the request times out.
  1609. `HTTPError`:
  1610. If the request fails with an HTTP error status code other than HTTP 503.
  1611. Example:
  1612. ```py
  1613. >>> from huggingface_hub import InferenceClient
  1614. >>> client = InferenceClient()
  1615. >>> query = "How many stars does the transformers repository have?"
  1616. >>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
  1617. >>> client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
  1618. TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')
  1619. ```
  1620. """
  1621. model_id = model or self.model
  1622. provider_helper = get_provider_helper(self.provider, task="table-question-answering", model=model_id)
  1623. request_parameters = provider_helper.prepare_request(
  1624. inputs={"query": query, "table": table},
  1625. parameters={"model": model, "padding": padding, "sequential": sequential, "truncation": truncation},
  1626. headers=self.headers,
  1627. model=model_id,
  1628. api_key=self.token,
  1629. )
  1630. response = self._inner_post(request_parameters)
  1631. return TableQuestionAnsweringOutputElement.parse_obj_as_instance(response)
  1632. def tabular_classification(self, table: Dict[str, Any], *, model: Optional[str] = None) -> List[str]:
  1633. """
  1634. Classifying a target category (a group) based on a set of attributes.
  1635. Args:
  1636. table (`Dict[str, Any]`):
  1637. Set of attributes to classify.
  1638. model (`str`, *optional*):
  1639. The model to use for the tabular classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  1640. a deployed Inference Endpoint. If not provided, the default recommended tabular classification model will be used.
  1641. Defaults to None.
  1642. Returns:
  1643. `List`: a list of labels, one per row in the initial table.
  1644. Raises:
  1645. [`InferenceTimeoutError`]:
  1646. If the model is unavailable or the request times out.
  1647. `HTTPError`:
  1648. If the request fails with an HTTP error status code other than HTTP 503.
  1649. Example:
  1650. ```py
  1651. >>> from huggingface_hub import InferenceClient
  1652. >>> client = InferenceClient()
  1653. >>> table = {
  1654. ... "fixed_acidity": ["7.4", "7.8", "10.3"],
  1655. ... "volatile_acidity": ["0.7", "0.88", "0.32"],
  1656. ... "citric_acid": ["0", "0", "0.45"],
  1657. ... "residual_sugar": ["1.9", "2.6", "6.4"],
  1658. ... "chlorides": ["0.076", "0.098", "0.073"],
  1659. ... "free_sulfur_dioxide": ["11", "25", "5"],
  1660. ... "total_sulfur_dioxide": ["34", "67", "13"],
  1661. ... "density": ["0.9978", "0.9968", "0.9976"],
  1662. ... "pH": ["3.51", "3.2", "3.23"],
  1663. ... "sulphates": ["0.56", "0.68", "0.82"],
  1664. ... "alcohol": ["9.4", "9.8", "12.6"],
  1665. ... }
  1666. >>> client.tabular_classification(table=table, model="julien-c/wine-quality")
  1667. ["5", "5", "5"]
  1668. ```
  1669. """
  1670. model_id = model or self.model
  1671. provider_helper = get_provider_helper(self.provider, task="tabular-classification", model=model_id)
  1672. request_parameters = provider_helper.prepare_request(
  1673. inputs=None,
  1674. extra_payload={"table": table},
  1675. parameters={},
  1676. headers=self.headers,
  1677. model=model_id,
  1678. api_key=self.token,
  1679. )
  1680. response = self._inner_post(request_parameters)
  1681. return _bytes_to_list(response)
  1682. def tabular_regression(self, table: Dict[str, Any], *, model: Optional[str] = None) -> List[float]:
  1683. """
  1684. Predicting a numerical target value given a set of attributes/features in a table.
  1685. Args:
  1686. table (`Dict[str, Any]`):
  1687. Set of attributes stored in a table. The attributes used to predict the target can be both numerical and categorical.
  1688. model (`str`, *optional*):
  1689. The model to use for the tabular regression task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  1690. a deployed Inference Endpoint. If not provided, the default recommended tabular regression model will be used.
  1691. Defaults to None.
  1692. Returns:
  1693. `List`: a list of predicted numerical target values.
  1694. Raises:
  1695. [`InferenceTimeoutError`]:
  1696. If the model is unavailable or the request times out.
  1697. `HTTPError`:
  1698. If the request fails with an HTTP error status code other than HTTP 503.
  1699. Example:
  1700. ```py
  1701. >>> from huggingface_hub import InferenceClient
  1702. >>> client = InferenceClient()
  1703. >>> table = {
  1704. ... "Height": ["11.52", "12.48", "12.3778"],
  1705. ... "Length1": ["23.2", "24", "23.9"],
  1706. ... "Length2": ["25.4", "26.3", "26.5"],
  1707. ... "Length3": ["30", "31.2", "31.1"],
  1708. ... "Species": ["Bream", "Bream", "Bream"],
  1709. ... "Width": ["4.02", "4.3056", "4.6961"],
  1710. ... }
  1711. >>> client.tabular_regression(table, model="scikit-learn/Fish-Weight")
  1712. [110, 120, 130]
  1713. ```
  1714. """
  1715. model_id = model or self.model
  1716. provider_helper = get_provider_helper(self.provider, task="tabular-regression", model=model_id)
  1717. request_parameters = provider_helper.prepare_request(
  1718. inputs=None,
  1719. parameters={},
  1720. extra_payload={"table": table},
  1721. headers=self.headers,
  1722. model=model_id,
  1723. api_key=self.token,
  1724. )
  1725. response = self._inner_post(request_parameters)
  1726. return _bytes_to_list(response)
  1727. def text_classification(
  1728. self,
  1729. text: str,
  1730. *,
  1731. model: Optional[str] = None,
  1732. top_k: Optional[int] = None,
  1733. function_to_apply: Optional["TextClassificationOutputTransform"] = None,
  1734. ) -> List[TextClassificationOutputElement]:
  1735. """
  1736. Perform text classification (e.g. sentiment-analysis) on the given text.
  1737. Args:
  1738. text (`str`):
  1739. A string to be classified.
  1740. model (`str`, *optional*):
  1741. The model to use for the text classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  1742. a deployed Inference Endpoint. If not provided, the default recommended text classification model will be used.
  1743. Defaults to None.
  1744. top_k (`int`, *optional*):
  1745. When specified, limits the output to the top K most probable classes.
  1746. function_to_apply (`"TextClassificationOutputTransform"`, *optional*):
  1747. The function to apply to the model outputs in order to retrieve the scores.
  1748. Returns:
  1749. `List[TextClassificationOutputElement]`: a list of [`TextClassificationOutputElement`] items containing the predicted label and associated probability.
  1750. Raises:
  1751. [`InferenceTimeoutError`]:
  1752. If the model is unavailable or the request times out.
  1753. `HTTPError`:
  1754. If the request fails with an HTTP error status code other than HTTP 503.
  1755. Example:
  1756. ```py
  1757. >>> from huggingface_hub import InferenceClient
  1758. >>> client = InferenceClient()
  1759. >>> client.text_classification("I like you")
  1760. [
  1761. TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
  1762. TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
  1763. ]
  1764. ```
  1765. """
  1766. model_id = model or self.model
  1767. provider_helper = get_provider_helper(self.provider, task="text-classification", model=model_id)
  1768. request_parameters = provider_helper.prepare_request(
  1769. inputs=text,
  1770. parameters={
  1771. "function_to_apply": function_to_apply,
  1772. "top_k": top_k,
  1773. },
  1774. headers=self.headers,
  1775. model=model_id,
  1776. api_key=self.token,
  1777. )
  1778. response = self._inner_post(request_parameters)
  1779. return TextClassificationOutputElement.parse_obj_as_list(response)[0] # type: ignore [return-value]
  1780. @overload
  1781. def text_generation(
  1782. self,
  1783. prompt: str,
  1784. *,
  1785. details: Literal[True],
  1786. stream: Literal[True],
  1787. model: Optional[str] = None,
  1788. # Parameters from `TextGenerationInputGenerateParameters` (maintained manually)
  1789. adapter_id: Optional[str] = None,
  1790. best_of: Optional[int] = None,
  1791. decoder_input_details: Optional[bool] = None,
  1792. do_sample: Optional[bool] = None,
  1793. frequency_penalty: Optional[float] = None,
  1794. grammar: Optional[TextGenerationInputGrammarType] = None,
  1795. max_new_tokens: Optional[int] = None,
  1796. repetition_penalty: Optional[float] = None,
  1797. return_full_text: Optional[bool] = None,
  1798. seed: Optional[int] = None,
  1799. stop: Optional[List[str]] = None,
  1800. stop_sequences: Optional[List[str]] = None, # Deprecated, use `stop` instead
  1801. temperature: Optional[float] = None,
  1802. top_k: Optional[int] = None,
  1803. top_n_tokens: Optional[int] = None,
  1804. top_p: Optional[float] = None,
  1805. truncate: Optional[int] = None,
  1806. typical_p: Optional[float] = None,
  1807. watermark: Optional[bool] = None,
  1808. ) -> Iterable[TextGenerationStreamOutput]: ...
  1809. @overload
  1810. def text_generation(
  1811. self,
  1812. prompt: str,
  1813. *,
  1814. details: Literal[True],
  1815. stream: Optional[Literal[False]] = None,
  1816. model: Optional[str] = None,
  1817. # Parameters from `TextGenerationInputGenerateParameters` (maintained manually)
  1818. adapter_id: Optional[str] = None,
  1819. best_of: Optional[int] = None,
  1820. decoder_input_details: Optional[bool] = None,
  1821. do_sample: Optional[bool] = None,
  1822. frequency_penalty: Optional[float] = None,
  1823. grammar: Optional[TextGenerationInputGrammarType] = None,
  1824. max_new_tokens: Optional[int] = None,
  1825. repetition_penalty: Optional[float] = None,
  1826. return_full_text: Optional[bool] = None,
  1827. seed: Optional[int] = None,
  1828. stop: Optional[List[str]] = None,
  1829. stop_sequences: Optional[List[str]] = None, # Deprecated, use `stop` instead
  1830. temperature: Optional[float] = None,
  1831. top_k: Optional[int] = None,
  1832. top_n_tokens: Optional[int] = None,
  1833. top_p: Optional[float] = None,
  1834. truncate: Optional[int] = None,
  1835. typical_p: Optional[float] = None,
  1836. watermark: Optional[bool] = None,
  1837. ) -> TextGenerationOutput: ...
  1838. @overload
  1839. def text_generation(
  1840. self,
  1841. prompt: str,
  1842. *,
  1843. details: Optional[Literal[False]] = None,
  1844. stream: Literal[True],
  1845. model: Optional[str] = None,
  1846. # Parameters from `TextGenerationInputGenerateParameters` (maintained manually)
  1847. adapter_id: Optional[str] = None,
  1848. best_of: Optional[int] = None,
  1849. decoder_input_details: Optional[bool] = None,
  1850. do_sample: Optional[bool] = None,
  1851. frequency_penalty: Optional[float] = None,
  1852. grammar: Optional[TextGenerationInputGrammarType] = None,
  1853. max_new_tokens: Optional[int] = None,
  1854. repetition_penalty: Optional[float] = None,
  1855. return_full_text: Optional[bool] = None, # Manual default value
  1856. seed: Optional[int] = None,
  1857. stop: Optional[List[str]] = None,
  1858. stop_sequences: Optional[List[str]] = None, # Deprecated, use `stop` instead
  1859. temperature: Optional[float] = None,
  1860. top_k: Optional[int] = None,
  1861. top_n_tokens: Optional[int] = None,
  1862. top_p: Optional[float] = None,
  1863. truncate: Optional[int] = None,
  1864. typical_p: Optional[float] = None,
  1865. watermark: Optional[bool] = None,
  1866. ) -> Iterable[str]: ...
  1867. @overload
  1868. def text_generation(
  1869. self,
  1870. prompt: str,
  1871. *,
  1872. details: Optional[Literal[False]] = None,
  1873. stream: Optional[Literal[False]] = None,
  1874. model: Optional[str] = None,
  1875. # Parameters from `TextGenerationInputGenerateParameters` (maintained manually)
  1876. adapter_id: Optional[str] = None,
  1877. best_of: Optional[int] = None,
  1878. decoder_input_details: Optional[bool] = None,
  1879. do_sample: Optional[bool] = None,
  1880. frequency_penalty: Optional[float] = None,
  1881. grammar: Optional[TextGenerationInputGrammarType] = None,
  1882. max_new_tokens: Optional[int] = None,
  1883. repetition_penalty: Optional[float] = None,
  1884. return_full_text: Optional[bool] = None,
  1885. seed: Optional[int] = None,
  1886. stop: Optional[List[str]] = None,
  1887. stop_sequences: Optional[List[str]] = None, # Deprecated, use `stop` instead
  1888. temperature: Optional[float] = None,
  1889. top_k: Optional[int] = None,
  1890. top_n_tokens: Optional[int] = None,
  1891. top_p: Optional[float] = None,
  1892. truncate: Optional[int] = None,
  1893. typical_p: Optional[float] = None,
  1894. watermark: Optional[bool] = None,
  1895. ) -> str: ...
  1896. @overload
  1897. def text_generation(
  1898. self,
  1899. prompt: str,
  1900. *,
  1901. details: Optional[bool] = None,
  1902. stream: Optional[bool] = None,
  1903. model: Optional[str] = None,
  1904. # Parameters from `TextGenerationInputGenerateParameters` (maintained manually)
  1905. adapter_id: Optional[str] = None,
  1906. best_of: Optional[int] = None,
  1907. decoder_input_details: Optional[bool] = None,
  1908. do_sample: Optional[bool] = None,
  1909. frequency_penalty: Optional[float] = None,
  1910. grammar: Optional[TextGenerationInputGrammarType] = None,
  1911. max_new_tokens: Optional[int] = None,
  1912. repetition_penalty: Optional[float] = None,
  1913. return_full_text: Optional[bool] = None,
  1914. seed: Optional[int] = None,
  1915. stop: Optional[List[str]] = None,
  1916. stop_sequences: Optional[List[str]] = None, # Deprecated, use `stop` instead
  1917. temperature: Optional[float] = None,
  1918. top_k: Optional[int] = None,
  1919. top_n_tokens: Optional[int] = None,
  1920. top_p: Optional[float] = None,
  1921. truncate: Optional[int] = None,
  1922. typical_p: Optional[float] = None,
  1923. watermark: Optional[bool] = None,
  1924. ) -> Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]: ...
  1925. def text_generation(
  1926. self,
  1927. prompt: str,
  1928. *,
  1929. details: Optional[bool] = None,
  1930. stream: Optional[bool] = None,
  1931. model: Optional[str] = None,
  1932. # Parameters from `TextGenerationInputGenerateParameters` (maintained manually)
  1933. adapter_id: Optional[str] = None,
  1934. best_of: Optional[int] = None,
  1935. decoder_input_details: Optional[bool] = None,
  1936. do_sample: Optional[bool] = None,
  1937. frequency_penalty: Optional[float] = None,
  1938. grammar: Optional[TextGenerationInputGrammarType] = None,
  1939. max_new_tokens: Optional[int] = None,
  1940. repetition_penalty: Optional[float] = None,
  1941. return_full_text: Optional[bool] = None,
  1942. seed: Optional[int] = None,
  1943. stop: Optional[List[str]] = None,
  1944. stop_sequences: Optional[List[str]] = None, # Deprecated, use `stop` instead
  1945. temperature: Optional[float] = None,
  1946. top_k: Optional[int] = None,
  1947. top_n_tokens: Optional[int] = None,
  1948. top_p: Optional[float] = None,
  1949. truncate: Optional[int] = None,
  1950. typical_p: Optional[float] = None,
  1951. watermark: Optional[bool] = None,
  1952. ) -> Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]:
  1953. """
  1954. Given a prompt, generate the following text.
  1955. > [!TIP]
  1956. > If you want to generate a response from chat messages, you should use the [`InferenceClient.chat_completion`] method.
  1957. > It accepts a list of messages instead of a single text prompt and handles the chat templating for you.
  1958. Args:
  1959. prompt (`str`):
  1960. Input text.
  1961. details (`bool`, *optional*):
  1962. By default, text_generation returns a string. Pass `details=True` if you want a detailed output (tokens,
  1963. probabilities, seed, finish reason, etc.). Only available for models running on with the
  1964. `text-generation-inference` backend.
  1965. stream (`bool`, *optional*):
  1966. By default, text_generation returns the full generated text. Pass `stream=True` if you want a stream of
  1967. tokens to be returned. Only available for models running on with the `text-generation-inference`
  1968. backend.
  1969. model (`str`, *optional*):
  1970. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  1971. Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
  1972. adapter_id (`str`, *optional*):
  1973. Lora adapter id.
  1974. best_of (`int`, *optional*):
  1975. Generate best_of sequences and return the one if the highest token logprobs.
  1976. decoder_input_details (`bool`, *optional*):
  1977. Return the decoder input token logprobs and ids. You must set `details=True` as well for it to be taken
  1978. into account. Defaults to `False`.
  1979. do_sample (`bool`, *optional*):
  1980. Activate logits sampling
  1981. frequency_penalty (`float`, *optional*):
  1982. Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in
  1983. the text so far, decreasing the model's likelihood to repeat the same line verbatim.
  1984. grammar ([`TextGenerationInputGrammarType`], *optional*):
  1985. Grammar constraints. Can be either a JSONSchema or a regex.
  1986. max_new_tokens (`int`, *optional*):
  1987. Maximum number of generated tokens. Defaults to 100.
  1988. repetition_penalty (`float`, *optional*):
  1989. The parameter for repetition penalty. 1.0 means no penalty. See [this
  1990. paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
  1991. return_full_text (`bool`, *optional*):
  1992. Whether to prepend the prompt to the generated text
  1993. seed (`int`, *optional*):
  1994. Random sampling seed
  1995. stop (`List[str]`, *optional*):
  1996. Stop generating tokens if a member of `stop` is generated.
  1997. stop_sequences (`List[str]`, *optional*):
  1998. Deprecated argument. Use `stop` instead.
  1999. temperature (`float`, *optional*):
  2000. The value used to module the logits distribution.
  2001. top_n_tokens (`int`, *optional*):
  2002. Return information about the `top_n_tokens` most likely tokens at each generation step, instead of
  2003. just the sampled token.
  2004. top_k (`int`, *optional`):
  2005. The number of highest probability vocabulary tokens to keep for top-k-filtering.
  2006. top_p (`float`, *optional`):
  2007. If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
  2008. higher are kept for generation.
  2009. truncate (`int`, *optional`):
  2010. Truncate inputs tokens to the given size.
  2011. typical_p (`float`, *optional`):
  2012. Typical Decoding mass
  2013. See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
  2014. watermark (`bool`, *optional*):
  2015. Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
  2016. Returns:
  2017. `Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]`:
  2018. Generated text returned from the server:
  2019. - if `stream=False` and `details=False`, the generated text is returned as a `str` (default)
  2020. - if `stream=True` and `details=False`, the generated text is returned token by token as a `Iterable[str]`
  2021. - if `stream=False` and `details=True`, the generated text is returned with more details as a [`~huggingface_hub.TextGenerationOutput`]
  2022. - if `details=True` and `stream=True`, the generated text is returned token by token as a iterable of [`~huggingface_hub.TextGenerationStreamOutput`]
  2023. Raises:
  2024. `ValidationError`:
  2025. If input values are not valid. No HTTP call is made to the server.
  2026. [`InferenceTimeoutError`]:
  2027. If the model is unavailable or the request times out.
  2028. `HTTPError`:
  2029. If the request fails with an HTTP error status code other than HTTP 503.
  2030. Example:
  2031. ```py
  2032. >>> from huggingface_hub import InferenceClient
  2033. >>> client = InferenceClient()
  2034. # Case 1: generate text
  2035. >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12)
  2036. '100% open source and built to be easy to use.'
  2037. # Case 2: iterate over the generated tokens. Useful for large generation.
  2038. >>> for token in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True):
  2039. ... print(token)
  2040. 100
  2041. %
  2042. open
  2043. source
  2044. and
  2045. built
  2046. to
  2047. be
  2048. easy
  2049. to
  2050. use
  2051. .
  2052. # Case 3: get more details about the generation process.
  2053. >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True)
  2054. TextGenerationOutput(
  2055. generated_text='100% open source and built to be easy to use.',
  2056. details=TextGenerationDetails(
  2057. finish_reason='length',
  2058. generated_tokens=12,
  2059. seed=None,
  2060. prefill=[
  2061. TextGenerationPrefillOutputToken(id=487, text='The', logprob=None),
  2062. TextGenerationPrefillOutputToken(id=53789, text=' hugging', logprob=-13.171875),
  2063. (...)
  2064. TextGenerationPrefillOutputToken(id=204, text=' ', logprob=-7.0390625)
  2065. ],
  2066. tokens=[
  2067. TokenElement(id=1425, text='100', logprob=-1.0175781, special=False),
  2068. TokenElement(id=16, text='%', logprob=-0.0463562, special=False),
  2069. (...)
  2070. TokenElement(id=25, text='.', logprob=-0.5703125, special=False)
  2071. ],
  2072. best_of_sequences=None
  2073. )
  2074. )
  2075. # Case 4: iterate over the generated tokens with more details.
  2076. # Last object is more complete, containing the full generated text and the finish reason.
  2077. >>> for details in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True):
  2078. ... print(details)
  2079. ...
  2080. TextGenerationStreamOutput(token=TokenElement(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
  2081. TextGenerationStreamOutput(token=TokenElement(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
  2082. TextGenerationStreamOutput(token=TokenElement(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
  2083. TextGenerationStreamOutput(token=TokenElement(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
  2084. TextGenerationStreamOutput(token=TokenElement(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
  2085. TextGenerationStreamOutput(token=TokenElement(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
  2086. TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
  2087. TextGenerationStreamOutput(token=TokenElement(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
  2088. TextGenerationStreamOutput(token=TokenElement(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
  2089. TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
  2090. TextGenerationStreamOutput(token=TokenElement(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
  2091. TextGenerationStreamOutput(token=TokenElement(
  2092. id=25,
  2093. text='.',
  2094. logprob=-0.5703125,
  2095. special=False),
  2096. generated_text='100% open source and built to be easy to use.',
  2097. details=TextGenerationStreamOutputStreamDetails(finish_reason='length', generated_tokens=12, seed=None)
  2098. )
  2099. # Case 5: generate constrained output using grammar
  2100. >>> response = client.text_generation(
  2101. ... prompt="I saw a puppy a cat and a raccoon during my bike ride in the park",
  2102. ... model="HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1",
  2103. ... max_new_tokens=100,
  2104. ... repetition_penalty=1.3,
  2105. ... grammar={
  2106. ... "type": "json",
  2107. ... "value": {
  2108. ... "properties": {
  2109. ... "location": {"type": "string"},
  2110. ... "activity": {"type": "string"},
  2111. ... "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
  2112. ... "animals": {"type": "array", "items": {"type": "string"}},
  2113. ... },
  2114. ... "required": ["location", "activity", "animals_seen", "animals"],
  2115. ... },
  2116. ... },
  2117. ... )
  2118. >>> json.loads(response)
  2119. {
  2120. "activity": "bike riding",
  2121. "animals": ["puppy", "cat", "raccoon"],
  2122. "animals_seen": 3,
  2123. "location": "park"
  2124. }
  2125. ```
  2126. """
  2127. if decoder_input_details and not details:
  2128. warnings.warn(
  2129. "`decoder_input_details=True` has been passed to the server but `details=False` is set meaning that"
  2130. " the output from the server will be truncated."
  2131. )
  2132. decoder_input_details = False
  2133. if stop_sequences is not None:
  2134. warnings.warn(
  2135. "`stop_sequences` is a deprecated argument for `text_generation` task"
  2136. " and will be removed in version '0.28.0'. Use `stop` instead.",
  2137. FutureWarning,
  2138. )
  2139. if stop is None:
  2140. stop = stop_sequences # use deprecated arg if provided
  2141. # Build payload
  2142. parameters = {
  2143. "adapter_id": adapter_id,
  2144. "best_of": best_of,
  2145. "decoder_input_details": decoder_input_details,
  2146. "details": details,
  2147. "do_sample": do_sample,
  2148. "frequency_penalty": frequency_penalty,
  2149. "grammar": grammar,
  2150. "max_new_tokens": max_new_tokens,
  2151. "repetition_penalty": repetition_penalty,
  2152. "return_full_text": return_full_text,
  2153. "seed": seed,
  2154. "stop": stop,
  2155. "temperature": temperature,
  2156. "top_k": top_k,
  2157. "top_n_tokens": top_n_tokens,
  2158. "top_p": top_p,
  2159. "truncate": truncate,
  2160. "typical_p": typical_p,
  2161. "watermark": watermark,
  2162. }
  2163. # Remove some parameters if not a TGI server
  2164. unsupported_kwargs = _get_unsupported_text_generation_kwargs(model)
  2165. if len(unsupported_kwargs) > 0:
  2166. # The server does not support some parameters
  2167. # => means it is not a TGI server
  2168. # => remove unsupported parameters and warn the user
  2169. ignored_parameters = []
  2170. for key in unsupported_kwargs:
  2171. if parameters.get(key):
  2172. ignored_parameters.append(key)
  2173. parameters.pop(key, None)
  2174. if len(ignored_parameters) > 0:
  2175. warnings.warn(
  2176. "API endpoint/model for text-generation is not served via TGI. Ignoring following parameters:"
  2177. f" {', '.join(ignored_parameters)}.",
  2178. UserWarning,
  2179. )
  2180. if details:
  2181. warnings.warn(
  2182. "API endpoint/model for text-generation is not served via TGI. Parameter `details=True` will"
  2183. " be ignored meaning only the generated text will be returned.",
  2184. UserWarning,
  2185. )
  2186. details = False
  2187. if stream:
  2188. raise ValueError(
  2189. "API endpoint/model for text-generation is not served via TGI. Cannot return output as a stream."
  2190. " Please pass `stream=False` as input."
  2191. )
  2192. model_id = model or self.model
  2193. provider_helper = get_provider_helper(self.provider, task="text-generation", model=model_id)
  2194. request_parameters = provider_helper.prepare_request(
  2195. inputs=prompt,
  2196. parameters=parameters,
  2197. extra_payload={"stream": stream},
  2198. headers=self.headers,
  2199. model=model_id,
  2200. api_key=self.token,
  2201. )
  2202. # Handle errors separately for more precise error messages
  2203. try:
  2204. bytes_output = self._inner_post(request_parameters, stream=stream or False)
  2205. except HTTPError as e:
  2206. match = MODEL_KWARGS_NOT_USED_REGEX.search(str(e))
  2207. if isinstance(e, BadRequestError) and match:
  2208. unused_params = [kwarg.strip("' ") for kwarg in match.group(1).split(",")]
  2209. _set_unsupported_text_generation_kwargs(model, unused_params)
  2210. return self.text_generation( # type: ignore
  2211. prompt=prompt,
  2212. details=details,
  2213. stream=stream,
  2214. model=model_id,
  2215. adapter_id=adapter_id,
  2216. best_of=best_of,
  2217. decoder_input_details=decoder_input_details,
  2218. do_sample=do_sample,
  2219. frequency_penalty=frequency_penalty,
  2220. grammar=grammar,
  2221. max_new_tokens=max_new_tokens,
  2222. repetition_penalty=repetition_penalty,
  2223. return_full_text=return_full_text,
  2224. seed=seed,
  2225. stop=stop,
  2226. temperature=temperature,
  2227. top_k=top_k,
  2228. top_n_tokens=top_n_tokens,
  2229. top_p=top_p,
  2230. truncate=truncate,
  2231. typical_p=typical_p,
  2232. watermark=watermark,
  2233. )
  2234. raise_text_generation_error(e)
  2235. # Parse output
  2236. if stream:
  2237. return _stream_text_generation_response(bytes_output, details) # type: ignore
  2238. data = _bytes_to_dict(bytes_output) # type: ignore[arg-type]
  2239. # Data can be a single element (dict) or an iterable of dicts where we select the first element of.
  2240. if isinstance(data, list):
  2241. data = data[0]
  2242. response = provider_helper.get_response(data, request_parameters)
  2243. return TextGenerationOutput.parse_obj_as_instance(response) if details else response["generated_text"]
  2244. def text_to_image(
  2245. self,
  2246. prompt: str,
  2247. *,
  2248. negative_prompt: Optional[str] = None,
  2249. height: Optional[int] = None,
  2250. width: Optional[int] = None,
  2251. num_inference_steps: Optional[int] = None,
  2252. guidance_scale: Optional[float] = None,
  2253. model: Optional[str] = None,
  2254. scheduler: Optional[str] = None,
  2255. seed: Optional[int] = None,
  2256. extra_body: Optional[Dict[str, Any]] = None,
  2257. ) -> "Image":
  2258. """
  2259. Generate an image based on a given text using a specified model.
  2260. > [!WARNING]
  2261. > You must have `PIL` installed if you want to work with images (`pip install Pillow`).
  2262. > [!TIP]
  2263. > You can pass provider-specific parameters to the model by using the `extra_body` argument.
  2264. Args:
  2265. prompt (`str`):
  2266. The prompt to generate an image from.
  2267. negative_prompt (`str`, *optional*):
  2268. One prompt to guide what NOT to include in image generation.
  2269. height (`int`, *optional*):
  2270. The height in pixels of the output image
  2271. width (`int`, *optional*):
  2272. The width in pixels of the output image
  2273. num_inference_steps (`int`, *optional*):
  2274. The number of denoising steps. More denoising steps usually lead to a higher quality image at the
  2275. expense of slower inference.
  2276. guidance_scale (`float`, *optional*):
  2277. A higher guidance scale value encourages the model to generate images closely linked to the text
  2278. prompt, but values too high may cause saturation and other artifacts.
  2279. model (`str`, *optional*):
  2280. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  2281. Inference Endpoint. If not provided, the default recommended text-to-image model will be used.
  2282. Defaults to None.
  2283. scheduler (`str`, *optional*):
  2284. Override the scheduler with a compatible one.
  2285. seed (`int`, *optional*):
  2286. Seed for the random number generator.
  2287. extra_body (`Dict[str, Any]`, *optional*):
  2288. Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
  2289. for supported parameters.
  2290. Returns:
  2291. `Image`: The generated image.
  2292. Raises:
  2293. [`InferenceTimeoutError`]:
  2294. If the model is unavailable or the request times out.
  2295. `HTTPError`:
  2296. If the request fails with an HTTP error status code other than HTTP 503.
  2297. Example:
  2298. ```py
  2299. >>> from huggingface_hub import InferenceClient
  2300. >>> client = InferenceClient()
  2301. >>> image = client.text_to_image("An astronaut riding a horse on the moon.")
  2302. >>> image.save("astronaut.png")
  2303. >>> image = client.text_to_image(
  2304. ... "An astronaut riding a horse on the moon.",
  2305. ... negative_prompt="low resolution, blurry",
  2306. ... model="stabilityai/stable-diffusion-2-1",
  2307. ... )
  2308. >>> image.save("better_astronaut.png")
  2309. ```
  2310. Example using a third-party provider directly. Usage will be billed on your fal.ai account.
  2311. ```py
  2312. >>> from huggingface_hub import InferenceClient
  2313. >>> client = InferenceClient(
  2314. ... provider="fal-ai", # Use fal.ai provider
  2315. ... api_key="fal-ai-api-key", # Pass your fal.ai API key
  2316. ... )
  2317. >>> image = client.text_to_image(
  2318. ... "A majestic lion in a fantasy forest",
  2319. ... model="black-forest-labs/FLUX.1-schnell",
  2320. ... )
  2321. >>> image.save("lion.png")
  2322. ```
  2323. Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
  2324. ```py
  2325. >>> from huggingface_hub import InferenceClient
  2326. >>> client = InferenceClient(
  2327. ... provider="replicate", # Use replicate provider
  2328. ... api_key="hf_...", # Pass your HF token
  2329. ... )
  2330. >>> image = client.text_to_image(
  2331. ... "An astronaut riding a horse on the moon.",
  2332. ... model="black-forest-labs/FLUX.1-dev",
  2333. ... )
  2334. >>> image.save("astronaut.png")
  2335. ```
  2336. Example using Replicate provider with extra parameters
  2337. ```py
  2338. >>> from huggingface_hub import InferenceClient
  2339. >>> client = InferenceClient(
  2340. ... provider="replicate", # Use replicate provider
  2341. ... api_key="hf_...", # Pass your HF token
  2342. ... )
  2343. >>> image = client.text_to_image(
  2344. ... "An astronaut riding a horse on the moon.",
  2345. ... model="black-forest-labs/FLUX.1-schnell",
  2346. ... extra_body={"output_quality": 100},
  2347. ... )
  2348. >>> image.save("astronaut.png")
  2349. ```
  2350. """
  2351. model_id = model or self.model
  2352. provider_helper = get_provider_helper(self.provider, task="text-to-image", model=model_id)
  2353. request_parameters = provider_helper.prepare_request(
  2354. inputs=prompt,
  2355. parameters={
  2356. "negative_prompt": negative_prompt,
  2357. "height": height,
  2358. "width": width,
  2359. "num_inference_steps": num_inference_steps,
  2360. "guidance_scale": guidance_scale,
  2361. "scheduler": scheduler,
  2362. "seed": seed,
  2363. **(extra_body or {}),
  2364. },
  2365. headers=self.headers,
  2366. model=model_id,
  2367. api_key=self.token,
  2368. )
  2369. response = self._inner_post(request_parameters)
  2370. response = provider_helper.get_response(response)
  2371. return _bytes_to_image(response)
  2372. def text_to_video(
  2373. self,
  2374. prompt: str,
  2375. *,
  2376. model: Optional[str] = None,
  2377. guidance_scale: Optional[float] = None,
  2378. negative_prompt: Optional[List[str]] = None,
  2379. num_frames: Optional[float] = None,
  2380. num_inference_steps: Optional[int] = None,
  2381. seed: Optional[int] = None,
  2382. extra_body: Optional[Dict[str, Any]] = None,
  2383. ) -> bytes:
  2384. """
  2385. Generate a video based on a given text.
  2386. > [!TIP]
  2387. > You can pass provider-specific parameters to the model by using the `extra_body` argument.
  2388. Args:
  2389. prompt (`str`):
  2390. The prompt to generate a video from.
  2391. model (`str`, *optional*):
  2392. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  2393. Inference Endpoint. If not provided, the default recommended text-to-video model will be used.
  2394. Defaults to None.
  2395. guidance_scale (`float`, *optional*):
  2396. A higher guidance scale value encourages the model to generate videos closely linked to the text
  2397. prompt, but values too high may cause saturation and other artifacts.
  2398. negative_prompt (`List[str]`, *optional*):
  2399. One or several prompt to guide what NOT to include in video generation.
  2400. num_frames (`float`, *optional*):
  2401. The num_frames parameter determines how many video frames are generated.
  2402. num_inference_steps (`int`, *optional*):
  2403. The number of denoising steps. More denoising steps usually lead to a higher quality video at the
  2404. expense of slower inference.
  2405. seed (`int`, *optional*):
  2406. Seed for the random number generator.
  2407. extra_body (`Dict[str, Any]`, *optional*):
  2408. Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
  2409. for supported parameters.
  2410. Returns:
  2411. `bytes`: The generated video.
  2412. Example:
  2413. Example using a third-party provider directly. Usage will be billed on your fal.ai account.
  2414. ```py
  2415. >>> from huggingface_hub import InferenceClient
  2416. >>> client = InferenceClient(
  2417. ... provider="fal-ai", # Using fal.ai provider
  2418. ... api_key="fal-ai-api-key", # Pass your fal.ai API key
  2419. ... )
  2420. >>> video = client.text_to_video(
  2421. ... "A majestic lion running in a fantasy forest",
  2422. ... model="tencent/HunyuanVideo",
  2423. ... )
  2424. >>> with open("lion.mp4", "wb") as file:
  2425. ... file.write(video)
  2426. ```
  2427. Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
  2428. ```py
  2429. >>> from huggingface_hub import InferenceClient
  2430. >>> client = InferenceClient(
  2431. ... provider="replicate", # Using replicate provider
  2432. ... api_key="hf_...", # Pass your HF token
  2433. ... )
  2434. >>> video = client.text_to_video(
  2435. ... "A cat running in a park",
  2436. ... model="genmo/mochi-1-preview",
  2437. ... )
  2438. >>> with open("cat.mp4", "wb") as file:
  2439. ... file.write(video)
  2440. ```
  2441. """
  2442. model_id = model or self.model
  2443. provider_helper = get_provider_helper(self.provider, task="text-to-video", model=model_id)
  2444. request_parameters = provider_helper.prepare_request(
  2445. inputs=prompt,
  2446. parameters={
  2447. "guidance_scale": guidance_scale,
  2448. "negative_prompt": negative_prompt,
  2449. "num_frames": num_frames,
  2450. "num_inference_steps": num_inference_steps,
  2451. "seed": seed,
  2452. **(extra_body or {}),
  2453. },
  2454. headers=self.headers,
  2455. model=model_id,
  2456. api_key=self.token,
  2457. )
  2458. response = self._inner_post(request_parameters)
  2459. response = provider_helper.get_response(response, request_parameters)
  2460. return response
  2461. def text_to_speech(
  2462. self,
  2463. text: str,
  2464. *,
  2465. model: Optional[str] = None,
  2466. do_sample: Optional[bool] = None,
  2467. early_stopping: Optional[Union[bool, "TextToSpeechEarlyStoppingEnum"]] = None,
  2468. epsilon_cutoff: Optional[float] = None,
  2469. eta_cutoff: Optional[float] = None,
  2470. max_length: Optional[int] = None,
  2471. max_new_tokens: Optional[int] = None,
  2472. min_length: Optional[int] = None,
  2473. min_new_tokens: Optional[int] = None,
  2474. num_beam_groups: Optional[int] = None,
  2475. num_beams: Optional[int] = None,
  2476. penalty_alpha: Optional[float] = None,
  2477. temperature: Optional[float] = None,
  2478. top_k: Optional[int] = None,
  2479. top_p: Optional[float] = None,
  2480. typical_p: Optional[float] = None,
  2481. use_cache: Optional[bool] = None,
  2482. extra_body: Optional[Dict[str, Any]] = None,
  2483. ) -> bytes:
  2484. """
  2485. Synthesize an audio of a voice pronouncing a given text.
  2486. > [!TIP]
  2487. > You can pass provider-specific parameters to the model by using the `extra_body` argument.
  2488. Args:
  2489. text (`str`):
  2490. The text to synthesize.
  2491. model (`str`, *optional*):
  2492. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  2493. Inference Endpoint. If not provided, the default recommended text-to-speech model will be used.
  2494. Defaults to None.
  2495. do_sample (`bool`, *optional*):
  2496. Whether to use sampling instead of greedy decoding when generating new tokens.
  2497. early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *optional*):
  2498. Controls the stopping condition for beam-based methods.
  2499. epsilon_cutoff (`float`, *optional*):
  2500. If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
  2501. epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on
  2502. the size of the model. See [Truncation Sampling as Language Model
  2503. Desmoothing](https://hf.co/papers/2210.15191) for more details.
  2504. eta_cutoff (`float`, *optional*):
  2505. Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly
  2506. between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff)
  2507. * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token
  2508. probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3,
  2509. depending on the size of the model. See [Truncation Sampling as Language Model
  2510. Desmoothing](https://hf.co/papers/2210.15191) for more details.
  2511. max_length (`int`, *optional*):
  2512. The maximum length (in tokens) of the generated text, including the input.
  2513. max_new_tokens (`int`, *optional*):
  2514. The maximum number of tokens to generate. Takes precedence over max_length.
  2515. min_length (`int`, *optional*):
  2516. The minimum length (in tokens) of the generated text, including the input.
  2517. min_new_tokens (`int`, *optional*):
  2518. The minimum number of tokens to generate. Takes precedence over min_length.
  2519. num_beam_groups (`int`, *optional*):
  2520. Number of groups to divide num_beams into in order to ensure diversity among different groups of beams.
  2521. See [this paper](https://hf.co/papers/1610.02424) for more details.
  2522. num_beams (`int`, *optional*):
  2523. Number of beams to use for beam search.
  2524. penalty_alpha (`float`, *optional*):
  2525. The value balances the model confidence and the degeneration penalty in contrastive search decoding.
  2526. temperature (`float`, *optional*):
  2527. The value used to modulate the next token probabilities.
  2528. top_k (`int`, *optional*):
  2529. The number of highest probability vocabulary tokens to keep for top-k-filtering.
  2530. top_p (`float`, *optional*):
  2531. If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
  2532. top_p or higher are kept for generation.
  2533. typical_p (`float`, *optional*):
  2534. Local typicality measures how similar the conditional probability of predicting a target token next is
  2535. to the expected conditional probability of predicting a random token next, given the partial text
  2536. already generated. If set to float < 1, the smallest set of the most locally typical tokens with
  2537. probabilities that add up to typical_p or higher are kept for generation. See [this
  2538. paper](https://hf.co/papers/2202.00666) for more details.
  2539. use_cache (`bool`, *optional*):
  2540. Whether the model should use the past last key/values attentions to speed up decoding
  2541. extra_body (`Dict[str, Any]`, *optional*):
  2542. Additional provider-specific parameters to pass to the model. Refer to the provider's documentation
  2543. for supported parameters.
  2544. Returns:
  2545. `bytes`: The generated audio.
  2546. Raises:
  2547. [`InferenceTimeoutError`]:
  2548. If the model is unavailable or the request times out.
  2549. `HTTPError`:
  2550. If the request fails with an HTTP error status code other than HTTP 503.
  2551. Example:
  2552. ```py
  2553. >>> from pathlib import Path
  2554. >>> from huggingface_hub import InferenceClient
  2555. >>> client = InferenceClient()
  2556. >>> audio = client.text_to_speech("Hello world")
  2557. >>> Path("hello_world.flac").write_bytes(audio)
  2558. ```
  2559. Example using a third-party provider directly. Usage will be billed on your Replicate account.
  2560. ```py
  2561. >>> from huggingface_hub import InferenceClient
  2562. >>> client = InferenceClient(
  2563. ... provider="replicate",
  2564. ... api_key="your-replicate-api-key", # Pass your Replicate API key directly
  2565. ... )
  2566. >>> audio = client.text_to_speech(
  2567. ... text="Hello world",
  2568. ... model="OuteAI/OuteTTS-0.3-500M",
  2569. ... )
  2570. >>> Path("hello_world.flac").write_bytes(audio)
  2571. ```
  2572. Example using a third-party provider through Hugging Face Routing. Usage will be billed on your Hugging Face account.
  2573. ```py
  2574. >>> from huggingface_hub import InferenceClient
  2575. >>> client = InferenceClient(
  2576. ... provider="replicate",
  2577. ... api_key="hf_...", # Pass your HF token
  2578. ... )
  2579. >>> audio =client.text_to_speech(
  2580. ... text="Hello world",
  2581. ... model="OuteAI/OuteTTS-0.3-500M",
  2582. ... )
  2583. >>> Path("hello_world.flac").write_bytes(audio)
  2584. ```
  2585. Example using Replicate provider with extra parameters
  2586. ```py
  2587. >>> from huggingface_hub import InferenceClient
  2588. >>> client = InferenceClient(
  2589. ... provider="replicate", # Use replicate provider
  2590. ... api_key="hf_...", # Pass your HF token
  2591. ... )
  2592. >>> audio = client.text_to_speech(
  2593. ... "Hello, my name is Kororo, an awesome text-to-speech model.",
  2594. ... model="hexgrad/Kokoro-82M",
  2595. ... extra_body={"voice": "af_nicole"},
  2596. ... )
  2597. >>> Path("hello.flac").write_bytes(audio)
  2598. ```
  2599. Example music-gen using "YuE-s1-7B-anneal-en-cot" on fal.ai
  2600. ```py
  2601. >>> from huggingface_hub import InferenceClient
  2602. >>> lyrics = '''
  2603. ... [verse]
  2604. ... In the town where I was born
  2605. ... Lived a man who sailed to sea
  2606. ... And he told us of his life
  2607. ... In the land of submarines
  2608. ... So we sailed on to the sun
  2609. ... 'Til we found a sea of green
  2610. ... And we lived beneath the waves
  2611. ... In our yellow submarine
  2612. ... [chorus]
  2613. ... We all live in a yellow submarine
  2614. ... Yellow submarine, yellow submarine
  2615. ... We all live in a yellow submarine
  2616. ... Yellow submarine, yellow submarine
  2617. ... '''
  2618. >>> genres = "pavarotti-style tenor voice"
  2619. >>> client = InferenceClient(
  2620. ... provider="fal-ai",
  2621. ... model="m-a-p/YuE-s1-7B-anneal-en-cot",
  2622. ... api_key=...,
  2623. ... )
  2624. >>> audio = client.text_to_speech(lyrics, extra_body={"genres": genres})
  2625. >>> with open("output.mp3", "wb") as f:
  2626. ... f.write(audio)
  2627. ```
  2628. """
  2629. model_id = model or self.model
  2630. provider_helper = get_provider_helper(self.provider, task="text-to-speech", model=model_id)
  2631. request_parameters = provider_helper.prepare_request(
  2632. inputs=text,
  2633. parameters={
  2634. "do_sample": do_sample,
  2635. "early_stopping": early_stopping,
  2636. "epsilon_cutoff": epsilon_cutoff,
  2637. "eta_cutoff": eta_cutoff,
  2638. "max_length": max_length,
  2639. "max_new_tokens": max_new_tokens,
  2640. "min_length": min_length,
  2641. "min_new_tokens": min_new_tokens,
  2642. "num_beam_groups": num_beam_groups,
  2643. "num_beams": num_beams,
  2644. "penalty_alpha": penalty_alpha,
  2645. "temperature": temperature,
  2646. "top_k": top_k,
  2647. "top_p": top_p,
  2648. "typical_p": typical_p,
  2649. "use_cache": use_cache,
  2650. **(extra_body or {}),
  2651. },
  2652. headers=self.headers,
  2653. model=model_id,
  2654. api_key=self.token,
  2655. )
  2656. response = self._inner_post(request_parameters)
  2657. response = provider_helper.get_response(response)
  2658. return response
  2659. def token_classification(
  2660. self,
  2661. text: str,
  2662. *,
  2663. model: Optional[str] = None,
  2664. aggregation_strategy: Optional["TokenClassificationAggregationStrategy"] = None,
  2665. ignore_labels: Optional[List[str]] = None,
  2666. stride: Optional[int] = None,
  2667. ) -> List[TokenClassificationOutputElement]:
  2668. """
  2669. Perform token classification on the given text.
  2670. Usually used for sentence parsing, either grammatical, or Named Entity Recognition (NER) to understand keywords contained within text.
  2671. Args:
  2672. text (`str`):
  2673. A string to be classified.
  2674. model (`str`, *optional*):
  2675. The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  2676. a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used.
  2677. Defaults to None.
  2678. aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *optional*):
  2679. The strategy used to fuse tokens based on model predictions
  2680. ignore_labels (`List[str`, *optional*):
  2681. A list of labels to ignore
  2682. stride (`int`, *optional*):
  2683. The number of overlapping tokens between chunks when splitting the input text.
  2684. Returns:
  2685. `List[TokenClassificationOutputElement]`: List of [`TokenClassificationOutputElement`] items containing the entity group, confidence score, word, start and end index.
  2686. Raises:
  2687. [`InferenceTimeoutError`]:
  2688. If the model is unavailable or the request times out.
  2689. `HTTPError`:
  2690. If the request fails with an HTTP error status code other than HTTP 503.
  2691. Example:
  2692. ```py
  2693. >>> from huggingface_hub import InferenceClient
  2694. >>> client = InferenceClient()
  2695. >>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
  2696. [
  2697. TokenClassificationOutputElement(
  2698. entity_group='PER',
  2699. score=0.9971321225166321,
  2700. word='Sarah Jessica Parker',
  2701. start=11,
  2702. end=31,
  2703. ),
  2704. TokenClassificationOutputElement(
  2705. entity_group='PER',
  2706. score=0.9773476123809814,
  2707. word='Jessica',
  2708. start=52,
  2709. end=59,
  2710. )
  2711. ]
  2712. ```
  2713. """
  2714. model_id = model or self.model
  2715. provider_helper = get_provider_helper(self.provider, task="token-classification", model=model_id)
  2716. request_parameters = provider_helper.prepare_request(
  2717. inputs=text,
  2718. parameters={
  2719. "aggregation_strategy": aggregation_strategy,
  2720. "ignore_labels": ignore_labels,
  2721. "stride": stride,
  2722. },
  2723. headers=self.headers,
  2724. model=model_id,
  2725. api_key=self.token,
  2726. )
  2727. response = self._inner_post(request_parameters)
  2728. return TokenClassificationOutputElement.parse_obj_as_list(response)
  2729. def translation(
  2730. self,
  2731. text: str,
  2732. *,
  2733. model: Optional[str] = None,
  2734. src_lang: Optional[str] = None,
  2735. tgt_lang: Optional[str] = None,
  2736. clean_up_tokenization_spaces: Optional[bool] = None,
  2737. truncation: Optional["TranslationTruncationStrategy"] = None,
  2738. generate_parameters: Optional[Dict[str, Any]] = None,
  2739. ) -> TranslationOutput:
  2740. """
  2741. Convert text from one language to another.
  2742. Check out https://huggingface.co/tasks/translation for more information on how to choose the best model for
  2743. your specific use case. Source and target languages usually depend on the model.
  2744. However, it is possible to specify source and target languages for certain models. If you are working with one of these models,
  2745. you can use `src_lang` and `tgt_lang` arguments to pass the relevant information.
  2746. Args:
  2747. text (`str`):
  2748. A string to be translated.
  2749. model (`str`, *optional*):
  2750. The model to use for the translation task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  2751. a deployed Inference Endpoint. If not provided, the default recommended translation model will be used.
  2752. Defaults to None.
  2753. src_lang (`str`, *optional*):
  2754. The source language of the text. Required for models that can translate from multiple languages.
  2755. tgt_lang (`str`, *optional*):
  2756. Target language to translate to. Required for models that can translate to multiple languages.
  2757. clean_up_tokenization_spaces (`bool`, *optional*):
  2758. Whether to clean up the potential extra spaces in the text output.
  2759. truncation (`"TranslationTruncationStrategy"`, *optional*):
  2760. The truncation strategy to use.
  2761. generate_parameters (`Dict[str, Any]`, *optional*):
  2762. Additional parametrization of the text generation algorithm.
  2763. Returns:
  2764. [`TranslationOutput`]: The generated translated text.
  2765. Raises:
  2766. [`InferenceTimeoutError`]:
  2767. If the model is unavailable or the request times out.
  2768. `HTTPError`:
  2769. If the request fails with an HTTP error status code other than HTTP 503.
  2770. `ValueError`:
  2771. If only one of the `src_lang` and `tgt_lang` arguments are provided.
  2772. Example:
  2773. ```py
  2774. >>> from huggingface_hub import InferenceClient
  2775. >>> client = InferenceClient()
  2776. >>> client.translation("My name is Wolfgang and I live in Berlin")
  2777. 'Mein Name ist Wolfgang und ich lebe in Berlin.'
  2778. >>> client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
  2779. TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')
  2780. ```
  2781. Specifying languages:
  2782. ```py
  2783. >>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
  2784. "Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"
  2785. ```
  2786. """
  2787. # Throw error if only one of `src_lang` and `tgt_lang` was given
  2788. if src_lang is not None and tgt_lang is None:
  2789. raise ValueError("You cannot specify `src_lang` without specifying `tgt_lang`.")
  2790. if src_lang is None and tgt_lang is not None:
  2791. raise ValueError("You cannot specify `tgt_lang` without specifying `src_lang`.")
  2792. model_id = model or self.model
  2793. provider_helper = get_provider_helper(self.provider, task="translation", model=model_id)
  2794. request_parameters = provider_helper.prepare_request(
  2795. inputs=text,
  2796. parameters={
  2797. "src_lang": src_lang,
  2798. "tgt_lang": tgt_lang,
  2799. "clean_up_tokenization_spaces": clean_up_tokenization_spaces,
  2800. "truncation": truncation,
  2801. "generate_parameters": generate_parameters,
  2802. },
  2803. headers=self.headers,
  2804. model=model_id,
  2805. api_key=self.token,
  2806. )
  2807. response = self._inner_post(request_parameters)
  2808. return TranslationOutput.parse_obj_as_list(response)[0]
  2809. def visual_question_answering(
  2810. self,
  2811. image: ContentT,
  2812. question: str,
  2813. *,
  2814. model: Optional[str] = None,
  2815. top_k: Optional[int] = None,
  2816. ) -> List[VisualQuestionAnsweringOutputElement]:
  2817. """
  2818. Answering open-ended questions based on an image.
  2819. Args:
  2820. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  2821. The input image for the context. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  2822. question (`str`):
  2823. Question to be answered.
  2824. model (`str`, *optional*):
  2825. The model to use for the visual question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to
  2826. a deployed Inference Endpoint. If not provided, the default recommended visual question answering model will be used.
  2827. Defaults to None.
  2828. top_k (`int`, *optional*):
  2829. The number of answers to return (will be chosen by order of likelihood). Note that we return less than
  2830. topk answers if there are not enough options available within the context.
  2831. Returns:
  2832. `List[VisualQuestionAnsweringOutputElement]`: a list of [`VisualQuestionAnsweringOutputElement`] items containing the predicted label and associated probability.
  2833. Raises:
  2834. `InferenceTimeoutError`:
  2835. If the model is unavailable or the request times out.
  2836. `HTTPError`:
  2837. If the request fails with an HTTP error status code other than HTTP 503.
  2838. Example:
  2839. ```py
  2840. >>> from huggingface_hub import InferenceClient
  2841. >>> client = InferenceClient()
  2842. >>> client.visual_question_answering(
  2843. ... image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
  2844. ... question="What is the animal doing?"
  2845. ... )
  2846. [
  2847. VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
  2848. VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
  2849. ]
  2850. ```
  2851. """
  2852. model_id = model or self.model
  2853. provider_helper = get_provider_helper(self.provider, task="visual-question-answering", model=model_id)
  2854. request_parameters = provider_helper.prepare_request(
  2855. inputs=image,
  2856. parameters={"top_k": top_k},
  2857. headers=self.headers,
  2858. model=model_id,
  2859. api_key=self.token,
  2860. extra_payload={"question": question, "image": _b64_encode(image)},
  2861. )
  2862. response = self._inner_post(request_parameters)
  2863. return VisualQuestionAnsweringOutputElement.parse_obj_as_list(response)
  2864. def zero_shot_classification(
  2865. self,
  2866. text: str,
  2867. candidate_labels: List[str],
  2868. *,
  2869. multi_label: Optional[bool] = False,
  2870. hypothesis_template: Optional[str] = None,
  2871. model: Optional[str] = None,
  2872. ) -> List[ZeroShotClassificationOutputElement]:
  2873. """
  2874. Provide as input a text and a set of candidate labels to classify the input text.
  2875. Args:
  2876. text (`str`):
  2877. The input text to classify.
  2878. candidate_labels (`List[str]`):
  2879. The set of possible class labels to classify the text into.
  2880. labels (`List[str]`, *optional*):
  2881. (deprecated) List of strings. Each string is the verbalization of a possible label for the input text.
  2882. multi_label (`bool`, *optional*):
  2883. Whether multiple candidate labels can be true. If false, the scores are normalized such that the sum of
  2884. the label likelihoods for each sequence is 1. If true, the labels are considered independent and
  2885. probabilities are normalized for each candidate.
  2886. hypothesis_template (`str`, *optional*):
  2887. The sentence used in conjunction with `candidate_labels` to attempt the text classification by
  2888. replacing the placeholder with the candidate labels.
  2889. model (`str`, *optional*):
  2890. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  2891. Inference Endpoint. This parameter overrides the model defined at the instance level. If not provided, the default recommended zero-shot classification model will be used.
  2892. Returns:
  2893. `List[ZeroShotClassificationOutputElement]`: List of [`ZeroShotClassificationOutputElement`] items containing the predicted labels and their confidence.
  2894. Raises:
  2895. [`InferenceTimeoutError`]:
  2896. If the model is unavailable or the request times out.
  2897. `HTTPError`:
  2898. If the request fails with an HTTP error status code other than HTTP 503.
  2899. Example with `multi_label=False`:
  2900. ```py
  2901. >>> from huggingface_hub import InferenceClient
  2902. >>> client = InferenceClient()
  2903. >>> text = (
  2904. ... "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
  2905. ... "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
  2906. ... " mysteries when he went for a run up a hill in Nice, France."
  2907. ... )
  2908. >>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
  2909. >>> client.zero_shot_classification(text, labels)
  2910. [
  2911. ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
  2912. ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
  2913. ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
  2914. ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
  2915. ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
  2916. ]
  2917. >>> client.zero_shot_classification(text, labels, multi_label=True)
  2918. [
  2919. ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
  2920. ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
  2921. ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
  2922. ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
  2923. ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
  2924. ]
  2925. ```
  2926. Example with `multi_label=True` and a custom `hypothesis_template`:
  2927. ```py
  2928. >>> from huggingface_hub import InferenceClient
  2929. >>> client = InferenceClient()
  2930. >>> client.zero_shot_classification(
  2931. ... text="I really like our dinner and I'm very happy. I don't like the weather though.",
  2932. ... labels=["positive", "negative", "pessimistic", "optimistic"],
  2933. ... multi_label=True,
  2934. ... hypothesis_template="This text is {} towards the weather"
  2935. ... )
  2936. [
  2937. ZeroShotClassificationOutputElement(label='negative', score=0.9231801629066467),
  2938. ZeroShotClassificationOutputElement(label='pessimistic', score=0.8760990500450134),
  2939. ZeroShotClassificationOutputElement(label='optimistic', score=0.0008674879791215062),
  2940. ZeroShotClassificationOutputElement(label='positive', score=0.0005250611575320363)
  2941. ]
  2942. ```
  2943. """
  2944. model_id = model or self.model
  2945. provider_helper = get_provider_helper(self.provider, task="zero-shot-classification", model=model_id)
  2946. request_parameters = provider_helper.prepare_request(
  2947. inputs=text,
  2948. parameters={
  2949. "candidate_labels": candidate_labels,
  2950. "multi_label": multi_label,
  2951. "hypothesis_template": hypothesis_template,
  2952. },
  2953. headers=self.headers,
  2954. model=model_id,
  2955. api_key=self.token,
  2956. )
  2957. response = self._inner_post(request_parameters)
  2958. output = _bytes_to_dict(response)
  2959. return [
  2960. ZeroShotClassificationOutputElement.parse_obj_as_instance({"label": label, "score": score})
  2961. for label, score in zip(output["labels"], output["scores"])
  2962. ]
  2963. def zero_shot_image_classification(
  2964. self,
  2965. image: ContentT,
  2966. candidate_labels: List[str],
  2967. *,
  2968. model: Optional[str] = None,
  2969. hypothesis_template: Optional[str] = None,
  2970. # deprecated argument
  2971. labels: List[str] = None, # type: ignore
  2972. ) -> List[ZeroShotImageClassificationOutputElement]:
  2973. """
  2974. Provide input image and text labels to predict text labels for the image.
  2975. Args:
  2976. image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`):
  2977. The input image to caption. It can be raw bytes, an image file, a URL to an online image, or a PIL Image.
  2978. candidate_labels (`List[str]`):
  2979. The candidate labels for this image
  2980. labels (`List[str]`, *optional*):
  2981. (deprecated) List of string possible labels. There must be at least 2 labels.
  2982. model (`str`, *optional*):
  2983. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  2984. Inference Endpoint. This parameter overrides the model defined at the instance level. If not provided, the default recommended zero-shot image classification model will be used.
  2985. hypothesis_template (`str`, *optional*):
  2986. The sentence used in conjunction with `candidate_labels` to attempt the image classification by
  2987. replacing the placeholder with the candidate labels.
  2988. Returns:
  2989. `List[ZeroShotImageClassificationOutputElement]`: List of [`ZeroShotImageClassificationOutputElement`] items containing the predicted labels and their confidence.
  2990. Raises:
  2991. [`InferenceTimeoutError`]:
  2992. If the model is unavailable or the request times out.
  2993. `HTTPError`:
  2994. If the request fails with an HTTP error status code other than HTTP 503.
  2995. Example:
  2996. ```py
  2997. >>> from huggingface_hub import InferenceClient
  2998. >>> client = InferenceClient()
  2999. >>> client.zero_shot_image_classification(
  3000. ... "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
  3001. ... labels=["dog", "cat", "horse"],
  3002. ... )
  3003. [ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
  3004. ```
  3005. """
  3006. # Raise ValueError if input is less than 2 labels
  3007. if len(candidate_labels) < 2:
  3008. raise ValueError("You must specify at least 2 classes to compare.")
  3009. model_id = model or self.model
  3010. provider_helper = get_provider_helper(self.provider, task="zero-shot-image-classification", model=model_id)
  3011. request_parameters = provider_helper.prepare_request(
  3012. inputs=image,
  3013. parameters={
  3014. "candidate_labels": candidate_labels,
  3015. "hypothesis_template": hypothesis_template,
  3016. },
  3017. headers=self.headers,
  3018. model=model_id,
  3019. api_key=self.token,
  3020. )
  3021. response = self._inner_post(request_parameters)
  3022. return ZeroShotImageClassificationOutputElement.parse_obj_as_list(response)
  3023. def get_endpoint_info(self, *, model: Optional[str] = None) -> Dict[str, Any]:
  3024. """
  3025. Get information about the deployed endpoint.
  3026. This endpoint is only available on endpoints powered by Text-Generation-Inference (TGI) or Text-Embedding-Inference (TEI).
  3027. Endpoints powered by `transformers` return an empty payload.
  3028. Args:
  3029. model (`str`, *optional*):
  3030. The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
  3031. Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
  3032. Returns:
  3033. `Dict[str, Any]`: Information about the endpoint.
  3034. Example:
  3035. ```py
  3036. >>> from huggingface_hub import InferenceClient
  3037. >>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
  3038. >>> client.get_endpoint_info()
  3039. {
  3040. 'model_id': 'meta-llama/Meta-Llama-3-70B-Instruct',
  3041. 'model_sha': None,
  3042. 'model_dtype': 'torch.float16',
  3043. 'model_device_type': 'cuda',
  3044. 'model_pipeline_tag': None,
  3045. 'max_concurrent_requests': 128,
  3046. 'max_best_of': 2,
  3047. 'max_stop_sequences': 4,
  3048. 'max_input_length': 8191,
  3049. 'max_total_tokens': 8192,
  3050. 'waiting_served_ratio': 0.3,
  3051. 'max_batch_total_tokens': 1259392,
  3052. 'max_waiting_tokens': 20,
  3053. 'max_batch_size': None,
  3054. 'validation_workers': 32,
  3055. 'max_client_batch_size': 4,
  3056. 'version': '2.0.2',
  3057. 'sha': 'dccab72549635c7eb5ddb17f43f0b7cdff07c214',
  3058. 'docker_label': 'sha-dccab72'
  3059. }
  3060. ```
  3061. """
  3062. if self.provider != "hf-inference":
  3063. raise ValueError(f"Getting endpoint info is not supported on '{self.provider}'.")
  3064. model = model or self.model
  3065. if model is None:
  3066. raise ValueError("Model id not provided.")
  3067. if model.startswith(("http://", "https://")):
  3068. url = model.rstrip("/") + "/info"
  3069. else:
  3070. url = f"{constants.INFERENCE_ENDPOINT}/models/{model}/info"
  3071. response = get_session().get(url, headers=build_hf_headers(token=self.token))
  3072. hf_raise_for_status(response)
  3073. return response.json()
  3074. def health_check(self, model: Optional[str] = None) -> bool:
  3075. """
  3076. Check the health of the deployed endpoint.
  3077. Health check is only available with Inference Endpoints powered by Text-Generation-Inference (TGI) or Text-Embedding-Inference (TEI).
  3078. Args:
  3079. model (`str`, *optional*):
  3080. URL of the Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
  3081. Returns:
  3082. `bool`: True if everything is working fine.
  3083. Example:
  3084. ```py
  3085. >>> from huggingface_hub import InferenceClient
  3086. >>> client = InferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
  3087. >>> client.health_check()
  3088. True
  3089. ```
  3090. """
  3091. if self.provider != "hf-inference":
  3092. raise ValueError(f"Health check is not supported on '{self.provider}'.")
  3093. model = model or self.model
  3094. if model is None:
  3095. raise ValueError("Model id not provided.")
  3096. if not model.startswith(("http://", "https://")):
  3097. raise ValueError("Model must be an Inference Endpoint URL.")
  3098. url = model.rstrip("/") + "/health"
  3099. response = get_session().get(url, headers=build_hf_headers(token=self.token))
  3100. return response.status_code == 200
  3101. @property
  3102. def chat(self) -> "ProxyClientChat":
  3103. return ProxyClientChat(self)
  3104. class _ProxyClient:
  3105. """Proxy class to be able to call `client.chat.completion.create(...)` as OpenAI client."""
  3106. def __init__(self, client: InferenceClient):
  3107. self._client = client
  3108. class ProxyClientChat(_ProxyClient):
  3109. """Proxy class to be able to call `client.chat.completion.create(...)` as OpenAI client."""
  3110. @property
  3111. def completions(self) -> "ProxyClientChatCompletions":
  3112. return ProxyClientChatCompletions(self._client)
  3113. class ProxyClientChatCompletions(_ProxyClient):
  3114. """Proxy class to be able to call `client.chat.completion.create(...)` as OpenAI client."""
  3115. @property
  3116. def create(self):
  3117. return self._client.chat_completion