text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
The models that this pipeline can use are models that have been fine-tuned on a question answering task. See the
up-to-date list of available models on
[huggingface.co/models](https://huggingface.co/models?filter=question-answering).
"""
default_input_names = "question,context"
handle_impossible_an... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
self._args_parser = QuestionAnsweringArgumentHandler()
self.check_model_type(
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
if self.framework == "tf"
else MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
@staticmethod
def create_sample(
question: Union[st... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
Returns:
One or a list of [`SquadExample`]: The corresponding [`SquadExample`] grouping question and context.
"""
if isinstance(question, list):
return [SquadExample(None, q, c, None, None, None) for q, c in zip(question, context)]
else:
return SquadExample(No... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
def _sanitize_parameters(
self,
padding=None,
topk=None,
top_k=None,
doc_stride=None,
max_answer_len=None,
max_seq_len=None,
max_question_len=None,
handle_impossible_answer=None,
align_to_words=None,
**kwargs,
):
# Set d... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
postprocess_params = {}
if topk is not None and top_k is None:
warnings.warn("topk parameter is deprecated, use top_k instead", UserWarning)
top_k = topk
if top_k is not None:
if top_k < 1:
raise ValueError(f"top_k parameter should be >= 1 (got {top_k}... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
def __call__(self, *args, **kwargs):
"""
Answer the question(s) given as inputs by using the context(s). | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
Args:
question (`str` or `List[str]`):
One or several question(s) (must be used in conjunction with the `context` argument).
context (`str` or `List[str]`):
One or several context(s) associated with the question(s) (must be used in conjunction with the
... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
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 ... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/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 character start index of the answer (in the tokenized version of the input).
- *... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
examples = self._args_parser(*args, **kwargs)
if isinstance(examples, (list, tuple)) and len(examples) == 1:
return super().__call__(examples[0], **kwargs)
return super().__call__(examples, **kwargs)
def preprocess(self, example, padding="do_not_pad", doc_stride=None, max_question_len=6... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
if doc_stride > max_seq_len:
raise ValueError(f"`doc_stride` ({doc_stride}) is larger than `max_seq_len` ({max_seq_len})")
if not self.tokenizer.is_fast:
features = squad_convert_examples_to_features(
examples=[example],
tokenizer=self.tokenizer,
... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
encoded_inputs = self.tokenizer(
text=example.question_text if question_first else example.context_text,
text_pair=example.context_text if question_first else example.question_text,
padding=padding,
truncation="only_second" if question_first else "only_fir... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
# Here we tokenize examples one-by-one so we don't need to use "overflow_to_sample_mapping".
# "num_span" is the number of output samples generated from the overflowing tokens.
num_spans = len(encoded_inputs["input_ids"]) | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/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)
p_mask = [
[tok != 1 if question_first else 0 for tok in encoded_inputs.sequence_ids(... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
features = []
for span_idx in range(num_spans):
input_ids_span_idx = encoded_inputs["input_ids"][span_idx]
attention_mask_span_idx = (
encoded_inputs["attention_mask"][span_idx] if "attention_mask" in encoded_inputs else None
)
... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
input_ids=input_ids_span_idx,
attention_mask=attention_mask_span_idx,
token_type_ids=token_type_ids_span_idx,
p_mask=submask,
encoding=encoded_inputs[span_idx],
# We don't use the rest of the values -... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
for i, feature in enumerate(features):
fw_args = {}
others = {}
model_input_names = self.tokenizer.model_input_names + ["p_mask", "token_type_ids"]
for k, v in feature.__dict__.items():
if k in model_input_names:
if self.framework == "... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
def _forward(self, inputs):
example = inputs["example"]
model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
# `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
model_forward = self.model.forward if self.framework == "pt" else... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
def postprocess(
self,
model_outputs,
top_k=1,
handle_impossible_answer=False,
max_answer_len=15,
align_to_words=True,
):
min_null_score = 1000000 # large and positive
answers = []
for output in model_outputs:
if self.framework == ... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
starts, ends, scores, min_null_score = select_starts_ends(
start_, end_, p_mask, attention_mask, min_null_score, top_k, handle_impossible_answer, max_answer_len
)
if not self.tokenizer.is_fast:
char_to_word = np.array(example.char_to_word_offset) | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
# Convert the answer (tokens) back to the original text
# Score: score from the model
# Start: Index of the first character of the answer in the context string
# End: Index of the character following the last character of the answer in the context string
#... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
# Convert the answer (tokens) back to the original text
# Score: score from the model
# Start: Index of the first character of the answer in the context string
# End: Index of the character following the last character of the answer in the context string
#... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
# Encoding was *not* padded, input_ids *might*.
# It doesn't make a difference unless we're padding on
# the left hand side, since now we have different offsets
# everywhere.
if self.tokenizer.padding_side == "left":
offset = (output["i... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
answers.append(
{
"score": score.item(),
"start": start_index,
"end": end_index,
"answer": example.context_text[start_index:end_index],
}
)
... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
def get_indices(
self, enc: "tokenizers.Encoding", s: int, e: int, sequence_index: int, align_to_words: bool
) -> Tuple[int, int]:
if align_to_words:
try:
start_word = enc.token_to_word(s)
end_word = enc.token_to_word(e)
start_index = enc.w... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
def span_to_answer(self, text: str, start: int, end: int) -> Dict[str, Union[str, int]]:
"""
When decoding from token probabilities, this method maps token indexes to actual word in the initial context.
Args:
text (`str`): The actual context to extract the answer from.
s... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
# Stop if we went over the end of the answer
if token_idx > end:
break
# Append the subtokenization length to the running index
token_idx += len(token)
chars_idx += len(word) + 1
# Join text with spaces
return {
"answer": " ".... | 413 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/question_answering.py |
class ReturnType(enum.Enum):
TENSORS = 0
TEXT = 1 | 414 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
class Text2TextGenerationPipeline(Pipeline):
"""
Pipeline for text to text generation using seq2seq models.
Example:
```python
>>> from transformers import pipeline
>>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap")
>>> generator(
... "answer: Manue... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
This Text2TextGenerationPipeline pipeline can currently be loaded from [`pipeline`] using the following task
identifier: `"text2text-generation"`.
The models that this pipeline can use are models that have been fine-tuned on a translation task. See the
up-to-date list of available models on
[huggingfac... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
self.check_model_type(
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
if self.framework == "tf"
else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
def _sanitize_parameters(
self,
return_tensors=None,
return_text=None,
return_type=None,
... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
if clean_up_tokenization_spaces is not None:
postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
if stop_sequence is not None:
stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False)
if len(stop_sequence_ids) > 1:
... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
def check_inputs(self, input_length: int, min_length: int, max_length: int):
"""
Checks whether there might be something wrong with given input with regard to the model.
"""
return True
def _parse_and_tokenize(self, *args, truncation):
prefix = self.prefix if self.prefix is ... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
elif isinstance(args[0], str):
args = (prefix + args[0],)
padding = False
else:
raise ValueError(
f" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`"
)
inputs = self.tokenizer(*args, padding=pad... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
Args:
args (`str` or `List[str]`):
Input text for the encoder.
return_tensors (`bool`, *optional*, defaults to `False`):
Whether or not to include the tensors of predictions (as token indices) in the outputs.
return_text (`bool`, *optional*, defaults t... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
generate_kwargs:
Additional keyword arguments to pass along to the generate method of the model (see the generate method
corresponding to your framework [here](./text_generation)). | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
Return:
A list or a list of list of `dict`: Each result comes as a dictionary with the following keys:
- **generated_text** (`str`, present when `return_text=True`) -- The generated text.
- **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
def _forward(self, model_inputs, **generate_kwargs):
if self.framework == "pt":
in_b, input_length = model_inputs["input_ids"].shape
elif self.framework == "tf":
in_b, input_length = tf.shape(model_inputs["input_ids"]).numpy()
self.check_inputs(
input_length,... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
output_ids = self.model.generate(**model_inputs, **generate_kwargs)
out_b = output_ids.shape[0]
if self.framework == "pt":
output_ids = output_ids.reshape(in_b, out_b // in_b, *output_ids.shape[1:])
elif self.framework == "tf":
output_ids = tf.reshape(output_ids, (in_b, o... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
def postprocess(self, model_outputs, return_type=ReturnType.TEXT, clean_up_tokenization_spaces=False):
records = []
for output_ids in model_outputs["output_ids"][0]:
if return_type == ReturnType.TENSORS:
record = {f"{self.return_name}_token_ids": output_ids}
elif ... | 415 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
class SummarizationPipeline(Text2TextGenerationPipeline):
"""
Summarize news articles and other documents.
This summarizing pipeline can currently be loaded from [`pipeline`] using the following task identifier:
`"summarization"`.
The models that this pipeline can use are models that have been fin... | 416 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
# use t5 in tf
summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
```"""
# Used in the return key of the pipeline.
return_name = "summary"
def __call__... | 416 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
Args:
documents (*str* or `List[str]`):
One or several articles (or one list of articles) to summarize.
return_text (`bool`, *optional*, defaults to `True`):
Whether or not to include the decoded texts in the outputs
return_tensors (`bool`, *optional*,... | 416 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
- **summary_text** (`str`, present when `return_text=True`) -- The summary of the corresponding input.
- **summary_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token
ids of the summary.
"""
return super().__call__(*args, **kwargs)
... | 416 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
if input_length < max_length:
logger.warning(
f"Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is "
"a summarization task, where outputs shorter than the input are typically wanted, you might "
f"consider decre... | 416 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
class TranslationPipeline(Text2TextGenerationPipeline):
"""
Translates from one language to another.
This translation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
`"translation_xx_to_yy"`.
The models that this pipeline can use are models that have been fi... | 417 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
def check_inputs(self, input_length: int, min_length: int, max_length: int):
if input_length > 0.9 * max_length:
logger.warning(
f"Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider "
"increasing your max_length manuall... | 417 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
def _sanitize_parameters(self, src_lang=None, tgt_lang=None, **kwargs):
preprocess_params, forward_params, postprocess_params = super()._sanitize_parameters(**kwargs)
if src_lang is not None:
preprocess_params["src_lang"] = src_lang
if tgt_lang is not None:
preprocess_par... | 417 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
Args:
args (`str` or `List[str]`):
Texts to be translated.
return_tensors (`bool`, *optional*, defaults to `False`):
Whether or not to include the tensors of predictions (as token indices) in the outputs.
return_text (`bool`, *optional*, defaults to `T... | 417 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
generate_kwargs:
Additional keyword arguments to pass along to the generate method of the model (see the generate method
corresponding to your framework [here](./text_generation)). | 417 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
Return:
A list or a list of list of `dict`: Each result comes as a dictionary with the following keys:
- **translation_text** (`str`, present when `return_text=True`) -- The translation.
- **translation_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) ... | 417 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text2text_generation.py |
class ImageSegmentationPipeline(Pipeline):
"""
Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and
their classes.
Example:
```python
>>> from transformers import pipeline
>>> segmenter = pipeline(model="facebook/detr-resnet-50-p... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
See the list of available models on
[huggingface.co/models](https://huggingface.co/models?filter=image-segmentation).
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.framework == "tf":
raise ValueError(f"The {self.__class__} is only available ... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
def _sanitize_parameters(self, **kwargs):
preprocess_kwargs = {}
postprocess_kwargs = {}
if "subtask" in kwargs:
postprocess_kwargs["subtask"] = kwargs["subtask"]
preprocess_kwargs["subtask"] = kwargs["subtask"]
if "threshold" in kwargs:
postprocess_kw... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing an HTTP(S) link pointing to an image
- A string containing a local path to an image
- An image loaded in PIL... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
same format: all as HTTP(S) links, all as local paths, or all as PIL images.
subtask (`str`, *optional*):
Segmentation task to be performed, choose [`semantic`, `instance` an... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
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. | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
Return:
A dictionary or a list of dictionaries containing the result. If the input is a single image, will return a
list of dictionaries, if the input is a list of several images, will return a list of list of dictionaries
corresponding to each image.
The dictionaries co... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
- **label** (`str`) -- The class label identified by the model.
- **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of
the original image. Returns a mask filled with zeros if no object is found.
- **score** (*optional* `float`) -... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
def preprocess(self, image, subtask=None, timeout=None):
image = load_image(image, timeout=timeout)
target_size = [(image.height, image.width)]
if self.model.config.__class__.__name__ == "OneFormerConfig":
if subtask is None:
kwargs = {}
else:
... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
inputs["target_size"] = target_size
return inputs | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
def _forward(self, model_inputs):
target_size = model_inputs.pop("target_size")
model_outputs = self.model(**model_inputs)
model_outputs["target_size"] = target_size
return model_outputs
def postprocess(
self, model_outputs, subtask=None, threshold=0.9, mask_threshold=0.5, o... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
if fn is not None:
outputs = fn(
model_outputs,
threshold=threshold,
mask_threshold=mask_threshold,
overlap_mask_area_threshold=overlap_mask_area_threshold,
target_sizes=model_outputs["target_size"],
)[0]
... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
elif subtask in {"semantic", None} and hasattr(self.image_processor, "post_process_semantic_segmentation"):
outputs = self.image_processor.post_process_semantic_segmentation(
model_outputs, target_sizes=model_outputs["target_size"]
)[0]
annotation = []
se... | 418 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_segmentation.py |
class VisualQuestionAnsweringPipeline(Pipeline):
"""
Visual Question Answering pipeline using a `AutoModelForVisualQuestionAnswering`. This pipeline is currently only
available in PyTorch.
Example:
```python
>>> from transformers import pipeline
>>> oracle = pipeline(model="dandelin/vilt-... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
>>> oracle(question="Is this a man ?", image=image_url, top_k=1)
[{'score': 0.996, 'answer': 'no'}]
```
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
This visual question answering pipeline can currently be loaded from [`pipeline`] using the following... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
def _sanitize_parameters(self, top_k=None, padding=None, truncation=None, timeout=None, **kwargs):
preprocess_params, postprocess_params = {}, {}
if padding is not None:
preprocess_params["padding"] = padding
if truncation is not None:
preprocess_params["truncation"] = tr... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
def __call__(
self,
image: Union["Image.Image", str, List["Image.Image"], List[str], "KeyDataset"],
question: Union[str, List[str]] = None,
**kwargs,
):
r"""
Answers open-ended questions about images. The pipeline accepts several types of inputs which are detailed
... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_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.
For dataset: the passed in dataset must be of type `transformers.pipelines.pt_utils.KeyDataset`
Example:
```python
... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
```
question (`str`, `List[str]`):
The question(s) asked. If given a single question, it can be broadcasted to multiple images.
If multiple images and questions are given, each and every question will be broadcasted to all images
(same effect as a Cartesian pr... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
- **label** (`str`) -- The label identified by the model.
- **score** (`int`) -- The score attributed by the model for that label.
"""
is_dataset = isinstance(image, KeyDataset)
is_image_batch = isinstance(image, list) and all(isinstance(item, (Image.Image, str)) for item in image)
... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
if isinstance(image, (Image.Image, str)) and isinstance(question, str):
inputs = {"image": image, "question": question}
elif (is_image_batch or is_dataset) and isinstance(question, str):
inputs = [{"image": im, "question": question} for im in image]
elif isinstance(image, (Image.... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
results = super().__call__(inputs, **kwargs)
return results | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
def preprocess(self, inputs, padding=False, truncation=False, timeout=None):
image = load_image(inputs["image"], timeout=timeout)
model_inputs = self.tokenizer(
inputs["question"],
return_tensors=self.framework,
padding=padding,
truncation=truncation,
... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
model_outputs = self.model.generate(**model_inputs, **generate_kwargs)
else:
model_outputs = self.model(**model_inputs)
return model_outputs
def postprocess(self, model_outputs, top_k=5):
if self.model.can_generate():
return [
{"answer": self.tokenize... | 419 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/visual_question_answering.py |
class ClassificationFunction(ExplicitEnum):
SIGMOID = "sigmoid"
SOFTMAX = "softmax"
NONE = "none" | 420 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
class ImageClassificationPipeline(Pipeline):
"""
Image classification pipeline using any `AutoModelForImageClassification`. This pipeline predicts the class of an
image.
Example:
```python
>>> from transformers import pipeline
>>> classifier = pipeline(model="microsoft/beit-base-patch16-2... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
See the list of available models on
[huggingface.co/models](https://huggingface.co/models?filter=image-classification).
"""
function_to_apply: ClassificationFunction = ClassificationFunction.NONE
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
requires_backends(s... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
def _sanitize_parameters(self, top_k=None, function_to_apply=None, timeout=None):
preprocess_params = {}
if timeout is not None:
preprocess_params["timeout"] = timeout
postprocess_params = {}
if top_k is not None:
postprocess_params["top_k"] = top_k
if isi... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
- 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
The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
Images in a bat... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
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.
top_k (`int`, *optional*, defaults to 5):
The num... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
Return:
A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
the images.
The dictionaries contain the following ke... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
def preprocess(self, image, timeout=None):
image = load_image(image, timeout=timeout)
model_inputs = self.image_processor(images=image, return_tensors=self.framework)
if self.framework == "pt":
model_inputs = model_inputs.to(self.torch_dtype)
return model_inputs
def _for... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
def postprocess(self, model_outputs, function_to_apply=None, top_k=5):
if function_to_apply is None:
if self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels == 1:
function_to_apply = ClassificationFunction.SIGMOID
elif self.model... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
outputs = model_outputs["logits"][0]
if self.framework == "pt" and outputs.dtype in (torch.bfloat16, torch.float16):
outputs = outputs.to(torch.float32).numpy()
else:
outputs = outputs.numpy()
if function_to_apply == ClassificationFunction.SIGMOID:
scores = s... | 421 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_classification.py |
class FillMaskPipeline(Pipeline):
"""
Masked language modeling prediction pipeline using any `ModelWithLMHead`. See the [masked language modeling
examples](../task_summary#masked-language-modeling) for more information.
Example:
```python
>>> from transformers import pipeline
>>> fill_mas... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
This mask filling pipeline can currently be loaded from [`pipeline`] using the following task identifier:
`"fill-mask"`.
The models that this pipeline can use are models that have been trained with a masked language modeling objective,
which includes the bi-directional models in the library. See the up-to-... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
>>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
>>> tokenizer_kwargs = {"truncation": True}
>>> fill_masker(
... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100,
... tokenizer_kwargs=tokenizer_kwargs,
... )
```
</Tip>
... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
def _ensure_exactly_one_mask_token(self, input_ids: GenericTensor) -> np.ndarray:
masked_index = self.get_masked_index(input_ids)
numel = np.prod(masked_index.shape)
if numel < 1:
raise PipelineException(
"fill-mask",
self.model.base_model_prefix,
... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
def preprocess(
self, inputs, return_tensors=None, tokenizer_kwargs=None, **preprocess_parameters
) -> Dict[str, GenericTensor]:
if return_tensors is None:
return_tensors = self.framework
if tokenizer_kwargs is None:
tokenizer_kwargs = {}
model_inputs = self.... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
if self.framework == "tf":
masked_index = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]
outputs = outputs.numpy()
logits = outputs[0, masked_index, :]
probs = stable_softmax(logits, axis=-1)
if target_ids is not None:
prob... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
result = []
single_mask = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist(), predictions.tolist())):
row = []
for v, p in zip(_values, _predictions):
# Copy is important since we're going to modify this array in place
... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
tokens[masked_index[i]] = p
# Filter padding out:
tokens = tokens[np.where(tokens != self.tokenizer.pad_token_id)]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
def get_target_ids(self, targets, top_k=None):
if isinstance(targets, str):
targets = [targets]
try:
vocab = self.tokenizer.get_vocab()
except Exception:
vocab = {}
target_ids = []
for target in targets:
id_ = vocab.get(target, None... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
id_ = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
f"The specified target token `{... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
def _sanitize_parameters(self, top_k=None, targets=None, tokenizer_kwargs=None):
preprocess_params = {}
if tokenizer_kwargs is not None:
preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs
postprocess_params = {}
if targets is not None:
target_ids = self.g... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
Args:
inputs (`str` or `List[str]`):
One or several texts (or one list of prompts) with masked tokens.
targets (`str` or `List[str]`, *optional*):
When passed, the model will limit the scores to the passed targets instead of looking up in the whole
... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
- **sequence** (`str`) -- The corresponding input with the mask token prediction.
- **score** (`float`) -- The corresponding probability.
- **token** (`int`) -- The predicted token id (to replace the masked one).
- **token_str** (`str`) -- The predicted token (to replace the masked o... | 422 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/fill_mask.py |
class ImageToTextPipeline(Pipeline):
"""
Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.
Example:
```python
>>> from transformers import pipeline
>>> captioner = pipeline(model="ydshieh/vit-gpt2-coco-en")
>>> captioner("https://... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
requires_backends(self, "vision")
self.check_model_type(
TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES
)
def _sanitize_parameters(self, ma... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.