Spaces:
Runtime error
Runtime error
feat: implement our own InferenceClient
Browse files19 unmodified lines2021222324254 unmodified lines30313233343561 unmodified lines979899100101102103104105106102 unmodified lines20921021121221321421519 unmodified linesTextbox,get_component_instance,)from gradio.themes import ThemeClass as Themeimport gradio as gr4 unmodified linesfrom huggingface_hub import Repository, InferenceClientfrom utils import force_git_pushHF_TOKEN = os.environ.get("HF_TOKEN", None)DATASET_REPO_URL = os.getenv("DATASET_REPO_URL")MODEL_NAME = os.getenv("MODEL_NAME")61 unmodified lines# ["<%مهدی اخوان ثالث%"],# ]client = InferenceClient(API_URL,headers={"Authorization": f"Bearer {HF_TOKEN}","use_cache": False},)def asynchronous_push(f_stop):102 unmodified lines),gr.Slider(label="Top-p (nucleus sampling)",value=1.0,minimum=0.0,maximum=1,step=0.05,19 unmodified lines20212223242526272829303132334 unmodified lines38394041424344454647484950515253545561 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229102 unmodified lines33233333433533633733819 unmodified linesTextbox,get_component_instance,)from huggingface_hub.utils import (BadRequestError,build_hf_headers,get_session,hf_raise_for_status,)from gradio.themes import ThemeClass as Themeimport gradio as gr4 unmodified linesfrom huggingface_hub import Repository, InferenceClientfrom utils import force_git_pushfrom typing import (TYPE_CHECKING,Any,Dict,Iterable,List,Literal,Optional,Union,overload,)HF_TOKEN = os.environ.get("HF_TOKEN", None)DATASET_REPO_URL = os.getenv("DATASET_REPO_URL")MODEL_NAME = os.getenv("MODEL_NAME")61 unmodified lines# ["<%مهدی اخوان ثالث%"],# ]class InferenceClientUS(InferenceClient):def __init__(self,model: Optional[str] = None,token: Union[str, bool, None] = None,timeout: Optional[float] = None,headers: Optional[Dict[str, str]] = None,cookies: Optional[Dict[str, str]] = None,) -> None:super().__init__(model=model,token=token,timeout=timeout,headers=headers,cookies=cookies,)def post(self,*,json: Optional[Union[str, Dict, List]] = None,data: Optional[ContentT] = None,model: Optional[str] = None,task: Optional[str] = None,stream: bool = False,) -> Union[bytes, Iterable[bytes]]:"""Make a POST request to the inference server.Args:json (`Union[str, Dict, List]`, *optional*):The JSON data to send in the request body. Defaults to None.data (`Union[str, Path, bytes, BinaryIO]`, *optional*):The content to send in the request body. It can be raw bytes, a pointer to an opened file, a local filepath, or a URL to an online resource (image, audio file,...). If both `json` and `data` are passed,`data` will take precedence. At least `json` or `data` must be provided. Defaults to None.model (`str`, *optional*):The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployedInference Endpoint. Will override the model defined at the instance level. Defaults to None.task (`str`, *optional*):The task to perform on the inference. Used only to default to a recommended model if `model` is notprovided. At least `model` or `task` must be provided. Defaults to None.stream (`bool`, *optional*):Whether to iterate over streaming APIs.Returns:bytes: The raw bytes returned by the server.Raises:[`InferenceTimeoutError`]:If the model is unavailable or the request times out.`HTTPError`:If the request fails with an HTTP error status code other than HTTP 503."""url = self._resolve_url(model, task)if data is not None and json is not None:warnings.warn("Ignoring `json` as `data` is passed as binary.")# Set Accept header if relevantheaders = self.headers.copy()if task in TASKS_EXPECTING_IMAGES and "Accept" not in headers:headers["Accept"] = "image/png"t0 = time.time()timeout = self.timeoutwhile True:with _open_as_binary(data) as data_as_binary:try:response = get_session().post(url,json=json,data=data_as_binary,headers=headers,cookies=self.cookies,timeout=self.timeout,stream=stream,)except TimeoutError as error:# Convert any `TimeoutError` to a `InferenceTimeoutError`raise InferenceTimeoutError(f"Inference call timed out: {url}") from error # type: ignoretry:hf_raise_for_status(response)return response.iter_lines() if stream else response.contentexcept HTTPError as error:if error.response.status_code == 503:# If Model is unavailable, either raise a TimeoutError...if timeout is not None and time.time() - t0 > timeout:raise InferenceTimeoutError(f"Model not loaded on the server: {url}. Please retry with a higher timeout (current:"f" {self.timeout}).",request=error.request,response=error.response,) from error# ...or wait 1s and retrylogger.info(f"Waiting for model to be loaded on the server: {error}")time.sleep(1)if timeout is not None:timeout = max(self.timeout - (time.time() - t0), 1) # type: ignorecontinueraiseclient = InferenceClientUS(API_URL,headers={"Authorization": f"Bearer {HF_TOKEN}"},)def asynchronous_push(f_stop):102 unmodified lines),gr.Slider(label="Top-p (nucleus sampling)",value=0.9,minimum=0.0,maximum=1,step=0.05,
app.py+127-4