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` i... | 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
... | 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:
... | 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 _legac... | 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 isinsta... | 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():
mod... | 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 contain... | 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)
... | 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]
... | 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... | 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 mo... | 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:
... | 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,
... | 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 b... | 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
... | 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*):
... | 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*, default... | 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`, *option... | 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
... | 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 ... | 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 s... | 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_featur... | 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_value... | 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,
)
... | 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... | 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)... | 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, sequenc... | 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 {
... | 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.mode... | 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)
... | 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, "")
seque... | 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
... | 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 ... | 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 oper... | 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(mod... | 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_strategi... | 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 ... | 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 specifi... | 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, **... | 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_le... | 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["i... | 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`... | 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.... | 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... | 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 ... | 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
... | 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`... | 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,
(li... | 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)
... | 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... | 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... | 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) ... | 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_id... | 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:
... | 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... | 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 = ... | 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],
... | 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:
... | 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.mes... | 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
... | 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 i... | 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... | 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",
... "candida... | 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'... | 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):
... | 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`, ... | 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,... | 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 ... | 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)
... | 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_l... | 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[... | 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:
`... | 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 ([`SequenceFeatur... | 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 st... | 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 installe... | 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,
... | 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 [`AutomaticSpeechRecognit... | 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... | 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.
... | 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,
... | 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... | 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
chunk... | 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 pip... | 444 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.