text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
if isinstance(top_k, int) or top_k is None: postprocess_params["top_k"] = top_k postprocess_params["_legacy"] = False elif return_all_scores is not None: warnings.warn( "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.", UserWarning, ) if return_all_scores: postprocess_params["top_k"] = None else: postprocess_params["top_k"] = 1 if isinstance(function_to_apply, str): function_to_apply = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: postprocess_params["function_to_apply"] = function_to_apply return preprocess_params, {}, postprocess_params
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
def __call__(self, inputs, **kwargs): """ Classify the text(s) given as inputs. Args: inputs (`str` or `List[str]` or `Dict[str]`, or `List[Dict[str]]`): One or several texts to classify. In order to use text pairs for your classification, you can send a dictionary containing `{"text", "text_pair"}` keys, or a list of those. top_k (`int`, *optional*, defaults to `1`): How many results to return. function_to_apply (`str`, *optional*, defaults to `"default"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: If this argument is not specified, then it will apply the following functions according to the number of labels:
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
- If problem type is regression, will not apply any function on the output. - If the model has a single label, will apply the sigmoid function on the output. - If the model has several labels, will apply the softmax function on the output. Possible values are: - `"sigmoid"`: Applies the sigmoid function on the output. - `"softmax"`: Applies the softmax function on the output. - `"none"`: Does not apply any function on the output. Return: A list or a list of list of `dict`: Each result comes as list of dictionaries with the following keys: - **label** (`str`) -- The label predicted. - **score** (`float`) -- The corresponding probability.
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
If `top_k` is used, one such dictionary is returned per label. """ inputs = (inputs,) result = super().__call__(*inputs, **kwargs) # TODO try and retrieve it in a nicer way from _sanitize_parameters. _legacy = "top_k" not in kwargs if isinstance(inputs[0], str) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
def preprocess(self, inputs, **tokenizer_kwargs) -> Dict[str, GenericTensor]: return_tensors = self.framework if isinstance(inputs, dict): return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs) elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs ) elif isinstance(inputs, list): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
) return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
def _forward(self, model_inputs): # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported model_forward = self.model.forward if self.framework == "pt" else self.model.call if "use_cache" in inspect.signature(model_forward).parameters.keys(): model_inputs["use_cache"] = False return self.model(**model_inputs)
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True): # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "regression": function_to_apply = ClassificationFunction.NONE elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: function_to_apply = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: function_to_apply = ClassificationFunction.SOFTMAX elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
function_to_apply = self.model.config.function_to_apply else: function_to_apply = ClassificationFunction.NONE
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
outputs = model_outputs["logits"][0] if self.framework == "pt": # To enable using fp16 and bf16 outputs = outputs.float().numpy() else: outputs = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: scores = sigmoid(outputs) elif function_to_apply == ClassificationFunction.SOFTMAX: scores = softmax(outputs) elif function_to_apply == ClassificationFunction.NONE: scores = outputs else: raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}") if top_k == 1 and _legacy: return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()}
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
dict_scores = [ {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores) ] if not _legacy: dict_scores.sort(key=lambda x: x["score"], reverse=True) if top_k is not None: dict_scores = dict_scores[:top_k] return dict_scores
437
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py
class ModelType(ExplicitEnum): LayoutLM = "layoutlm" LayoutLMv2andv3 = "layoutlmv2andv3" VisionEncoderDecoder = "vision_encoder_decoder"
438
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
class DocumentQuestionAnsweringPipeline(ChunkPipeline): # TODO: Update task_summary docs to include an example with document QA and then update the first sentence """ Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are similar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context. Example: ```python >>> from transformers import pipeline >>> document_qa = pipeline(model="impira/layoutlm-document-qa") >>> document_qa( ... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", ... question="What is the invoice number?", ... ) [{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}] ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
This document question answering pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"document-question-answering"`. The models that this pipeline can use are models that have been fine-tuned on a document question answering task. See the up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=document-question-answering). """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.tokenizer is not None and not self.tokenizer.__class__.__name__.endswith("Fast"): raise ValueError( "`DocumentQuestionAnsweringPipeline` requires a fast tokenizer, but a slow tokenizer " f"(`{self.tokenizer.__class__.__name__}`) is provided." )
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if self.model.config.__class__.__name__ == "VisionEncoderDecoderConfig": self.model_type = ModelType.VisionEncoderDecoder if self.model.config.encoder.model_type != "donut-swin": raise ValueError("Currently, the only supported VisionEncoderDecoder model is Donut") else: self.check_model_type(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES) if self.model.config.__class__.__name__ == "LayoutLMConfig": self.model_type = ModelType.LayoutLM else: self.model_type = ModelType.LayoutLMv2andv3
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
def _sanitize_parameters( self, padding=None, doc_stride=None, max_question_len=None, lang: Optional[str] = None, tesseract_config: Optional[str] = None, max_answer_len=None, max_seq_len=None, top_k=None, handle_impossible_answer=None, timeout=None, **kwargs, ): preprocess_params, postprocess_params = {}, {} if padding is not None: preprocess_params["padding"] = padding if doc_stride is not None: preprocess_params["doc_stride"] = doc_stride if max_question_len is not None: preprocess_params["max_question_len"] = max_question_len if max_seq_len is not None: preprocess_params["max_seq_len"] = max_seq_len if lang is not None: preprocess_params["lang"] = lang if tesseract_config is not None: preprocess_params["tesseract_config"] = tesseract_config if timeout is not None:
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
preprocess_params["timeout"] = timeout
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if top_k is not None: if top_k < 1: raise ValueError(f"top_k parameter should be >= 1 (got {top_k})") postprocess_params["top_k"] = top_k if max_answer_len is not None: if max_answer_len < 1: raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len}") postprocess_params["max_answer_len"] = max_answer_len if handle_impossible_answer is not None: postprocess_params["handle_impossible_answer"] = handle_impossible_answer forward_params = {} if self.assistant_model is not None: forward_params["assistant_model"] = self.assistant_model if self.assistant_tokenizer is not None: forward_params["tokenizer"] = self.tokenizer forward_params["assistant_tokenizer"] = self.assistant_tokenizer return preprocess_params, forward_params, postprocess_params
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
def __call__( self, image: Union["Image.Image", str], question: Optional[str] = None, word_boxes: Tuple[str, List[float]] = None, **kwargs, ): """ Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an optional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not provided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for LayoutLM-like models which require them as input. For Donut, no OCR is run. You can invoke the pipeline several ways: - `pipeline(image=image, question=question)` - `pipeline(image=image, question=question, word_boxes=word_boxes)` - `pipeline([{"image": image, "question": question}])` - `pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])`
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
Args: image (`str` or `PIL.Image`): The pipeline handles three types of images: - A string containing a http link pointing to an image - A string containing a local path to an image - An image loaded in PIL directly
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
The pipeline accepts either a single image or a batch of images. If given a single image, it can be broadcasted to multiple questions. question (`str`): A question to ask of the document. word_boxes (`List[str, Tuple[float, float, float, float]]`, *optional*): A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the pipeline will use these words and boxes instead of running OCR on the image to derive them for models that need them (e.g. LayoutLM). This allows you to reuse OCR'd results across many invocations of the pipeline without having to re-run it each time. top_k (`int`, *optional*, defaults to 1): The number of answers to return (will be chosen by order of likelihood). Note that we return less than top_k answers if there are not enough options available within the context.
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
doc_stride (`int`, *optional*, defaults to 128): If the words in the document are too long to fit with the question for the model, it will be split in several chunks with some overlap. This argument controls the size of that overlap. max_answer_len (`int`, *optional*, defaults to 15): The maximum length of predicted answers (e.g., only answers with a shorter length are considered). max_seq_len (`int`, *optional*, defaults to 384): The maximum length of the total sentence (context + question) in tokens of each chunk passed to the model. The context will be split in several chunks (using `doc_stride` as overlap) if needed. max_question_len (`int`, *optional*, defaults to 64): The maximum length of the question after tokenization. It will be truncated if needed. handle_impossible_answer (`bool`, *optional*, defaults to `False`):
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
Whether or not we accept impossible as an answer. lang (`str`, *optional*): Language to use while running OCR. Defaults to english. tesseract_config (`str`, *optional*): Additional flags to pass to tesseract while running OCR. timeout (`float`, *optional*, defaults to None): The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever.
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
Return: A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys: - **score** (`float`) -- The probability associated to the answer. - **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided `word_boxes`). - **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided `word_boxes`). - **answer** (`str`) -- The answer to the question. - **words** (`list[int]`) -- The index of each word/box pair that is in the answer """ if isinstance(question, str): inputs = {"question": question, "image": image} if word_boxes is not None: inputs["word_boxes"] = word_boxes else: inputs = image return super().__call__(inputs, **kwargs)
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
def preprocess( self, input, padding="do_not_pad", doc_stride=None, max_seq_len=None, word_boxes: Tuple[str, List[float]] = None, lang=None, tesseract_config="", timeout=None, ): # NOTE: This code mirrors the code in question answering and will be implemented in a follow up PR # to support documents with enough tokens that overflow the model's window if max_seq_len is None: max_seq_len = self.tokenizer.model_max_length if doc_stride is None: doc_stride = min(max_seq_len // 2, 256)
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
image = None image_features = {} if input.get("image", None) is not None: image = load_image(input["image"], timeout=timeout) if self.image_processor is not None: image_inputs = self.image_processor(images=image, return_tensors=self.framework) if self.framework == "pt": image_inputs = image_inputs.to(self.torch_dtype) image_features.update(image_inputs) elif self.feature_extractor is not None: image_features.update(self.feature_extractor(images=image, return_tensors=self.framework)) elif self.model_type == ModelType.VisionEncoderDecoder: raise ValueError("If you are using a VisionEncoderDecoderModel, you must provide a feature extractor")
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
words, boxes = None, None if not self.model_type == ModelType.VisionEncoderDecoder: if "word_boxes" in input: words = [x[0] for x in input["word_boxes"]] boxes = [x[1] for x in input["word_boxes"]] elif "words" in image_features and "boxes" in image_features: words = image_features.pop("words")[0] boxes = image_features.pop("boxes")[0] elif image is not None: if not TESSERACT_LOADED: raise ValueError( "If you provide an image without word_boxes, then the pipeline will run OCR using Tesseract," " but pytesseract is not available" ) if TESSERACT_LOADED: words, boxes = apply_tesseract(image, lang=lang, tesseract_config=tesseract_config) else: raise ValueError(
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
"You must provide an image or word_boxes. If you provide an image, the pipeline will automatically" " run OCR to derive words and boxes" )
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if self.tokenizer.padding_side != "right": raise ValueError( "Document question answering only supports tokenizers whose padding side is 'right', not" f" {self.tokenizer.padding_side}" )
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if self.model_type == ModelType.VisionEncoderDecoder: task_prompt = f'<s_docvqa><s_question>{input["question"]}</s_question><s_answer>' # Adapted from https://huggingface.co/spaces/nielsr/donut-docvqa/blob/main/app.py encoding = { "inputs": image_features["pixel_values"], "decoder_input_ids": self.tokenizer( task_prompt, add_special_tokens=False, return_tensors=self.framework ).input_ids, "return_dict_in_generate": True, } yield { **encoding, "p_mask": None, "word_ids": None, "words": None, "output_attentions": True, "is_last": True, } else: tokenizer_kwargs = {} if self.model_type == ModelType.LayoutLM: tokenizer_kwargs["text"] = input["question"].split()
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
tokenizer_kwargs["text_pair"] = words tokenizer_kwargs["is_split_into_words"] = True else: tokenizer_kwargs["text"] = [input["question"]] tokenizer_kwargs["text_pair"] = [words] tokenizer_kwargs["boxes"] = [boxes]
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
encoding = self.tokenizer( padding=padding, max_length=max_seq_len, stride=doc_stride, return_token_type_ids=True, truncation="only_second", return_overflowing_tokens=True, **tokenizer_kwargs, ) # TODO: check why slower `LayoutLMTokenizer` and `LayoutLMv2Tokenizer` don't have this key in outputs # FIXME: ydshieh and/or Narsil encoding.pop("overflow_to_sample_mapping", None) # We do not use this num_spans = len(encoding["input_ids"])
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
# p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens) # This logic mirrors the logic in the question_answering pipeline p_mask = np.array([[tok != 1 for tok in encoding.sequence_ids(span_id)] for span_id in range(num_spans)]) for span_idx in range(num_spans): if self.framework == "pt": span_encoding = {k: torch.tensor(v[span_idx : span_idx + 1]) for (k, v) in encoding.items()} if "pixel_values" in image_features: span_encoding["image"] = image_features["pixel_values"] else: raise ValueError("Unsupported: Tensorflow preprocessing for DocumentQuestionAnsweringPipeline")
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
input_ids_span_idx = encoding["input_ids"][span_idx] # keep the cls_token unmasked (some models use it to indicate unanswerable questions) if self.tokenizer.cls_token_id is not None: cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0] for cls_index in cls_indices: p_mask[span_idx][cls_index] = 0
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
# For each span, place a bounding box [0,0,0,0] for question and CLS tokens, [1000,1000,1000,1000] # for SEP tokens, and the word's bounding box for words in the original document. if "boxes" not in tokenizer_kwargs: bbox = [] for input_id, sequence_id, word_id in zip( encoding.input_ids[span_idx], encoding.sequence_ids(span_idx), encoding.word_ids(span_idx), ): if sequence_id == 1: bbox.append(boxes[word_id]) elif input_id == self.tokenizer.sep_token_id: bbox.append([1000] * 4) else: bbox.append([0] * 4)
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if self.framework == "pt": span_encoding["bbox"] = torch.tensor(bbox).unsqueeze(0) elif self.framework == "tf": raise ValueError("Unsupported: Tensorflow preprocessing for DocumentQuestionAnsweringPipeline") yield { **span_encoding, "p_mask": p_mask[span_idx], "word_ids": encoding.word_ids(span_idx), "words": words, "is_last": span_idx == num_spans - 1, } def _forward(self, model_inputs, **generate_kwargs): p_mask = model_inputs.pop("p_mask", None) word_ids = model_inputs.pop("word_ids", None) words = model_inputs.pop("words", None) is_last = model_inputs.pop("is_last", False)
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if self.model_type == ModelType.VisionEncoderDecoder: # User-defined `generation_config` passed to the pipeline call take precedence if "generation_config" not in generate_kwargs: generate_kwargs["generation_config"] = self.generation_config model_outputs = self.model.generate(**model_inputs, **generate_kwargs) else: model_outputs = self.model(**model_inputs) model_outputs = dict(model_outputs.items()) model_outputs["p_mask"] = p_mask model_outputs["word_ids"] = word_ids model_outputs["words"] = words model_outputs["attention_mask"] = model_inputs.get("attention_mask", None) model_outputs["is_last"] = is_last return model_outputs
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
def postprocess(self, model_outputs, top_k=1, **kwargs): if self.model_type == ModelType.VisionEncoderDecoder: answers = [self.postprocess_encoder_decoder_single(o) for o in model_outputs] else: answers = self.postprocess_extractive_qa(model_outputs, top_k=top_k, **kwargs) answers = sorted(answers, key=lambda x: x.get("score", 0), reverse=True)[:top_k] return answers def postprocess_encoder_decoder_single(self, model_outputs, **kwargs): sequence = self.tokenizer.batch_decode(model_outputs["sequences"])[0]
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
# TODO: A lot of this logic is specific to Donut and should probably be handled in the tokenizer # (see https://github.com/huggingface/transformers/pull/18414/files#r961747408 for more context). sequence = sequence.replace(self.tokenizer.eos_token, "").replace(self.tokenizer.pad_token, "") sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token ret = { "answer": None, } answer = re.search(r"<s_answer>(.*)</s_answer>", sequence) if answer is not None: ret["answer"] = answer.group(1).strip() return ret def postprocess_extractive_qa( self, model_outputs, top_k=1, handle_impossible_answer=False, max_answer_len=15, **kwargs ): min_null_score = 1000000 # large and positive answers = [] for output in model_outputs: words = output["words"]
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
starts, ends, scores, min_null_score = select_starts_ends( start=output["start_logits"], end=output["end_logits"], p_mask=output["p_mask"], attention_mask=output["attention_mask"].numpy() if output.get("attention_mask", None) is not None else None, min_null_score=min_null_score, top_k=top_k, handle_impossible_answer=handle_impossible_answer, max_answer_len=max_answer_len, ) word_ids = output["word_ids"] for start, end, score in zip(starts, ends, scores): word_start, word_end = word_ids[start], word_ids[end] if word_start is not None and word_end is not None: answers.append( { "score": float(score), "answer": " ".join(words[word_start : word_end + 1]),
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
"start": word_start, "end": word_end, } )
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
if handle_impossible_answer: answers.append({"score": min_null_score, "answer": "", "start": 0, "end": 0}) return answers
439
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/document_question_answering.py
class ReturnType(enum.Enum): TENSORS = 0 NEW_TEXT = 1 FULL_TEXT = 2
440
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
class Chat: """This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats to this format because the rest of the pipeline code tends to assume that lists of messages are actually a batch of samples rather than messages in the same conversation.""" def __init__(self, messages: Dict): for message in messages: if not ("role" in message and "content" in message): raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.") self.messages = messages
441
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
class TextGenerationPipeline(Pipeline): """ Language generation pipeline using any `ModelWithLMHead`. This pipeline predicts the words that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys. Examples: ```python >>> from transformers import pipeline >>> generator = pipeline(model="openai-community/gpt2") >>> generator("I can't believe you did such a ", do_sample=False) [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
>>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions. >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False) ``` ```python >>> from transformers import pipeline >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta") >>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2) [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}] ```
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about text generation parameters in [Text generation strategies](../generation_strategies) and [Text generation](text_generation). This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"text-generation"`. The models that this pipeline can use are models that have been trained with an autoregressive language modeling objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation) and the list of [conversational models](https://huggingface.co/models?other=conversational) on [huggingface.co/models]. """
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
# Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia # in https://github.com/rusiaaman/XLNet-gen#methodology # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e XL_PREFIX = """ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision and denounces one of the men as a horse thief. Although his father initially slaps him for making such an accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing. <eod> </s> <eos> """
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING_NAMES ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. prefix = None if self.prefix is not None: prefix = self.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
prefix = self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params) self._preprocess_params = {**self._preprocess_params, **preprocess_params} self._forward_params = {**self._forward_params, **forward_params}
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
def _sanitize_parameters( self, return_full_text=None, return_tensors=None, return_text=None, return_type=None, clean_up_tokenization_spaces=None, prefix=None, handle_long_generation=None, stop_sequence=None, truncation=None, max_length=None, continue_final_message=None, **generate_kwargs, ): preprocess_params = {} add_special_tokens = False if "add_special_tokens" in generate_kwargs: add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens") if "padding" in generate_kwargs: preprocess_params["padding"] = generate_kwargs.pop("padding") if truncation is not None: preprocess_params["truncation"] = truncation if max_length is not None: preprocess_params["max_length"] = max_length generate_kwargs["max_length"] = max_length
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
if prefix is not None: preprocess_params["prefix"] = prefix if prefix: prefix_inputs = self.tokenizer( prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors=self.framework ) generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" " [None, 'hole']" ) preprocess_params["handle_long_generation"] = handle_long_generation if continue_final_message is not None: preprocess_params["continue_final_message"] = continue_final_message preprocess_params.update(generate_kwargs) forward_params = generate_kwargs
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
postprocess_params = {} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_full_text`") if return_tensors is not None: raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`") return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("`return_text` is mutually exclusive with `return_tensors`") return_type = ReturnType.TENSORS if return_type is not None: postprocess_params["return_type"] = return_type if clean_up_tokenization_spaces is not None: postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces if continue_final_message is not None:
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
postprocess_params["continue_final_message"] = continue_final_message
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
if stop_sequence is not None: stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False) generate_kwargs["eos_token_id"] = stop_sequence_ids if self.assistant_model is not None: forward_params["assistant_model"] = self.assistant_model if self.assistant_tokenizer is not None: forward_params["tokenizer"] = self.tokenizer forward_params["assistant_tokenizer"] = self.assistant_tokenizer return preprocess_params, forward_params, postprocess_params # overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments def _parse_and_tokenize(self, *args, **kwargs): """ Parse arguments and tokenize """ # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"add_space_before_punct_symbol": True}) return super()._parse_and_tokenize(*args, **kwargs)
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
def __call__(self, text_inputs, **kwargs): """ Complete the prompt(s) given as inputs.
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
Args: text_inputs (`str`, `List[str]`, List[Dict[str, str]], or `List[List[Dict[str, str]]]`): One or several prompts (or one list of prompts) to complete. If strings or a list of string are passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed, the model's chat template will be used to format them before passing them to the model. return_tensors (`bool`, *optional*, defaults to `False`): Returns the tensors of predictions (as token indices) in the outputs. If set to `True`, the decoded text is not returned. return_text (`bool`, *optional*): Returns the decoded texts in the outputs. return_full_text (`bool`, *optional*, defaults to `True`):
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
If set to `False` only added text is returned, otherwise the full text is returned. Cannot be specified at the same time as `return_text`. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`): Whether or not to clean up the potential extra spaces in the text output. continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the last message in the input chat rather than starting a new one, allowing you to "prefill" its response. By default this is `True` when the final message in the input chat has the `assistant` role and `False` otherwise, but you can manually override that behaviour by setting this flag. prefix (`str`, *optional*): Prefix added to prompt. handle_long_generation (`str`, *optional*):
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
By default, this pipelines does not handle long generation (ones that exceed in one form or the other the model maximum length). There is no perfect way to adress this (more info :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common strategies to work around that problem depending on your use case.
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
- `None` : default strategy where nothing in particular happens - `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might truncate a lot of the prompt and not suitable when generation exceed the model capacity) generate_kwargs (`dict`, *optional*): Additional keyword arguments to pass along to the generate method of the model (see the generate method corresponding to your framework [here](./text_generation)). Return: A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination of both `generated_text` and `generated_token_ids`):
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
- **generated_text** (`str`, present when `return_text=True`) -- The generated text. - **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token ids of the generated text. """ if isinstance( text_inputs, (list, tuple, types.GeneratorType, KeyDataset) if is_torch_available() else (list, tuple, types.GeneratorType), ): if isinstance(text_inputs, types.GeneratorType): text_inputs, _ = itertools.tee(text_inputs) text_inputs, first_item = (x for x in text_inputs), next(_) else: first_item = text_inputs[0] if isinstance(first_item, (list, tuple, dict)): # We have one or more prompts in list-of-dicts format, so this is chat mode if isinstance(first_item, dict): return super().__call__(Chat(text_inputs), **kwargs)
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
else: chats = (Chat(chat) for chat in text_inputs) # 🐈 🐈 🐈 if isinstance(text_inputs, types.GeneratorType): return super().__call__(chats, **kwargs) else: return super().__call__(list(chats), **kwargs) return super().__call__(text_inputs, **kwargs)
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
def preprocess( self, prompt_text, prefix="", handle_long_generation=None, add_special_tokens=None, truncation=None, padding=None, max_length=None, continue_final_message=None, **generate_kwargs, ): # Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults tokenizer_kwargs = { "add_special_tokens": add_special_tokens, "truncation": truncation, "padding": padding, "max_length": max_length, } tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None}
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
if isinstance(prompt_text, Chat): tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default # because very few models support multiple separate, consecutive assistant messages if continue_final_message is None: continue_final_message = prompt_text.messages[-1]["role"] == "assistant" inputs = self.tokenizer.apply_chat_template( prompt_text.messages, add_generation_prompt=not continue_final_message, continue_final_message=continue_final_message, return_dict=True, return_tensors=self.framework, **tokenizer_kwargs, ) else: inputs = self.tokenizer(prefix + prompt_text, return_tensors=self.framework, **tokenizer_kwargs) inputs["prompt_text"] = prompt_text
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
if handle_long_generation == "hole": cur_len = inputs["input_ids"].shape[-1] if "max_new_tokens" in generate_kwargs: new_tokens = generate_kwargs["max_new_tokens"] else: new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len if new_tokens < 0: raise ValueError("We cannot infer how many new tokens are expected") if cur_len + new_tokens > self.tokenizer.model_max_length: keep_length = self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" " models max length" )
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
inputs["input_ids"] = inputs["input_ids"][:, -keep_length:] if "attention_mask" in inputs: inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:] return inputs def _forward(self, model_inputs, **generate_kwargs): input_ids = model_inputs["input_ids"] attention_mask = model_inputs.get("attention_mask", None) # Allow empty prompts if input_ids.shape[1] == 0: input_ids = None attention_mask = None in_b = 1 else: in_b = input_ids.shape[0] prompt_text = model_inputs.pop("prompt_text")
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. prefix_length = generate_kwargs.pop("prefix_length", 0) if prefix_length > 0: has_max_new_tokens = "max_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].max_new_tokens is not None ) if not has_max_new_tokens: generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length generate_kwargs["max_length"] += prefix_length has_min_new_tokens = "min_new_tokens" in generate_kwargs or ( "generation_config" in generate_kwargs and generate_kwargs["generation_config"].min_new_tokens is not None )
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
# User-defined `generation_config` passed to the pipeline call take precedence if "generation_config" not in generate_kwargs: generate_kwargs["generation_config"] = self.generation_config generated_sequence = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs) out_b = generated_sequence.shape[0] if self.framework == "pt": generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:]) elif self.framework == "tf": generated_sequence = tf.reshape(generated_sequence, (in_b, out_b // in_b, *generated_sequence.shape[1:])) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
def postprocess( self, model_outputs, return_type=ReturnType.FULL_TEXT, clean_up_tokenization_spaces=True, continue_final_message=None, ): generated_sequence = model_outputs["generated_sequence"][0] input_ids = model_outputs["input_ids"] prompt_text = model_outputs["prompt_text"] generated_sequence = generated_sequence.numpy().tolist() records = [] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: record = {"generated_token_ids": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text text = self.tokenizer.decode( sequence, skip_special_tokens=True, clean_up_tokenization_spaces=clean_up_tokenization_spaces, )
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: prompt_length = 0 else: prompt_length = len( self.tokenizer.decode( input_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=clean_up_tokenization_spaces, ) )
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
all_text = text[prompt_length:] if return_type == ReturnType.FULL_TEXT: if isinstance(prompt_text, str): all_text = prompt_text + all_text elif isinstance(prompt_text, Chat): if continue_final_message is None: # If the user passes a chat ending in an assistant message, we treat it as a prefill by # default because very few models support multiple separate, consecutive assistant messages continue_final_message = prompt_text.messages[-1]["role"] == "assistant" if continue_final_message: # With assistant prefill, concat onto the end of the last message all_text = list(prompt_text.messages)[:-1] + [ { "role": prompt_text.messages[-1]["role"],
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
"content": prompt_text.messages[-1]["content"] + all_text, } ] else: # When we're not starting from a prefill, the output is a new assistant message all_text = list(prompt_text.messages) + [{"role": "assistant", "content": all_text}] record = {"generated_text": all_text} records.append(record)
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
return records
442
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_generation.py
class ZeroShotObjectDetectionPipeline(ChunkPipeline): """ Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of objects when you provide an image and a set of `candidate_labels`. Example: ```python >>> from transformers import pipeline >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection") >>> detector( ... "http://images.cocodataset.org/val2017/000000039769.jpg", ... candidate_labels=["cat", "couch"], ... ) [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
>>> detector( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", ... candidate_labels=["head", "bird"], ... ) [{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}] ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"zero-shot-object-detection"`. See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection). """ def __init__(self, **kwargs): super().__init__(**kwargs) if self.framework == "tf": raise ValueError(f"The {self.__class__} is only available in PyTorch.") requires_backends(self, "vision") self.check_model_type(MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES)
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
def __call__( self, image: Union[str, "Image.Image", List[Dict[str, Any]]], candidate_labels: Union[str, List[str]] = None, **kwargs, ): """ Detect objects (bounding boxes & classes) in the image(s) passed as inputs. Args: image (`str`, `PIL.Image` or `List[Dict[str, Any]]`): The pipeline handles three types of images: - A string containing an http url pointing to an image - A string containing a local path to an image - An image loaded in PIL directly You can use this parameter to send directly a list of images, or a dataset or a generator like so: ```python >>> from transformers import pipeline
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
>>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection") >>> detector( ... [ ... { ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg", ... "candidate_labels": ["cat", "couch"], ... }, ... { ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg", ... "candidate_labels": ["cat", "couch"], ... }, ... ] ... )
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
[[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]] ```
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
candidate_labels (`str` or `List[str]` or `List[List[str]]`): What the model should recognize in the image. threshold (`float`, *optional*, defaults to 0.1): The probability necessary to make a prediction. top_k (`int`, *optional*, defaults to None): The number of top predictions that will be returned by the pipeline. If the provided number is `None` or higher than the number of predictions available, it will default to the number of predictions. timeout (`float`, *optional*, defaults to None): The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Return: A list of lists containing prediction results, one list per input image. Each list contains dictionaries with the following keys:
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
- **label** (`str`) -- Text query corresponding to the found object. - **score** (`float`) -- Score corresponding to the object (between 0 and 1). - **box** (`Dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys. """ if "text_queries" in kwargs: candidate_labels = kwargs.pop("text_queries")
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
if isinstance(image, (str, Image.Image)): inputs = {"image": image, "candidate_labels": candidate_labels} elif isinstance(image, (list, tuple)) and valid_images(image): return list( super().__call__( ({"image": img, "candidate_labels": labels} for img, labels in zip(image, candidate_labels)), **kwargs, ) ) else: """ Supports the following format - {"image": image, "candidate_labels": candidate_labels} - [{"image": image, "candidate_labels": candidate_labels}] - Generator and datasets This is a common pattern in other multimodal pipelines, so we support it here as well. """ inputs = image results = super().__call__(inputs, **kwargs) return results
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
def _sanitize_parameters(self, **kwargs): preprocess_params = {} if "timeout" in kwargs: preprocess_params["timeout"] = kwargs["timeout"] postprocess_params = {} if "threshold" in kwargs: postprocess_params["threshold"] = kwargs["threshold"] if "top_k" in kwargs: postprocess_params["top_k"] = kwargs["top_k"] return preprocess_params, {}, postprocess_params def preprocess(self, inputs, timeout=None): image = load_image(inputs["image"], timeout=timeout) candidate_labels = inputs["candidate_labels"] if isinstance(candidate_labels, str): candidate_labels = candidate_labels.split(",")
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
target_size = torch.tensor([[image.height, image.width]], dtype=torch.int32) for i, candidate_label in enumerate(candidate_labels): text_inputs = self.tokenizer(candidate_label, return_tensors=self.framework) image_features = self.image_processor(image, return_tensors=self.framework) if self.framework == "pt": image_features = image_features.to(self.torch_dtype) yield { "is_last": i == len(candidate_labels) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def _forward(self, model_inputs): target_size = model_inputs.pop("target_size") candidate_label = model_inputs.pop("candidate_label") is_last = model_inputs.pop("is_last") outputs = self.model(**model_inputs)
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
model_outputs = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs} return model_outputs def postprocess(self, model_outputs, threshold=0.1, top_k=None): results = [] for model_output in model_outputs: label = model_output["candidate_label"] model_output = BaseModelOutput(model_output) outputs = self.image_processor.post_process_object_detection( outputs=model_output, threshold=threshold, target_sizes=model_output["target_size"] )[0] for index in outputs["scores"].nonzero(): score = outputs["scores"][index].item() box = self._get_bounding_box(outputs["boxes"][index][0]) result = {"score": score, "label": label, "box": box} results.append(result) results = sorted(results, key=lambda x: x["score"], reverse=True) if top_k: results = results[:top_k]
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
return results def _get_bounding_box(self, box: "torch.Tensor") -> Dict[str, int]: """ Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... } Args: box (`torch.Tensor`): Tensor containing the coordinates in corners format. Returns: bbox (`Dict[str, int]`): Dict containing the coordinates in corners format. """ if self.framework != "pt": raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch.") xmin, ymin, xmax, ymax = box.int().tolist() bbox = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
443
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_object_detection.py
class AutomaticSpeechRecognitionPipeline(ChunkPipeline): """ Pipeline that aims at extracting spoken text contained within some audio. The input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for to support multiple audio formats Example: ```python >>> from transformers import pipeline >>> transcriber = pipeline(model="openai/whisper-base") >>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac") {'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'} ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
Arguments: model ([`PreTrainedModel`] or [`TFPreTrainedModel`]): The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [`PreTrainedModel`] for PyTorch and [`TFPreTrainedModel`] for TensorFlow. feature_extractor ([`SequenceFeatureExtractor`]): The feature extractor that will be used by the pipeline to encode waveform for the model. tokenizer ([`PreTrainedTokenizer`]): The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [`PreTrainedTokenizer`]. decoder (`pyctcdecode.BeamSearchDecoderCTC`, *optional*): [PyCTCDecode's BeamSearchDecoderCTC](https://github.com/kensho-technologies/pyctcdecode/blob/2fd33dc37c4111417e08d89ccd23d28e9b308d19/pyctcdecode/decoder.py#L180) can be passed for language model boosted decoding. See [`Wav2Vec2ProcessorWithLM`] for more information.
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
chunk_length_s (`float`, *optional*, defaults to 0): The input length for in each chunk. If `chunk_length_s = 0` then chunking is disabled (default).
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
<Tip> For more information on how to effectively use `chunk_length_s`, please have a look at the [ASR chunking blog post](https://huggingface.co/blog/asr-chunking). </Tip> stride_length_s (`float`, *optional*, defaults to `chunk_length_s / 6`): The length of stride on the left and right of each chunk. Used only with `chunk_length_s > 0`. This enables the model to *see* more context and infer letters better than without this context but the pipeline discards the stride bits at the end to make the final reconstitution as perfect as possible. <Tip> For more information on how to effectively use `stride_length_s`, please have a look at the [ASR chunking blog post](https://huggingface.co/blog/asr-chunking). </Tip>
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
framework (`str`, *optional*): The framework to use, either `"pt"` for PyTorch or `"tf"` for TensorFlow. The specified framework must be installed. If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is provided. device (Union[`int`, `torch.device`], *optional*): Device ordinal for CPU/GPU supports. Setting this to `None` will leverage CPU, a positive will run the model on the associated CUDA device id. torch_dtype (Union[`int`, `torch.dtype`], *optional*): The data-type (dtype) of the computation. Setting this to `None` will use float32 precision. Set to `torch.float16` or `torch.bfloat16` to use half-precision in the respective dtypes. """
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
def __init__( self, model: "PreTrainedModel", feature_extractor: Union["SequenceFeatureExtractor", str] = None, tokenizer: Optional[PreTrainedTokenizer] = None, decoder: Optional[Union["BeamSearchDecoderCTC", str]] = None, device: Union[int, "torch.device"] = None, torch_dtype: Optional[Union[str, "torch.dtype"]] = None, **kwargs, ): # set the model type so we can check we have the right pre- and post-processing parameters if model.config.model_type == "whisper": self.type = "seq2seq_whisper" elif model.__class__.__name__ in MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.values(): self.type = "seq2seq" elif ( feature_extractor._processor_class and feature_extractor._processor_class.endswith("WithLM") and decoder is not None ): self.decoder = decoder self.type = "ctc_with_lm" else: self.type = "ctc"
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
super().__init__(model, tokenizer, feature_extractor, device=device, torch_dtype=torch_dtype, **kwargs) def __call__( self, inputs: Union[np.ndarray, bytes, str], **kwargs, ): """ Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more information.
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
Args: inputs (`np.ndarray` or `bytes` or `str` or `dict`): The inputs is either : - `str` that is either the filename of a local audio file, or a public URL address to download the audio file. The file will be read at the correct sampling rate to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system. - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the same way. - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`) Raw audio at the correct sampling rate (no further check will be done) - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this pipeline do the resampling. The dict must be in the format `{"sampling_rate": int, "raw":
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
np.array}` with optionally a `"stride": (left: int, right: int)` than can ask the pipeline to treat the first `left` samples and last `right` samples to be ignored in decoding (but used at inference to provide more context to the model). Only use `stride` with CTC models. return_timestamps (*optional*, `str` or `bool`): Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for other sequence-to-sequence models.
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
For CTC models, timestamps can take one of two formats: - `"char"`: the pipeline will return timestamps along the text for every character in the text. For instance, if you get `[{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7, 0.9)}]`, then it means the model predicts that the letter "h" was spoken after `0.5` and before `0.6` seconds. - `"word"`: the pipeline will return timestamps along the text for every word in the text. For instance, if you get `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]`, then it means the model predicts that the word "hi" was spoken after `0.5` and before `0.9` seconds.
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
For the Whisper model, timestamps can take one of two formats: - `"word"`: same as above for word-level CTC timestamps. Word-level timestamps are predicted through the *dynamic-time warping (DTW)* algorithm, an approximation to word-level timestamps by inspecting the cross-attention weights. - `True`: the pipeline will return timestamps along the text for *segments* of words in the text. For instance, if you get `[{"text": " Hi there!", "timestamp": (0.5, 1.5)}]`, then it means the model predicts that the segment "Hi there!" was spoken after `0.5` and before `1.5` seconds. Note that a segment of text refers to a sequence of one or more words, rather than individual words as with word-level timestamps. generate_kwargs (`dict`, *optional*):
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a complete overview of generate, check the [following guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation).
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
Return: `Dict`: A dictionary with the following keys: - **text** (`str`): The recognized text. - **chunks** (*optional(, `List[Dict]`) When using `return_timestamps`, the `chunks` will become a list containing all the various text chunks identified by the model, *e.g.* `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp": (1.0, 1.5)}]`. The original full text can roughly be recovered by doing `"".join(chunk["text"] for chunk in output["chunks"])`. """ return super().__call__(inputs, **kwargs)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
def _sanitize_parameters( self, chunk_length_s=None, stride_length_s=None, ignore_warning=None, decoder_kwargs=None, return_timestamps=None, return_language=None, generate_kwargs=None, max_new_tokens=None, ): # No parameters on this pipeline right now preprocess_params = {} if chunk_length_s is not None: if self.type == "seq2seq" and not ignore_warning: logger.warning( "Using `chunk_length_s` is very experimental with seq2seq models. The results will not necessarily" " be entirely accurate and will have caveats. More information:" " https://github.com/huggingface/transformers/pull/20104. Ignore this warning with pipeline(...," " ignore_warning=True)" ) preprocess_params["chunk_length_s"] = chunk_length_s if stride_length_s is not None:
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py