text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
if max_new_tokens is not None:
forward_params["max_new_tokens"] = max_new_tokens
if generate_kwargs is not None:
if max_new_tokens is not None and "max_new_tokens" in generate_kwargs:
raise ValueError(
"`max_new_tokens` is defined both as an argument a... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing a HTTP(s) link pointing to an image
- A string containing a local path to an image
- An image loaded in PIL ... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
Return:
A list or a list of list of `dict`: Each result comes as a dictionary with the following key:
- **generated_text** (`str`) -- The generated text.
"""
# After deprecation of this is completed, remove the default `None` value for `images`
if "images" in kwargs:
... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
if prompt is not None:
logger.warning_once(
"Passing `prompt` to the `image-to-text` pipeline is deprecated and will be removed in version 4.48"
" of 🤗 Transformers. Use the `image-text-to-text` pipeline instead",
)
if not isinstance(prompt, str):
... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
if model_type == "git":
model_inputs = self.image_processor(images=image, return_tensors=self.framework)
if self.framework == "pt":
model_inputs = model_inputs.to(self.torch_dtype)
input_ids = self.tokenizer(text=prompt, add_special_tokens=False).input... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
elif model_type != "vision-encoder-decoder":
# vision-encoder-decoder does not support conditional generation
model_inputs = self.image_processor(images=image, return_tensors=self.framework)
if self.framework == "pt":
model_inputs = model_inputs.to(sel... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
def _forward(self, model_inputs, **generate_kwargs):
# Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the
# pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first.
if (
"input_ids... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
# parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
# the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_... | 423 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_text.py |
class ImageFeatureExtractionPipeline(Pipeline):
"""
Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
transformer, which can be used as features in downstream tasks.
Example:
```python
>>> from transformers import pipeline
>>> ext... | 424 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_feature_extraction.py |
All vision models may be used for this pipeline. See a list of all models, including community-contributed models on
[huggingface.co/models](https://huggingface.co/models).
"""
def _sanitize_parameters(self, image_processor_kwargs=None, return_tensors=None, pool=None, **kwargs):
preprocess_params =... | 424 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_feature_extraction.py |
def preprocess(self, image, timeout=None, **image_processor_kwargs) -> Dict[str, GenericTensor]:
image = load_image(image, timeout=timeout)
model_inputs = self.image_processor(image, return_tensors=self.framework, **image_processor_kwargs)
if self.framework == "pt":
model_inputs = mo... | 424 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_feature_extraction.py |
if pool:
if "pooler_output" not in model_outputs:
raise ValueError(
"No pooled output was returned. Make sure the model has a `pooler` layer when using the `pool` option."
)
outputs = model_outputs["pooler_output"]
else:
# [... | 424 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_feature_extraction.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... | 424 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_feature_extraction.py |
class AudioClassificationPipeline(Pipeline):
"""
Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a
raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio
formats.
Example:
```p... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
See the list of available models on
[huggingface.co/models](https://huggingface.co/models?filter=audio-classification).
"""
def __init__(self, *args, **kwargs):
# Default, might be overriden by the model.config.
kwargs["top_k"] = kwargs.get("top_k", 5)
super().__init__(*args, **kwar... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
Args:
inputs (`np.ndarray` or `bytes` or `str` or `dict`):
The inputs is either :
- `str` that is the filename of the audio file, the file will be read at the correct sampling rate
to get the waveform using *ffmpeg*. This requires *ffmpeg* to be inst... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
"raw": np.array}`, or `{"sampling_rate": int, "array": np.array}`, where the key `"raw"` or
`"array"` is used to denote the raw audio waveform.
top_k (`int`, *optional*, defaults to None):
The number of top labels that will be returned by the pipeline. If the provided n... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
Return:
A list of `dict` with the following keys:
- **label** (`str`) -- The label predicted.
- **score** (`float`) -- The corresponding probability.
"""
return super().__call__(inputs, **kwargs) | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
def _sanitize_parameters(self, top_k=None, function_to_apply=None, **kwargs):
# No parameters on this pipeline right now
postprocess_params = {}
if top_k is not None:
if top_k > self.model.config.num_labels:
top_k = self.model.config.num_labels
postprocess... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
def preprocess(self, inputs):
if isinstance(inputs, str):
if inputs.startswith("http://") or inputs.startswith("https://"):
# We need to actually check for a real protocol, otherwise it's impossible to use a local file
# like http_huggingface_co.png
in... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
if isinstance(inputs, dict):
inputs = inputs.copy() # So we don't mutate the original dictionary outside the pipeline
# Accepting `"array"` which is the key defined in `datasets` for
# better integration
if not ("sampling_rate" in inputs and ("raw" in inputs or "array" i... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
_inputs = inputs.pop("raw", None)
if _inputs is None:
# Remove path which will not be used from `datasets`.
inputs.pop("path", None)
_inputs = inputs.pop("array", None)
in_sampling_rate = inputs.pop("sampling_rate")
inputs = _inputs
... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
if not isinstance(inputs, np.ndarray):
raise TypeError("We expect a numpy ndarray as input")
if len(inputs.shape) != 1:
raise ValueError("We expect a single channel audio input for AudioClassificationPipeline")
processed = self.feature_extractor(
inputs, sampling_rat... | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
labels = [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
return labels | 425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/audio_classification.py |
class VideoClassificationPipeline(Pipeline):
"""
Video classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a
video.
This video classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
`"video-classifi... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
postprocess_params = {}
if top_k is not None:
postprocess_params["top_k"] = top_k
if function_to_apply is not None:
if function_to_apply not in ["softmax", "sigmoid", "none"]:
raise ValueError(
f"Invalid value for `function_to_apply`: {function... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
- A string containing a http link pointing to a video
- A string containing a local path to a video | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
The pipeline accepts either a single video or a batch of videos, which must then be passed as a string.
Videos in a batch must all be in the same format: all as http links or all as local paths.
top_k (`int`, *optional*, defaults to 5):
The number of top labels that will be r... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
frame will be used.
function_to_apply(`str`, *optional*, defaults to "softmax"):
The function to apply to the model output. By default, the pipeline will apply the softmax function to
the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Py... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
Return:
A dictionary or a list of dictionaries containing result. If the input is a single video, will return a
dictionary, if the input is a list of several videos, will return a list of dictionaries corresponding to
the videos.
The dictionaries contain the following ke... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
- **label** (`str`) -- The label identified by the model.
- **score** (`int`) -- The score attributed by the model for that label.
"""
# After deprecation of this is completed, remove the default `None` value for `images`
if "videos" in kwargs:
warnings.warn(
... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
container = av.open(video)
start_idx = 0
end_idx = num_frames * frame_sampling_rate - 1
indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64)
video = read_video_pyav(container, indices)
video = list(video)
model_inputs = self.image_processor(video, ... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
if self.framework == "pt":
if function_to_apply == "softmax":
probs = model_outputs.logits[0].softmax(-1)
elif function_to_apply == "sigmoid":
probs = model_outputs.logits[0].sigmoid()
else:
probs = model_outputs.logits[0]
s... | 426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/video_classification.py |
class ImageToImagePipeline(Pipeline):
"""
Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous
image input.
Example:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import pipeline
>>> ups... | 427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_image.py |
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
requires_backends(self, "vision")
self.check_model_type(MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES)
def _sanitize_parameters(self, **kwargs):
preprocess_params = {}
postprocess_params = {}
forward_par... | 427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_image.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... | 427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_image.py |
Return:
An image (Image.Image) or a list of images (List["Image.Image"]) containing result(s). If the input is a
single image, the return will be also a single image, if the input is a list of several images, it will
return a list of transformed images.
"""
return sup... | 427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_image.py |
def postprocess(self, model_outputs):
images = []
if "reconstruction" in model_outputs.keys():
outputs = model_outputs.reconstruction
for output in outputs:
output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()
output = np.moveaxis(output, source=0... | 427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_to_image.py |
class FeatureExtractionPipeline(Pipeline):
"""
Feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
transformer, which can be used as features in downstream tasks.
Example:
```python
>>> from transformers import pipeline
>>> extractor = pi... | 428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/feature_extraction.py |
All models may be used for this pipeline. See a list of all models, including community-contributed models on
[huggingface.co/models](https://huggingface.co/models).
"""
def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, return_tensors=None, **kwargs):
if tokenize_kwargs is None:... | 428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/feature_extraction.py |
def preprocess(self, inputs, **tokenize_kwargs) -> Dict[str, GenericTensor]:
model_inputs = self.tokenizer(inputs, return_tensors=self.framework, **tokenize_kwargs)
return model_inputs
def _forward(self, model_inputs):
model_outputs = self.model(**model_inputs)
return model_outputs
... | 428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/feature_extraction.py |
Return:
A nested list of `float`: The features computed by the model.
"""
return super().__call__(*args, **kwargs) | 428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/feature_extraction.py |
class DepthEstimationPipeline(Pipeline):
"""
Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
Example:
```python
>>> from transformers import pipeline
>>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth... | 429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/depth_estimation.py |
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
requires_backends(self, "vision")
self.check_model_type(MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
def __call__(self, inputs: Union[str, List[str], "Image.Image", List["Image.Image"]] = None, **kwargs):
"""
... | 429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/depth_estimation.py |
The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
images.
parameters (`Dict`, *optional*):
A dictionary... | 429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/depth_estimation.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... | 429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/depth_estimation.py |
def _sanitize_parameters(self, timeout=None, parameters=None, **kwargs):
preprocess_params = {}
if timeout is not None:
preprocess_params["timeout"] = timeout
if isinstance(parameters, dict) and "timeout" in parameters:
preprocess_params["timeout"] = parameters["timeout"]... | 429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/depth_estimation.py |
def postprocess(self, model_outputs):
outputs = self.image_processor.post_process_depth_estimation(
model_outputs,
# this acts as `source_sizes` for ZoeDepth and as `target_sizes` for the rest of the models so do *not*
# replace with `target_sizes = [model_outputs["target_siz... | 429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/depth_estimation.py |
class ZeroShotAudioClassificationPipeline(Pipeline):
"""
Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
provide an audio and a set of `candidate_labels`.
<Tip warning={true}>
The default `hypothesis_template` is : `"This is a sound ... | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio
classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
`"zero-shot-audio-classification"`. See the list of available models on
[huggingface.co/models](h... | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
Args:
audios (`str`, `List[str]`, `np.array` or `List[np.array]`):
The pipeline handles three types of inputs:
- A string containing a http link pointing to an audio
- A string containing a local path to an audio
- An audio loaded in numpy
... | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
- **label** (`str`) -- One of the suggested *candidate_labels*.
- **score** (`float`) -- The score attributed by the model to that label. It is a value between
0 and 1, computed as the `softmax` of `logits_per_audio`.
"""
return super().__call__(audios, **kwargs) | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
def _sanitize_parameters(self, **kwargs):
preprocess_params = {}
if "candidate_labels" in kwargs:
preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"... | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
if not isinstance(audio, np.ndarray):
raise TypeError("We expect a numpy ndarray as input")
if len(audio.shape) != 1:
raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline")
inputs = self.feature_extractor(
[audio], sampling... | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
def _forward(self, model_inputs):
candidate_labels = model_inputs.pop("candidate_labels")
text_inputs = model_inputs.pop("text_inputs")
if isinstance(text_inputs[0], UserDict):
text_inputs = text_inputs[0]
else:
# Batching case.
text_inputs = text_inpu... | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
result = [
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
]
return result | 430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_audio_classification.py |
class ZeroShotClassificationArgumentHandler(ArgumentHandler):
"""
Handles arguments for zero-shot for text classification by turning each possible label into an NLI
premise/hypothesis pair.
"""
def _parse_labels(self, labels):
if isinstance(labels, str):
labels = [label.strip() ... | 431 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
if isinstance(sequences, str):
sequences = [sequences]
sequence_pairs = []
for sequence in sequences:
sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels])
return sequence_pairs, sequences | 431 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
class ZeroShotClassificationPipeline(ChunkPipeline):
"""
NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural
language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a
hardcoded number of potential c... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
>>> oracle = pipeline(model="facebook/bart-large-mnli")
>>> oracle(
... "I have a problem with my iphone that needs to be resolved asap!!",
... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resol... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list
of available models on [huggingface.co/models](https://huggingface.co/models?search=nli).
"""
def __init__(self, args_parser=ZeroShotClassificationArgumentHandler(), *args, **kwargs):
... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
def _parse_and_tokenize(
self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs
):
"""
Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
"""
return_tensors = self.framework
if s... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
# tokenizers might yell that we want to truncate
# to a value that is not even reached by the input.
# In that case we don't want to truncate.
# It seems there's not a really better way to catch that
# exception. | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
inputs = self.tokenizer(
sequence_pairs,
add_special_tokens=add_special_tokens,
return_tensors=return_tensors,
padding=padding,
truncation=TruncationStrategy.DO_NOT_TRUNCATE,
)
else:
... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
def _sanitize_parameters(self, **kwargs):
if kwargs.get("multi_class", None) is not None:
kwargs["multi_label"] = kwargs["multi_class"]
logger.warning(
"The `multi_class` argument has been deprecated and renamed to `multi_label`. "
"`multi_class` will be r... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
def __call__(
self,
sequences: Union[str, List[str]],
*args,
**kwargs,
):
"""
Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
information. | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
Args:
sequences (`str` or `List[str]`):
The sequence(s) to classify, will be truncated if the model input is too large.
candidate_labels (`str` or `List[str]`):
The set of possible class labels to classify each sequence into. Can be a single label, a string of
... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
works well in many cases, but it may be worthwhile to experiment with different templates depending on
the task setting.
multi_label (`bool`, *optional*, defaults to `False`):
Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such tha... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
Return:
A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
- **sequence** (`str`) -- The sequence for which this is the output.
- **labels** (`List[str]`) -- The labels sorted by order of likelihood.
- **scores** (`List[float]`) -- T... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
for i, (candidate_label, sequence_pair) in enumerate(zip(candidate_labels, sequence_pairs)):
model_input = self._parse_and_tokenize([sequence_pair])
yield {
"candidate_label": candidate_label,
"sequence": sequences[0],
"is_last": i == len(candidat... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
model_outputs = {
"candidate_label": candidate_label,
"sequence": sequence,
"is_last": inputs["is_last"],
**outputs,
}
return model_outputs
def postprocess(self, model_outputs, multi_label=False):
candidate_labels = [outputs["candidate_label"]... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
if multi_label or len(candidate_labels) == 1:
# softmax over the entailment vs. contradiction dim for each label independently
entailment_id = self.entailment_id
contradiction_id = -1 if entailment_id == 0 else 0
entail_contr_logits = reshaped_outputs[..., [contradiction_... | 432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_classification.py |
class ReturnType(enum.Enum):
TENSORS = 0
NEW_TEXT = 1
FULL_TEXT = 2 | 433 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.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 ... | 434 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
class ImageTextToTextPipeline(Pipeline):
"""
Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text.
When the underlying model is a conversational model, it can also accept one or more chats,
in which case the pipeline will operate in cha... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
>>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
>>> messages = [
>>> {
>>> "role": "user",
>>> "content": [
>>> {
>>> "type": "image",
>>> "url": "https://qianwen-res.oss-cn-beijing.aliy... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
``` | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier:
"image-text-to-text".
See the list of available models on
[huggingface.co/models](https://huggi... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
def _sanitize_parameters(
self,
max_new_tokens=None,
generate_kwargs=None,
timeout=None,
return_full_text=None,
return_tensors=None,
return_type=None,
continue_final_message=None,
**kwargs: Unpack[ProcessingKwargs],
):
forward_kwargs = ... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
if max_new_tokens is not None:
if "generate_kwargs" not in forward_kwargs:
forward_kwargs["generate_kwargs"] = {}
if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
raise ValueError(
"'max_new_tokens' is defined twice, once in 'generate_... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
if return_full_text is not None and return_type is None:
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 ... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
def __call__(
self,
images: Optional[
Union[str, List[str], List[List[str]], "Image.Image", List["Image.Image"], List[List["Image.Image"]]]
] = None,
text: Optional[Union[str, List[str], List[dict]]] = None,
**kwargs,
):
"""
Generate a text given t... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
The pipeline accepts either a single image or a batch of images.
text (str, List[str], `List[Dict[str, Union[str, PIL.Image]]]`):
The text to be used for generation. If a list of strings is passed, the length of the list should be the
same as the number of images. Text can al... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
`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`):
If set to `False` only added text is returned, otherwise the full text is returned. Can... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
Return:
A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot return a combination
of both `generated_text` and `generated_token_ids`): | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
- **generated_text** (`str`, present when `return_text=True`) -- The generated text.
- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
ids of the generated text.
- **input_text** (`str`) -- The input text.
"""
if images is... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
if isinstance(text, (list, tuple, KeyDataset)) and isinstance(text[0], (list, tuple, dict)):
# We have one or more prompts in list-of-dicts format, so this is chat mode
if isinstance(text[0], dict):
return super().__call__(Chat(text, images), **kwargs)
else:
... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
# encourage the user to use the chat format if supported
if getattr(self.processor, "chat_template", None) is not None:
logger.warning_once(
"The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even though this model supports chat. "
... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
def preprocess(self, inputs=None, timeout=None, continue_final_message=None, processing_kwargs=None):
# In case we only have text inputs
if isinstance(inputs, (list, tuple, str)):
images = None
text = inputs
inputs_text = inputs
else:
if isinstance... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
inputs_text = inputs
images = inputs.images
else:
text = inputs["text"]
inputs_text = inputs["text"]
images = inputs["images"] | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
images = load_images(images)
# if batched text inputs, we set padding to True unless specified otherwise
if isinstance(text, (list, tuple)) and len(text) > 1:
processing_kwargs.setdefault("padding", True)
model_inputs = self.processor(
images=images, text=text, return_te... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids}
def postprocess(self, model_outputs, return_type=ReturnType.FULL_TEXT, continue_final_message=None):
input_texts = model_outputs["prompt_text"]
input_texts = [input_texts] if isinstance(input_texts... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
# Force consistent behavior for including the input text in the output
if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
# Remove the input text from the generated text if the generated text starts with the input text
# (accounting for the possibility of a space between the ... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :])
else:
new_generated_texts.append(text_generated)
generated_texts = new_generated_texts
if return_type == ReturnType.FULL_TEXT:
full_texts = []
for prompt_te... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
# With assistant prefill, concat onto the end of the last message
new_text = dict(prompt_text.messages[-1]["content"][-1].items())
new_text["text"] += generated_text
generated_text = list(prompt_text.messages)[:-1] + [
{... | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
records = [
{
"input_text": input_text.messages if isinstance(input_text, Chat) else input_text,
"generated_text": generated_text,
}
for input_text, generated_text in zip(input_texts, generated_texts)
]
return records | 435 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/image_text_to_text.py |
class ClassificationFunction(ExplicitEnum):
SIGMOID = "sigmoid"
SOFTMAX = "softmax"
NONE = "none" | 436 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py |
class TextClassificationPipeline(Pipeline):
"""
Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification
examples](../task_summary#sequence-classification) for more information.
Example:
```python
>>> from transformers import pipeline
>>> c... | 437 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py |
If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax
over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression
tasks (`model.config.problem_type == "regression"`), will not apply any function ... | 437 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py |
def _sanitize_parameters(self, return_all_scores=None, function_to_apply=None, top_k="", **tokenizer_kwargs):
# Using "" as default argument because we're going to use `top_k=None` in user code to declare
# "No top_k"
preprocess_params = tokenizer_kwargs
postprocess_params = {}
... | 437 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/text_classification.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.