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.",
FutureWarni... | 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.typ... | 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."
... | 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_para... | 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)):
... | 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
... | 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:
... | 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.
strid... | 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_extrac... | 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:
proces... | 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,
... | 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.... | 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")
eli... | 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"... | 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":
... | 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":
... | 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... | 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'... | 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)
... | 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 le... | 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_offse... | 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_... | 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 importa... | 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://huggingfa... | 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:
... | 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 "... | 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*, defau... | 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 `51... | 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** (*opti... | 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... | 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.m... | 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,
... | 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
)
io... | 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... | 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
>>> classifi... | 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/mod... | 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 dire... | 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 c... | 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 ... | 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)
... | 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_inpu... | 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()
... | 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-... | 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 PyT... | 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 image... | 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.... | 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 comple... | 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... | 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... | 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"]
... | 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 = ["sco... | 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... | 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]},
... | 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 ... | 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`"
... | 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["t... | 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... | 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 ... | 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_... | 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_agg... | 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,)
... | 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)
... | 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 ... | 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"]
... | 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 = tok... | 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),
... | 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[:,... | 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": q... | 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[st... | 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 ... | 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 ... | 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... | 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.... | 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=truncatio... | 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"]
... | 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]
predictio... | 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, ... | 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 dat... | 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 [""]
... | 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()
... | 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 ... | 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,... | 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`, *optiona... | 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:
... | 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`, *optio... | 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 ou... | 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 sel... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.