text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
preprocess_params["stride_length_s"] = stride_length_s
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
forward_params = defaultdict(dict) if max_new_tokens is not None: warnings.warn( "`max_new_tokens` is deprecated and will be removed in version 4.49 of Transformers. To remove this warning, pass `max_new_tokens` as a key inside `generate_kwargs` instead.", FutureWarning, ) 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 and inside `generate_kwargs` argument, please use" " only 1 version" ) forward_params.update(generate_kwargs)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
postprocess_params = {} if decoder_kwargs is not None: postprocess_params["decoder_kwargs"] = decoder_kwargs if return_timestamps is not None: # Check whether we have a valid setting for return_timestamps and throw an error before we perform a forward pass if self.type == "seq2seq" and return_timestamps: raise ValueError("We cannot return_timestamps yet on non-CTC models apart from Whisper!") if self.type == "ctc_with_lm" and return_timestamps != "word": raise ValueError("CTC with LM can only predict word level timestamps, set `return_timestamps='word'`") if self.type == "ctc" and return_timestamps not in ["char", "word"]: raise ValueError( "CTC can either predict character level timestamps, or word level timestamps. " "Set `return_timestamps='char'` or `return_timestamps='word'` as required." )
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if self.type == "seq2seq_whisper" and return_timestamps == "char": raise ValueError( "Whisper cannot return `char` timestamps, only word level or segment level timestamps. " "Use `return_timestamps='word'` or `return_timestamps=True` respectively." ) forward_params["return_timestamps"] = return_timestamps postprocess_params["return_timestamps"] = return_timestamps if return_language is not None: if self.type != "seq2seq_whisper": raise ValueError("Only Whisper can return language for now.") postprocess_params["return_language"] = return_language
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if self.assistant_model is not None: forward_params["assistant_model"] = self.assistant_model if self.assistant_tokenizer is not None: forward_params["tokenizer"] = self.tokenizer forward_params["assistant_tokenizer"] = self.assistant_tokenizer return preprocess_params, forward_params, postprocess_params def preprocess(self, inputs, chunk_length_s=0, stride_length_s=None): 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 inputs = requests.get(inputs).content else: with open(inputs, "rb") as f: inputs = f.read() if isinstance(inputs, bytes): inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
stride = None extra = {} if isinstance(inputs, dict): stride = inputs.pop("stride", None) # Accepting `"array"` which is the key defined in `datasets` for # better integration if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)): raise ValueError( "When passing a dictionary to AutomaticSpeechRecognitionPipeline, the dict needs to contain a " '"raw" key containing the numpy array representing the audio and a "sampling_rate" key, ' "containing the sampling_rate associated with that array" )
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.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") extra = inputs inputs = _inputs if in_sampling_rate != self.feature_extractor.sampling_rate: if is_torchaudio_available(): from torchaudio import functional as F else: raise ImportError( "torchaudio is required to resample audio samples in AutomaticSpeechRecognitionPipeline. " "The torchaudio package can be installed through: `pip install torchaudio`." )
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
inputs = F.resample( torch.from_numpy(inputs), in_sampling_rate, self.feature_extractor.sampling_rate ).numpy() ratio = self.feature_extractor.sampling_rate / in_sampling_rate else: ratio = 1 if stride is not None: if stride[0] + stride[1] > inputs.shape[0]: raise ValueError("Stride is too large for input")
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
# Stride needs to get the chunk length here, it's going to get # swallowed by the `feature_extractor` later, and then batching # can add extra data in the inputs, so we need to keep track # of the original length in the stride so we can cut properly. stride = (inputs.shape[0], int(round(stride[0] * ratio)), int(round(stride[1] * ratio))) if not isinstance(inputs, np.ndarray): raise TypeError(f"We expect a numpy ndarray as input, got `{type(inputs)}`") if len(inputs.shape) != 1: raise ValueError("We expect a single channel audio input for AutomaticSpeechRecognitionPipeline") if chunk_length_s: if stride_length_s is None: stride_length_s = chunk_length_s / 6 if isinstance(stride_length_s, (int, float)): stride_length_s = [stride_length_s, stride_length_s]
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
# XXX: Carefuly, this variable will not exist in `seq2seq` setting. # Currently chunking is not possible at this level for `seq2seq` so # it's ok. align_to = getattr(self.model.config, "inputs_to_logits_ratio", 1) chunk_len = int(round(chunk_length_s * self.feature_extractor.sampling_rate / align_to) * align_to) stride_left = int(round(stride_length_s[0] * self.feature_extractor.sampling_rate / align_to) * align_to) stride_right = int(round(stride_length_s[1] * self.feature_extractor.sampling_rate / align_to) * align_to) if chunk_len < stride_left + stride_right: raise ValueError("Chunk length must be superior to stride length")
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
for item in chunk_iter( inputs, self.feature_extractor, chunk_len, stride_left, stride_right, self.torch_dtype ): yield {**item, **extra} else: if self.type == "seq2seq_whisper" and inputs.shape[0] > self.feature_extractor.n_samples: processed = self.feature_extractor( inputs, sampling_rate=self.feature_extractor.sampling_rate, truncation=False, padding="longest", return_tensors="pt", return_attention_mask=True, ) else: if self.type == "seq2seq_whisper" and stride is None: processed = self.feature_extractor( inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt", return_token_timestamps=True,
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
return_attention_mask=True, ) extra["num_frames"] = processed.pop("num_frames") else: processed = self.feature_extractor( inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt", return_attention_mask=True, ) if self.torch_dtype is not None: processed = processed.to(dtype=self.torch_dtype) if stride is not None: if self.type == "seq2seq": raise ValueError("Stride is only usable with CTC models, try removing it !")
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
processed["stride"] = stride yield {"is_last": True, **processed, **extra} def _forward(self, model_inputs, return_timestamps=False, **generate_kwargs): attention_mask = model_inputs.pop("attention_mask", None) stride = model_inputs.pop("stride", None) num_frames = model_inputs.pop("num_frames", None) is_last = model_inputs.pop("is_last") if stride is not None and num_frames is not None: raise ValueError("num_frames must be used only when stride is None")
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if self.type in {"seq2seq", "seq2seq_whisper"}: # Consume values so we can let extra information flow freely through # the pipeline (important for `partial` in microphone) if "input_features" in model_inputs: inputs = model_inputs.pop("input_features") elif "input_values" in model_inputs: inputs = model_inputs.pop("input_values") else: raise ValueError( "Seq2Seq speech recognition model requires either a " f"`input_features` or `input_values` key, but only has {model_inputs.keys()}" )
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
# custom processing for Whisper timestamps and word-level timestamps if return_timestamps and self.type == "seq2seq_whisper": generate_kwargs["return_timestamps"] = return_timestamps if return_timestamps == "word": generate_kwargs["return_token_timestamps"] = True generate_kwargs["return_segments"] = True if stride is not None: if isinstance(stride, tuple): generate_kwargs["num_frames"] = stride[0] // self.feature_extractor.hop_length else: generate_kwargs["num_frames"] = [s[0] // self.feature_extractor.hop_length for s in stride] else: generate_kwargs["num_frames"] = num_frames
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.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
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
tokens = self.model.generate( inputs=inputs, attention_mask=attention_mask, **generate_kwargs, ) # whisper longform generation stores timestamps in "segments" if return_timestamps == "word" and self.type == "seq2seq_whisper": if "segments" not in tokens: out = {"tokens": tokens["sequences"], "token_timestamps": tokens["token_timestamps"]} else: token_timestamps = [ torch.cat([segment["token_timestamps"] for segment in segment_list]) for segment_list in tokens["segments"] ] out = {"tokens": tokens["sequences"], "token_timestamps": token_timestamps} else: out = {"tokens": tokens} if self.type == "seq2seq_whisper": if stride is not None: out["stride"] = stride
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
else: inputs = { self.model.main_input_name: model_inputs.pop(self.model.main_input_name), "attention_mask": attention_mask, } outputs = self.model(**inputs) logits = outputs.logits if self.type == "ctc_with_lm": out = {"logits": logits} else: out = {"tokens": logits.argmax(dim=-1)} if stride is not None: # Send stride to `postprocess`. # it needs to be handled there where # the pieces are to be concatenated. ratio = 1 / self.model.config.inputs_to_logits_ratio if isinstance(stride, tuple): out["stride"] = rescale_stride([stride], ratio)[0] else: out["stride"] = rescale_stride(stride, ratio) # Leftover extra = model_inputs return {"is_last": is_last, **out, **extra}
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
def postprocess( self, model_outputs, decoder_kwargs: Optional[Dict] = None, return_timestamps=None, return_language=None ): # Optional return types optional = {}
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
final_items = [] key = "logits" if self.type == "ctc_with_lm" else "tokens" stride = None for outputs in model_outputs: if self.framework == "pt" and outputs[key].dtype in (torch.bfloat16, torch.float16): items = outputs[key].to(torch.float32).numpy() else: items = outputs[key].numpy() stride = outputs.get("stride", None) if stride is not None and self.type in {"ctc", "ctc_with_lm"}: total_n, left, right = stride # Total_n might be < logits.shape[1] # because of padding, that's why # we need to reconstruct this information # This won't work with left padding (which doesn't exist right now) right_n = total_n - right items = items[:, left:right_n] final_items.append(items)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if stride and self.type == "seq2seq": items = _find_longest_common_sequence(final_items, self.tokenizer) elif self.type == "seq2seq_whisper": time_precision = self.feature_extractor.chunk_length / self.model.config.max_source_positions # Send the chunking back to seconds, it's easier to handle in whisper sampling_rate = self.feature_extractor.sampling_rate for output in model_outputs: if "stride" in output: chunk_len, stride_left, stride_right = output["stride"] # Go back in seconds chunk_len /= sampling_rate stride_left /= sampling_rate stride_right /= sampling_rate output["stride"] = chunk_len, stride_left, stride_right
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
text, optional = self.tokenizer._decode_asr( model_outputs, return_timestamps=return_timestamps, return_language=return_language, time_precision=time_precision, ) else: items = np.concatenate(final_items, axis=1) items = items.squeeze(0)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if self.type == "ctc_with_lm": if decoder_kwargs is None: decoder_kwargs = {} beams = self.decoder.decode_beams(items, **decoder_kwargs) text = beams[0][0] if return_timestamps: # Simply cast from pyctcdecode format to wav2vec2 format to leverage # pre-existing code later chunk_offset = beams[0][2] offsets = [] for word, (start_offset, end_offset) in chunk_offset: offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset}) elif self.type != "seq2seq_whisper": skip_special_tokens = self.type != "ctc" text = self.tokenizer.decode(items, skip_special_tokens=skip_special_tokens) if return_timestamps: offsets = self.tokenizer.decode( items, skip_special_tokens=skip_special_tokens, output_char_offsets=True )["char_offsets"]
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if return_timestamps == "word": offsets = self.tokenizer._get_word_offsets(offsets, self.tokenizer.replace_word_delimiter_char)
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
if return_timestamps and self.type not in {"seq2seq", "seq2seq_whisper"}: chunks = [] for item in offsets: start = item["start_offset"] * self.model.config.inputs_to_logits_ratio start /= self.feature_extractor.sampling_rate stop = item["end_offset"] * self.model.config.inputs_to_logits_ratio stop /= self.feature_extractor.sampling_rate chunks.append({"text": item[return_timestamps], "timestamp": (start, stop)}) optional["chunks"] = chunks extra = defaultdict(list) for output in model_outputs: output.pop("tokens", None) output.pop("logits", None) output.pop("is_last", None) output.pop("stride", None) output.pop("token_timestamps", None) for k, v in output.items(): extra[k].append(v) return {"text": text, **optional, **extra}
444
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/automatic_speech_recognition.py
class MaskGenerationPipeline(ChunkPipeline): """ Automatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an image, given an image. It is a `ChunkPipeline` because you can seperate the points in a mini-batch in order to avoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the same time. Default is `64`. The pipeline works in 3 steps: 1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point labels. For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes` function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of `points_per_batch`.
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once. Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the tensors and models are on the same device. 3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps are induced: - image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks, resizes them according to the image size, and transforms there to binary masks. - image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and `stability_scores`. Also applies a variety of filters based on non maximum suppression to remove bad masks. - image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
Example: ```python >>> from transformers import pipeline >>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation") >>> outputs = generator( ... "http://images.cocodataset.org/val2017/000000039769.jpg", ... ) >>> outputs = generator( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128 ... ) ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"mask-generation"`. See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation). """ def __init__(self, **kwargs): super().__init__(**kwargs) requires_backends(self, "vision") requires_backends(self, "torch")
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
if self.framework != "pt": raise ValueError(f"The {self.__class__} is only available in PyTorch.") self.check_model_type(MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
def _sanitize_parameters(self, **kwargs): preprocess_kwargs = {} postprocess_kwargs = {} forward_params = {} # preprocess args if "points_per_batch" in kwargs: preprocess_kwargs["points_per_batch"] = kwargs["points_per_batch"] if "points_per_crop" in kwargs: preprocess_kwargs["points_per_crop"] = kwargs["points_per_crop"] if "crops_n_layers" in kwargs: preprocess_kwargs["crops_n_layers"] = kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: preprocess_kwargs["crop_overlap_ratio"] = kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: preprocess_kwargs["crop_n_points_downscale_factor"] = kwargs["crop_n_points_downscale_factor"] if "timeout" in kwargs: preprocess_kwargs["timeout"] = kwargs["timeout"] # postprocess args if "pred_iou_thresh" in kwargs:
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
forward_params["pred_iou_thresh"] = kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: forward_params["stability_score_offset"] = kwargs["stability_score_offset"] if "mask_threshold" in kwargs: forward_params["mask_threshold"] = kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: forward_params["stability_score_thresh"] = kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: postprocess_kwargs["crops_nms_thresh"] = kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: postprocess_kwargs["output_rle_mask"] = kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: postprocess_kwargs["output_bboxes_mask"] = kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
def __call__(self, image, *args, num_workers=None, batch_size=None, **kwargs): """ Generates binary segmentation masks
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
Args: inputs (`np.ndarray` or `bytes` or `str` or `dict`): Image or list of images. mask_threshold (`float`, *optional*, defaults to 0.0): Threshold to use when turning the predicted masks into binary values. pred_iou_thresh (`float`, *optional*, defaults to 0.88): A filtering threshold in `[0,1]` applied on the model's predicted mask quality. stability_score_thresh (`float`, *optional*, defaults to 0.95): A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (`int`, *optional*, defaults to 1): The amount to shift the cutoff when calculated the stability score. crops_nms_thresh (`float`, *optional*, defaults to 0.7): The box IoU cutoff used by non-maximal suppression to filter duplicate masks.
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
crops_n_layers (`int`, *optional*, defaults to 0): If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crop_overlap_ratio (`float`, *optional*, defaults to `512 / 1500`): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (`int`, *optional*, defaults to `1`): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. 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.
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
Return: `Dict`: A dictionary with the following keys: - **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`) -- Optionally, when the model is capable of estimating a confidence of the "object" described by the label and the mask. """ return super().__call__(image, *args, num_workers=num_workers, batch_size=batch_size, **kwargs)
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
def preprocess( self, image, points_per_batch=64, crops_n_layers: int = 0, crop_overlap_ratio: float = 512 / 1500, points_per_crop: Optional[int] = 32, crop_n_points_downscale_factor: Optional[int] = 1, timeout: Optional[float] = None, ): image = load_image(image, timeout=timeout) target_size = self.image_processor.size["longest_edge"] crop_boxes, grid_points, cropped_images, input_labels = self.image_processor.generate_crop_boxes( image, target_size, crops_n_layers, crop_overlap_ratio, points_per_crop, crop_n_points_downscale_factor ) model_inputs = self.image_processor(images=cropped_images, return_tensors="pt") if self.framework == "pt": model_inputs = model_inputs.to(self.torch_dtype)
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
with self.device_placement(): if self.framework == "pt": inference_context = self.get_inference_context() with inference_context(): model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device) image_embeddings = self.model.get_image_embeddings(model_inputs.pop("pixel_values")) model_inputs["image_embeddings"] = image_embeddings n_points = grid_points.shape[1] points_per_batch = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None" )
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
for i in range(0, n_points, points_per_batch): batched_points = grid_points[:, i : i + points_per_batch, :, :] labels = input_labels[:, i : i + points_per_batch] is_last = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _forward( self, model_inputs, pred_iou_thresh=0.88, stability_score_thresh=0.95, mask_threshold=0, stability_score_offset=1, ): input_boxes = model_inputs.pop("input_boxes") is_last = model_inputs.pop("is_last") original_sizes = model_inputs.pop("original_sizes").tolist() reshaped_input_sizes = model_inputs.pop("reshaped_input_sizes").tolist() model_outputs = self.model(**model_inputs)
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
# post processing happens here in order to avoid CPU GPU copies of ALL the masks low_resolution_masks = model_outputs["pred_masks"] masks = self.image_processor.post_process_masks( low_resolution_masks, original_sizes, reshaped_input_sizes, mask_threshold, binarize=False ) iou_scores = model_outputs["iou_scores"] masks, iou_scores, boxes = self.image_processor.filter_masks( masks[0], iou_scores[0], original_sizes[0], input_boxes[0], pred_iou_thresh, stability_score_thresh, mask_threshold, stability_score_offset, ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, }
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
def postprocess( self, model_outputs, output_rle_mask=False, output_bboxes_mask=False, crops_nms_thresh=0.7, ): all_scores = [] all_masks = [] all_boxes = [] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) all_scores = torch.cat(all_scores) all_boxes = torch.cat(all_boxes) output_masks, iou_scores, rle_mask, bounding_boxes = self.image_processor.post_process_for_mask_generation( all_masks, all_scores, all_boxes, crops_nms_thresh ) extra = defaultdict(list) for output in model_outputs: for k, v in output.items(): extra[k].append(v) optional = {} if output_rle_mask: optional["rle_mask"] = rle_mask
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
if output_bboxes_mask: optional["bounding_boxes"] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
445
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/mask_generation.py
class ZeroShotImageClassificationPipeline(Pipeline): """ Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you provide an image and a set of `candidate_labels`. Example: ```python >>> from transformers import pipeline >>> classifier = pipeline(model="google/siglip-so400m-patch14-384") >>> classifier( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", ... candidate_labels=["animals", "humans", "landscape"], ... ) [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}] >>> classifier( ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", ... candidate_labels=["black and white", "photorealist", "painting"], ... ) [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}] ```
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.py
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"zero-shot-image-classification"`. See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification). """ def __init__(self, **kwargs): super().__init__(**kwargs) requires_backends(self, "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES ) def __call__(self, image: Union[str, List[str], "Image", List["Image"]] = None, **kwargs): """ Assign labels to the image(s) passed as inputs.
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.py
Args: image (`str`, `List[str]`, `PIL.Image` or `List[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 candidate_labels (`List[str]`): The candidate labels for this image. They will be formatted using *hypothesis_template*. hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`): The format used in conjunction with *candidate_labels* to attempt the image classification by replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are already formatted.
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.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. Return: A list of dictionaries containing one entry per proposed label. Each dictionary contains the following keys: - **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_image`. """ # After deprecation of this is completed, remove the default `None` value for `image` if "images" in kwargs: image = kwargs.pop("images") if image is None: raise ValueError("Cannot call the zero-shot-image-classification pipeline without an images argument!") return super().__call__(image, **kwargs)
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.py
def _sanitize_parameters(self, tokenizer_kwargs=None, **kwargs): preprocess_params = {} if "candidate_labels" in kwargs: preprocess_params["candidate_labels"] = kwargs["candidate_labels"] if "timeout" in kwargs: preprocess_params["timeout"] = kwargs["timeout"] if "hypothesis_template" in kwargs: preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"] if tokenizer_kwargs is not None: warnings.warn( "The `tokenizer_kwargs` argument is deprecated and will be removed in version 5 of Transformers", FutureWarning, ) preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs return preprocess_params, {}, {}
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.py
def preprocess( self, image, candidate_labels=None, hypothesis_template="This is a photo of {}.", timeout=None, tokenizer_kwargs=None, ): if tokenizer_kwargs is None: tokenizer_kwargs = {} image = load_image(image, timeout=timeout) inputs = self.image_processor(images=[image], return_tensors=self.framework) if self.framework == "pt": inputs = inputs.to(self.torch_dtype) inputs["candidate_labels"] = candidate_labels sequences = [hypothesis_template.format(x) for x in candidate_labels] padding = "max_length" if self.model.config.model_type == "siglip" else True text_inputs = self.tokenizer(sequences, return_tensors=self.framework, padding=padding, **tokenizer_kwargs) inputs["text_inputs"] = [text_inputs] return inputs
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_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_inputs[0][0] outputs = self.model(**text_inputs, **model_inputs) model_outputs = { "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.py
def postprocess(self, model_outputs): candidate_labels = model_outputs.pop("candidate_labels") logits = model_outputs["logits"][0] if self.framework == "pt" and self.model.config.model_type == "siglip": probs = torch.sigmoid(logits).squeeze(-1) scores = probs.tolist() if not isinstance(scores, list): scores = [scores] elif self.framework == "pt": probs = logits.softmax(dim=-1).squeeze(-1) scores = probs.tolist() if not isinstance(scores, list): scores = [scores] elif self.framework == "tf": probs = stable_softmax(logits, axis=-1) scores = probs.numpy().tolist() else: raise ValueError(f"Unsupported framework: {self.framework}")
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_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
446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/zero_shot_image_classification.py
class ObjectDetectionPipeline(Pipeline): """ Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects and their classes. Example: ```python >>> from transformers import pipeline >>> detector = pipeline(model="facebook/detr-resnet-50") >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png") [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}] >>> # x, y are expressed relative to the top left hand corner. ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"object-detection"`.
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection). """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.framework == "tf": raise ValueError(f"The {self.__class__} is only available in PyTorch.") requires_backends(self, "vision") mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES.copy() mapping.update(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES) self.check_model_type(mapping) def _sanitize_parameters(self, **kwargs): preprocess_params = {} if "timeout" in kwargs: preprocess_params["timeout"] = kwargs["timeout"] postprocess_kwargs = {} if "threshold" in kwargs: postprocess_kwargs["threshold"] = kwargs["threshold"] return preprocess_params, {}, postprocess_kwargs
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
def __call__(self, *args, **kwargs) -> Union[Predictions, List[Prediction]]: """ Detect objects (bounding boxes & classes) in the image(s) passed as inputs. 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 directly
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.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. threshold (`float`, *optional*, defaults to 0.5): The probability necessary to make a prediction. timeout (`float`, *optional*, defaults to None): The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever. Return: A list of dictionaries or a list of 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 contain the following keys:
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
- **label** (`str`) -- The class label identified by the model. - **score** (`float`) -- The score attributed by the model for that label. - **box** (`List[Dict[str, int]]`) -- The bounding box of detected object in image's original size. """ # After deprecation of this is completed, remove the default `None` value for `images` if "images" in kwargs and "inputs" not in kwargs: kwargs["inputs"] = kwargs.pop("images") return super().__call__(*args, **kwargs)
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
def preprocess(self, image, timeout=None): image = load_image(image, timeout=timeout) target_size = torch.IntTensor([[image.height, image.width]]) inputs = self.image_processor(images=[image], return_tensors="pt") if self.framework == "pt": inputs = inputs.to(self.torch_dtype) if self.tokenizer is not None: inputs = self.tokenizer(text=inputs["words"], boxes=inputs["boxes"], return_tensors="pt") inputs["target_size"] = target_size return inputs def _forward(self, model_inputs): target_size = model_inputs.pop("target_size") outputs = self.model(**model_inputs) model_outputs = outputs.__class__({"target_size": target_size, **outputs}) if self.tokenizer is not None: model_outputs["bbox"] = model_inputs["bbox"] return model_outputs
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
def postprocess(self, model_outputs, threshold=0.5): target_size = model_outputs["target_size"] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. height, width = target_size[0].tolist() def unnormalize(bbox): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) )
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
scores, classes = model_outputs["logits"].squeeze(0).softmax(dim=-1).max(dim=-1) labels = [self.model.config.id2label[prediction] for prediction in classes.tolist()] boxes = [unnormalize(bbox) for bbox in model_outputs["bbox"].squeeze(0)] keys = ["score", "label", "box"] annotation = [dict(zip(keys, vals)) for vals in zip(scores.tolist(), labels, boxes) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel raw_annotations = self.image_processor.post_process_object_detection(model_outputs, threshold, target_size) raw_annotation = raw_annotations[0] scores = raw_annotation["scores"] labels = raw_annotation["labels"] boxes = raw_annotation["boxes"]
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
raw_annotation["scores"] = scores.tolist() raw_annotation["labels"] = [self.model.config.id2label[label.item()] for label in labels] raw_annotation["boxes"] = [self._get_bounding_box(box) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] keys = ["score", "label", "box"] annotation = [ dict(zip(keys, vals)) for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"]) ] return annotation 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.
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
Returns: bbox (`Dict[str, int]`): Dict containing the coordinates in corners format. """ if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch.") xmin, ymin, xmax, ymax = box.int().tolist() bbox = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/object_detection.py
class TableQuestionAnsweringArgumentHandler(ArgumentHandler): """ Handles arguments for the TableQuestionAnsweringPipeline """ def __call__(self, table=None, query=None, **kwargs): # Returns tqa_pipeline_inputs of shape: # [ # {"table": pd.DataFrame, "query": List[str]}, # ..., # {"table": pd.DataFrame, "query" : List[str]} # ] requires_backends(self, "pandas") import pandas as pd
448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
if table is None: raise ValueError("Keyword argument `table` cannot be None.") elif query is None: if isinstance(table, dict) and table.get("query") is not None and table.get("table") is not None: tqa_pipeline_inputs = [table] elif isinstance(table, list) and len(table) > 0: if not all(isinstance(d, dict) for d in table): raise ValueError( f"Keyword argument `table` should be a list of dict, but is {(type(d) for d in table)}" )
448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
if table[0].get("query") is not None and table[0].get("table") is not None: tqa_pipeline_inputs = table else: raise ValueError( "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`" f" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys." ) elif Dataset is not None and isinstance(table, Dataset) or isinstance(table, types.GeneratorType): return table else: raise ValueError( "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but " f"is {type(table)})" ) else: tqa_pipeline_inputs = [{"table": table, "query": query}]
448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
for tqa_pipeline_input in tqa_pipeline_inputs: if not isinstance(tqa_pipeline_input["table"], pd.DataFrame): if tqa_pipeline_input["table"] is None: raise ValueError("Table cannot be None.") tqa_pipeline_input["table"] = pd.DataFrame(tqa_pipeline_input["table"]) return tqa_pipeline_inputs
448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
class TableQuestionAnsweringPipeline(Pipeline): """ Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in PyTorch. Example: ```python >>> from transformers import pipeline >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq") >>> table = { ... "Repository": ["Transformers", "Datasets", "Tokenizers"], ... "Stars": ["36542", "4512", "3934"], ... "Contributors": ["651", "77", "34"], ... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], ... } >>> oracle(query="How many stars does the transformers repository have?", table=table) {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'} ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"table-question-answering"`. The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task. See the up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering). """ default_input_names = "table,query" def __init__(self, args_parser=TableQuestionAnsweringArgumentHandler(), *args, **kwargs): super().__init__(*args, **kwargs) self._args_parser = args_parser
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
if self.framework == "tf": mapping = TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy() mapping.update(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES) else: mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy() mapping.update(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES) self.check_model_type(mapping) self.aggregate = bool(getattr(self.model.config, "aggregation_labels", None)) and bool( getattr(self.model.config, "num_aggregation_labels", None) ) self.type = "tapas" if hasattr(self.model.config, "aggregation_labels") else None def batch_inference(self, **inputs): return self.model(**inputs)
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
def sequential_inference(self, **inputs): """ Inference used for models that need to process sequences in a sequential fashion, like the SQA models which handle conversational query related to a table. """ if self.framework == "pt": all_logits = [] all_aggregations = [] prev_answers = None batch_size = inputs["input_ids"].shape[0] input_ids = inputs["input_ids"].to(self.device) attention_mask = inputs["attention_mask"].to(self.device) token_type_ids = inputs["token_type_ids"].to(self.device) token_type_ids_example = None
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
for index in range(batch_size): # If sequences have already been processed, the token type IDs will be created according to the previous # answer. if prev_answers is not None: prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,) model_labels = np.zeros_like(prev_labels_example.cpu().numpy()) # shape (seq_len,) token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) for i in range(model_labels.shape[0]): segment_id = token_type_ids_example[:, 0].tolist()[i] col_id = token_type_ids_example[:, 1].tolist()[i] - 1 row_id = token_type_ids_example[:, 2].tolist()[i] - 1 if row_id >= 0 and col_id >= 0 and segment_id == 1: model_labels[i] = int(prev_answers[(col_id, row_id)])
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
token_type_ids_example[:, 3] = torch.from_numpy(model_labels).type(torch.long).to(self.device) input_ids_example = input_ids[index] attention_mask_example = attention_mask[index] # shape (seq_len,) token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) outputs = self.model( input_ids=input_ids_example.unsqueeze(0), attention_mask=attention_mask_example.unsqueeze(0), token_type_ids=token_type_ids_example.unsqueeze(0), ) logits = outputs.logits if self.aggregate: all_aggregations.append(outputs.logits_aggregation) all_logits.append(logits)
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
dist_per_token = torch.distributions.Bernoulli(logits=logits) probabilities = dist_per_token.probs * attention_mask_example.type(torch.float32).to( dist_per_token.probs.device ) coords_to_probs = collections.defaultdict(list) for i, p in enumerate(probabilities.squeeze().tolist()): segment_id = token_type_ids_example[:, 0].tolist()[i] col = token_type_ids_example[:, 1].tolist()[i] - 1 row = token_type_ids_example[:, 2].tolist()[i] - 1 if col >= 0 and row >= 0 and segment_id == 1: coords_to_probs[(col, row)].append(p) prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs} logits_batch = torch.cat(tuple(all_logits), 0)
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(all_aggregations), 0)) else: all_logits = [] all_aggregations = [] prev_answers = None batch_size = inputs["input_ids"].shape[0] input_ids = inputs["input_ids"] attention_mask = inputs["attention_mask"] token_type_ids = inputs["token_type_ids"].numpy() token_type_ids_example = None for index in range(batch_size): # If sequences have already been processed, the token type IDs will be created according to the previous # answer. if prev_answers is not None: prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,) model_labels = np.zeros_like(prev_labels_example, dtype=np.int32) # shape (seq_len,)
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) for i in range(model_labels.shape[0]): segment_id = token_type_ids_example[:, 0].tolist()[i] col_id = token_type_ids_example[:, 1].tolist()[i] - 1 row_id = token_type_ids_example[:, 2].tolist()[i] - 1 if row_id >= 0 and col_id >= 0 and segment_id == 1: model_labels[i] = int(prev_answers[(col_id, row_id)]) token_type_ids_example[:, 3] = model_labels
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
input_ids_example = input_ids[index] attention_mask_example = attention_mask[index] # shape (seq_len,) token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) outputs = self.model( input_ids=np.expand_dims(input_ids_example, axis=0), attention_mask=np.expand_dims(attention_mask_example, axis=0), token_type_ids=np.expand_dims(token_type_ids_example, axis=0), ) logits = outputs.logits if self.aggregate: all_aggregations.append(outputs.logits_aggregation) all_logits.append(logits) probabilities = tf.math.sigmoid(tf.cast(logits, tf.float32)) * tf.cast( attention_mask_example, tf.float32 )
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
coords_to_probs = collections.defaultdict(list) token_type_ids_example = token_type_ids_example for i, p in enumerate(tf.squeeze(probabilities).numpy().tolist()): segment_id = token_type_ids_example[:, 0].tolist()[i] col = token_type_ids_example[:, 1].tolist()[i] - 1 row = token_type_ids_example[:, 2].tolist()[i] - 1 if col >= 0 and row >= 0 and segment_id == 1: coords_to_probs[(col, row)].append(p) prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs} logits_batch = tf.concat(tuple(all_logits), 0) return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(all_aggregations), 0)) def __call__(self, *args, **kwargs): r""" Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
- `pipeline(table, query)` - `pipeline(table, [query])` - `pipeline(table=table, query=query)` - `pipeline(table=table, query=[query])` - `pipeline({"table": table, "query": query})` - `pipeline({"table": table, "query": [query]})` - `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])` The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table: Example: ```python data = { "actors": ["brad pitt", "leonardo di caprio", "george clooney"], "age": ["56", "45", "59"], "number of movies": ["87", "53", "69"], "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], } ``` This dictionary can be passed in as such, or can be converted to a pandas DataFrame: Example: ```python import pandas as pd
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
table = pd.DataFrame.from_dict(data) ``` Args: table (`pd.DataFrame` or `Dict`): Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values. See above for an example of dictionary. query (`str` or `List[str]`): Query or list of queries that will be sent to the model alongside the table. sequential (`bool`, *optional*, defaults to `False`): Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the inference to be done sequentially to extract relations within sequences, given their conversational nature. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values:
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values:
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
- `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate row by row, removing rows from the table. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). Return: A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following keys:
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
- **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will be preceded by `AGGREGATOR >`. - **coordinates** (`List[Tuple[int, int]]`) -- Coordinates of the cells of the answers. - **cells** (`List[str]`) -- List of strings made up of the answer cell values. - **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator. """ pipeline_inputs = self._args_parser(*args, **kwargs) results = super().__call__(pipeline_inputs, **kwargs) if len(results) == 1: return results[0] return results def _sanitize_parameters(self, sequential=None, padding=None, truncation=None, **kwargs): preprocess_params = {} if padding is not None: preprocess_params["padding"] = padding if truncation is not None: preprocess_params["truncation"] = truncation
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
forward_params = {} if sequential is not None: forward_params["sequential"] = sequential if self.assistant_model is not None: forward_params["assistant_model"] = self.assistant_model if self.assistant_tokenizer is not None: forward_params["tokenizer"] = self.tokenizer forward_params["assistant_tokenizer"] = self.assistant_tokenizer return preprocess_params, forward_params, {} def preprocess(self, pipeline_input, sequential=None, padding=True, truncation=None): if truncation is None: if self.type == "tapas": truncation = "drop_rows_to_fit" else: truncation = "do_not_truncate"
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
table, query = pipeline_input["table"], pipeline_input["query"] if table.empty: raise ValueError("table is empty") if query is None or query == "": raise ValueError("query is empty") inputs = self.tokenizer(table, query, return_tensors=self.framework, truncation=truncation, padding=padding) inputs["table"] = table return inputs def _forward(self, model_inputs, sequential=False, **generate_kwargs): table = model_inputs.pop("table") if self.type == "tapas": if sequential: outputs = self.sequential_inference(**model_inputs) else: outputs = self.batch_inference(**model_inputs) else: # 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
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
outputs = self.model.generate(**model_inputs, **generate_kwargs) model_outputs = {"model_inputs": model_inputs, "table": table, "outputs": outputs} return model_outputs def postprocess(self, model_outputs): inputs = model_outputs["model_inputs"] table = model_outputs["table"] outputs = model_outputs["outputs"] if self.type == "tapas": if self.aggregate: logits, logits_agg = outputs[:2] predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits, logits_agg) answer_coordinates_batch, agg_predictions = predictions aggregators = {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(agg_predictions)}
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
no_agg_label_index = self.model.config.no_aggregation_label_index aggregators_prefix = { i: aggregators[i] + " > " for i, pred in enumerate(agg_predictions) if pred != no_agg_label_index } else: logits = outputs[0] predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits) answer_coordinates_batch = predictions[0] aggregators = {} aggregators_prefix = {} answers = [] for index, coordinates in enumerate(answer_coordinates_batch): cells = [table.iat[coordinate] for coordinate in coordinates] aggregator = aggregators.get(index, "") aggregator_prefix = aggregators_prefix.get(index, "") answer = { "answer": aggregator_prefix + ", ".join(cells), "coordinates": coordinates,
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
"cells": [table.iat[coordinate] for coordinate in coordinates], } if aggregator: answer["aggregator"] = aggregator
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
answers.append(answer) if len(answer) == 0: raise PipelineException("Empty answer") else: answers = [{"answer": answer} for answer in self.tokenizer.batch_decode(outputs, skip_special_tokens=True)] return answers if len(answers) > 1 else answers[0]
449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/table_question_answering.py
class PipelineException(Exception): """ Raised by a [`Pipeline`] when handling __call__. Args: task (`str`): The task of the pipeline. model (`str`): The model used by the pipeline. reason (`str`): The error message to display. """ def __init__(self, task: str, model: str, reason: str): super().__init__(reason) self.task = task self.model = model
450
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class ArgumentHandler(ABC): """ Base interface for handling arguments for each [`~pipelines.Pipeline`]. """ @abstractmethod def __call__(self, *args, **kwargs): raise NotImplementedError()
451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class PipelineDataFormat: """ Base class for all the pipeline supported data format both for reading and writing. Supported data formats currently includes: - JSON - CSV - stdin/stdout (pipe) `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format. Args: output_path (`str`): Where to save the outgoing data. input_path (`str`): Where to look for the input data. column (`str`): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. """ SUPPORTED_FORMATS = ["json", "csv", "pipe"]
452
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def __init__( self, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite: bool = False, ): self.output_path = output_path self.input_path = input_path self.column = column.split(",") if column is not None else [""] self.is_multi_columns = len(self.column) > 1 if self.is_multi_columns: self.column = [tuple(c.split("=")) if "=" in c else (c, c) for c in self.column] if output_path is not None and not overwrite: if exists(abspath(self.output_path)): raise OSError(f"{self.output_path} already exists on disk") if input_path is not None: if not exists(abspath(self.input_path)): raise OSError(f"{self.input_path} doesnt exist on disk") @abstractmethod def __iter__(self): raise NotImplementedError()
452
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
@abstractmethod def save(self, data: Union[dict, List[dict]]): """ Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`]. Args: data (`dict` or list of `dict`): The data to store. """ raise NotImplementedError() def save_binary(self, data: Union[dict, List[dict]]) -> str: """ Save the provided data object as a pickle-formatted binary data on the disk. Args: data (`dict` or list of `dict`): The data to store. Returns: `str`: Path where the data has been saved. """ path, _ = os.path.splitext(self.output_path) binary_path = os.path.extsep.join((path, "pickle")) with open(binary_path, "wb+") as f_output: pickle.dump(data, f_output) return binary_path
452
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
@staticmethod def from_str( format: str, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite=False, ) -> "PipelineDataFormat": """ Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`. Args: format (`str`): The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`. output_path (`str`, *optional*): Where to save the outgoing data. input_path (`str`, *optional*): Where to look for the input data. column (`str`, *optional*): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`.
452
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
Returns: [`~pipelines.PipelineDataFormat`]: The proper data format. """ if format == "json": return JsonPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) elif format == "csv": return CsvPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) elif format == "pipe": return PipedPipelineDataFormat(output_path, input_path, column, overwrite=overwrite) else: raise KeyError(f"Unknown reader {format} (Available reader are json/csv/pipe)")
452
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class CsvPipelineDataFormat(PipelineDataFormat): """ Support for pipelines using CSV data format. Args: output_path (`str`): Where to save the outgoing data. input_path (`str`): Where to look for the input data. column (`str`): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. """ def __init__( self, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite=False, ): super().__init__(output_path, input_path, column, overwrite=overwrite) def __iter__(self): with open(self.input_path, "r") as f: reader = csv.DictReader(f) for row in reader: if self.is_multi_columns: yield {k: row[c] for k, c in self.column} else: yield row[self.column[0]]
453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def save(self, data: List[dict]): """ Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`]. Args: data (`List[dict]`): The data to store. """ with open(self.output_path, "w") as f: if len(data) > 0: writer = csv.DictWriter(f, list(data[0].keys())) writer.writeheader() writer.writerows(data)
453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class JsonPipelineDataFormat(PipelineDataFormat): """ Support for pipelines using JSON file format. Args: output_path (`str`): Where to save the outgoing data. input_path (`str`): Where to look for the input data. column (`str`): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. """ def __init__( self, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite=False, ): super().__init__(output_path, input_path, column, overwrite=overwrite) with open(input_path, "r") as f: self._entries = json.load(f) def __iter__(self): for entry in self._entries: if self.is_multi_columns: yield {k: entry[c] for k, c in self.column} else: yield entry[self.column[0]]
454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def save(self, data: dict): """ Save the provided data object in a json file. Args: data (`dict`): The data to store. """ with open(self.output_path, "w") as f: json.dump(data, f)
454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class PipedPipelineDataFormat(PipelineDataFormat): """ Read data from piped input to the python process. For multi columns data, columns should separated by \t If columns are provided, then the output will be a dictionary with {column_x: value_x} Args: output_path (`str`): Where to save the outgoing data. input_path (`str`): Where to look for the input data. column (`str`): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. """ def __iter__(self): for line in sys.stdin: # Split for multi-columns if "\t" in line: line = line.split("\t") if self.column: # Dictionary to map arguments yield {kwargs: l for (kwargs, _), l in zip(self.column, line)} else: yield tuple(line)
455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
# No dictionary to map arguments else: yield line def save(self, data: dict): """ Print the data. Args: data (`dict`): The data to store. """ print(data) def save_binary(self, data: Union[dict, List[dict]]) -> str: if self.output_path is None: raise KeyError( "When using piped input on pipeline outputting large object requires an output file path. " "Please provide such output path through --output argument." ) return super().save_binary(data)
455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class _ScikitCompat(ABC): """ Interface layer for the Scikit and Keras compatibility. """ @abstractmethod def transform(self, X): raise NotImplementedError() @abstractmethod def predict(self, X): raise NotImplementedError()
456
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py