|
| 1 | +import logging |
| 2 | +from typing import Dict, List, Optional, Union |
| 3 | + |
| 4 | +import requests |
| 5 | + |
| 6 | +from .hf_api import HfApi |
| 7 | + |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +ENDPOINT = "https://api-inference.huggingface.co" |
| 13 | + |
| 14 | +ALL_TASKS = [ |
| 15 | + # NLP |
| 16 | + "text-classification", |
| 17 | + "token-classification", |
| 18 | + "table-question-answering", |
| 19 | + "question-answering", |
| 20 | + "zero-shot-classification", |
| 21 | + "translation", |
| 22 | + "summarization", |
| 23 | + "conversational", |
| 24 | + "feature-extraction", |
| 25 | + "text-generation", |
| 26 | + "text2text-generation", |
| 27 | + "fill-mask", |
| 28 | + "sentence-similarity", |
| 29 | + # Audio |
| 30 | + "text-to-speech", |
| 31 | + "automatic-speech-recognition", |
| 32 | + "audio-to-audio", |
| 33 | + "audio-source-separation", |
| 34 | + "voice-activity-detection", |
| 35 | + # Computer vision |
| 36 | + "image-classification", |
| 37 | + "object-detection", |
| 38 | + "image-segmentation", |
| 39 | + # Others |
| 40 | + "structured-data-classification", |
| 41 | +] |
| 42 | + |
| 43 | + |
| 44 | +class InferenceApi: |
| 45 | + """Client to configure requests and make calls to the HuggingFace Inference API. |
| 46 | +
|
| 47 | + Example: |
| 48 | +
|
| 49 | + >>> from huggingface_hub.inference_api import InferenceApi |
| 50 | +
|
| 51 | + >>> # Mask-fill example |
| 52 | + >>> api = InferenceApi("bert-base-uncased") |
| 53 | + >>> api(inputs="The goal of life is [MASK].") |
| 54 | + >>> >> [{'sequence': 'the goal of life is life.', 'score': 0.10933292657136917, 'token': 2166, 'token_str': 'life'}] |
| 55 | +
|
| 56 | + >>> # Question Answering example |
| 57 | + >>> api = InferenceApi("deepset/roberta-base-squad2") |
| 58 | + >>> inputs = {"question":"What's my name?", "context":"My name is Clara and I live in Berkeley."} |
| 59 | + >>> api(inputs) |
| 60 | + >>> >> {'score': 0.9326569437980652, 'start': 11, 'end': 16, 'answer': 'Clara'} |
| 61 | +
|
| 62 | + >>> # Zero-shot example |
| 63 | + >>> api = InferenceApi("typeform/distilbert-base-uncased-mnli") |
| 64 | + >>> inputs = "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!" |
| 65 | + >>> params = {"candidate_labels":["refund", "legal", "faq"]} |
| 66 | + >>> api(inputs, params) |
| 67 | + >>> >> {'sequence': 'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!', 'labels': ['refund', 'faq', 'legal'], 'scores': [0.9378499388694763, 0.04914155602455139, 0.013008488342165947]} |
| 68 | +
|
| 69 | + >>> # Overriding configured task |
| 70 | + >>> api = InferenceApi("bert-base-uncased", task="feature-extraction") |
| 71 | + """ |
| 72 | + |
| 73 | + def __init__( |
| 74 | + self, |
| 75 | + repo_id: str, |
| 76 | + task: Optional[str] = None, |
| 77 | + token: Optional[str] = None, |
| 78 | + gpu: Optional[bool] = False, |
| 79 | + ): |
| 80 | + """Inits headers and API call information. |
| 81 | +
|
| 82 | + Args: |
| 83 | + repo_id (``str``): Id of repository (e.g. `user/bert-base-uncased`). |
| 84 | + task (``str``, `optional`, defaults ``None``): Whether to force a task instead of using task specified in the repository. |
| 85 | + token (:obj:`str`, `optional`): |
| 86 | + The API token to use as HTTP bearer authorization. This is not the authentication token. |
| 87 | + You can find the token in https://huggingface.co/settings/token. Alternatively, you can |
| 88 | + find both your organizations and personal API tokens using `HfApi().whoami(token)`. |
| 89 | + gpu (``bool``, `optional`, defaults ``False``): Whether to use GPU instead of CPU for inference(requires Startup plan at least). |
| 90 | + .. note:: |
| 91 | + Setting :obj:`token` is required when you want to use a private model. |
| 92 | + """ |
| 93 | + self.options = {"wait_for_model": True, "use_gpu": gpu} |
| 94 | + |
| 95 | + self.headers = {} |
| 96 | + if isinstance(token, str): |
| 97 | + self.headers["Authorization"] = "Bearer {}".format(token) |
| 98 | + |
| 99 | + # Configure task |
| 100 | + model_info = HfApi().model_info(repo_id=repo_id, token=token) |
| 101 | + if not model_info.pipeline_tag and not task: |
| 102 | + raise ValueError( |
| 103 | + "Task not specified in the repository. Please add it to the model card using pipeline_tag (https://huggingface.co/docs#how-is-a-models-type-of-inference-api-and-widget-determined)" |
| 104 | + ) |
| 105 | + |
| 106 | + if task and task != model_info.pipeline_tag: |
| 107 | + if task not in ALL_TASKS: |
| 108 | + raise ValueError(f"Invalid task {task}. Make sure it's valid.") |
| 109 | + |
| 110 | + logger.warning( |
| 111 | + "You're using a different task than the one specified in the repository. Be sure to know what you're doing :)" |
| 112 | + ) |
| 113 | + self.task = task |
| 114 | + else: |
| 115 | + self.task = model_info.pipeline_tag |
| 116 | + |
| 117 | + self.api_url = f"{ENDPOINT}/pipeline/{self.task}/{repo_id}" |
| 118 | + |
| 119 | + def __repr__(self): |
| 120 | + items = (f"{k}='{v}'" for k, v in self.__dict__.items()) |
| 121 | + return f"{self.__class__.__name__}({', '.join(items)})" |
| 122 | + |
| 123 | + def __call__( |
| 124 | + self, |
| 125 | + inputs: Union[str, Dict, List[str], List[List[str]]], |
| 126 | + params: Optional[Dict] = None, |
| 127 | + ): |
| 128 | + payload = { |
| 129 | + "inputs": inputs, |
| 130 | + "options": self.options, |
| 131 | + } |
| 132 | + |
| 133 | + if params: |
| 134 | + payload["parameters"] = params |
| 135 | + |
| 136 | + # TODO: Decide if we should raise an error instead of |
| 137 | + # returning the json. |
| 138 | + response = requests.post( |
| 139 | + self.api_url, headers=self.headers, json=payload |
| 140 | + ).json() |
| 141 | + return response |
0 commit comments