Upload image_feature_extraction_pipeline.py
Browse files
image_feature_extraction_pipeline.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict
|
2 |
+
|
3 |
+
from ..utils import add_end_docstrings, is_vision_available
|
4 |
+
from .base import GenericTensor, Pipeline, build_pipeline_init_args
|
5 |
+
|
6 |
+
|
7 |
+
if is_vision_available():
|
8 |
+
from ..image_utils import load_image
|
9 |
+
|
10 |
+
|
11 |
+
@add_end_docstrings(
|
12 |
+
build_pipeline_init_args(has_image_processor=True),
|
13 |
+
"""
|
14 |
+
image_processor_kwargs (`dict`, *optional*):
|
15 |
+
Additional dictionary of keyword arguments passed along to the image processor e.g.
|
16 |
+
{"size": {"height": 100, "width": 100}}
|
17 |
+
pool (`bool`, *optional*, defaults to `False`):
|
18 |
+
Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.
|
19 |
+
""",
|
20 |
+
)
|
21 |
+
class ImageFeatureExtractionPipeline(Pipeline):
|
22 |
+
"""
|
23 |
+
Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
|
24 |
+
transformer, which can be used as features in downstream tasks.
|
25 |
+
|
26 |
+
Example:
|
27 |
+
|
28 |
+
```python
|
29 |
+
>>> from transformers import pipeline
|
30 |
+
|
31 |
+
>>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction")
|
32 |
+
>>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True)
|
33 |
+
>>> result.shape # This is a tensor of shape [1, sequence_lenth, hidden_dimension] representing the input image.
|
34 |
+
torch.Size([1, 197, 768])
|
35 |
+
```
|
36 |
+
|
37 |
+
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
|
38 |
+
|
39 |
+
This image feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
|
40 |
+
`"image-feature-extraction"`.
|
41 |
+
|
42 |
+
All vision models may be used for this pipeline. See a list of all models, including community-contributed models on
|
43 |
+
[huggingface.co/models](https://huggingface.co/models).
|
44 |
+
"""
|
45 |
+
|
46 |
+
def _sanitize_parameters(self, image_processor_kwargs=None, return_tensors=None, pool=None, **kwargs):
|
47 |
+
preprocess_params = {} if image_processor_kwargs is None else image_processor_kwargs
|
48 |
+
|
49 |
+
postprocess_params = {}
|
50 |
+
if pool is not None:
|
51 |
+
postprocess_params["pool"] = pool
|
52 |
+
if return_tensors is not None:
|
53 |
+
postprocess_params["return_tensors"] = return_tensors
|
54 |
+
|
55 |
+
if "timeout" in kwargs:
|
56 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
57 |
+
|
58 |
+
return preprocess_params, {}, postprocess_params
|
59 |
+
|
60 |
+
def preprocess(self, image, timeout=None, **image_processor_kwargs) -> Dict[str, GenericTensor]:
|
61 |
+
image = load_image(image, timeout=timeout)
|
62 |
+
model_inputs = self.image_processor(image, return_tensors=self.framework, **image_processor_kwargs)
|
63 |
+
if self.framework == "pt":
|
64 |
+
model_inputs = model_inputs.to(self.torch_dtype)
|
65 |
+
return model_inputs
|
66 |
+
|
67 |
+
def _forward(self, model_inputs):
|
68 |
+
model_outputs = self.model(**model_inputs)
|
69 |
+
return model_outputs
|
70 |
+
|
71 |
+
def postprocess(self, model_outputs, pool=None, return_tensors=False):
|
72 |
+
pool = pool if pool is not None else False
|
73 |
+
|
74 |
+
if pool:
|
75 |
+
if "pooler_output" not in model_outputs:
|
76 |
+
raise ValueError(
|
77 |
+
"No pooled output was returned. Make sure the model has a `pooler` layer when using the `pool` option."
|
78 |
+
)
|
79 |
+
outputs = model_outputs["pooler_output"]
|
80 |
+
else:
|
81 |
+
# [0] is the first available tensor, logits or last_hidden_state.
|
82 |
+
outputs = model_outputs[0]
|
83 |
+
|
84 |
+
if return_tensors:
|
85 |
+
return outputs
|
86 |
+
if self.framework == "pt":
|
87 |
+
return outputs.tolist()
|
88 |
+
elif self.framework == "tf":
|
89 |
+
return outputs.numpy().tolist()
|
90 |
+
|
91 |
+
def __call__(self, *args, **kwargs):
|
92 |
+
"""
|
93 |
+
Extract the features of the input(s).
|
94 |
+
|
95 |
+
Args:
|
96 |
+
images (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
|
97 |
+
The pipeline handles three types of images:
|
98 |
+
|
99 |
+
- A string containing a http link pointing to an image
|
100 |
+
- A string containing a local path to an image
|
101 |
+
- An image loaded in PIL directly
|
102 |
+
|
103 |
+
The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
|
104 |
+
Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
|
105 |
+
images.
|
106 |
+
timeout (`float`, *optional*, defaults to None):
|
107 |
+
The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and
|
108 |
+
the call may block forever.
|
109 |
+
Return:
|
110 |
+
A nested list of `float`: The features computed by the model.
|
111 |
+
"""
|
112 |
+
return super().__call__(*args, **kwargs)
|