File size: 7,256 Bytes
47a9186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# coding=utf-8
# Copyright 2023 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""

Processor class for Centurio.

"""
import timm
import torch
import transformers
from tokenizers import AddedToken
from torchvision.transforms import InterpolationMode, Compose, Resize, ToTensor, Normalize
from transformers import BaseImageProcessor, AutoTokenizer, AutoProcessor, AutoImageProcessor
from typing import List, Union, Optional

from transformers.feature_extraction_utils import BatchFeature
from transformers.image_utils import ImageInput, get_image_size, to_numpy_array
from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, _validate_images_text_input_order
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
from transformers.utils import logging

logger = logging.get_logger(__name__)

class CenturioTimmImageProcessor(BaseImageProcessor):
    r"""



    """
    model_input_names = ["pixel_values"]

    def __init__(

        self,

        timm_model="vit_so400m_patch14_siglip_384",

        tiling=1,

        **kwargs,

    ) -> None:
        config = timm.get_pretrained_cfg(timm_model)
        input_size = config.input_size[1]
        self.timm_model = timm_model
        self.interpolation = config.interpolation
        self.mean = config.mean
        self.std = config.std
        self.tiling = tiling
        self.input_size = (input_size, input_size)


    def __call__(

        self,

        images: ImageInput,

        **kwargs

    ):
        return self.preprocess(images, **kwargs)


    def preprocess(

        self,

        images: ImageInput,

        **kwargs

    ):
        transform = Compose([
            Resize(self.input_size, interpolation=InterpolationMode(self.interpolation)),
            ToTensor(),
            Normalize(mean=self.mean, std=self.std)
        ])
        if self.tiling > 1:

            self.input_size_large = (self.input_size[0] * self.tiling, self.input_size[0] * self.tiling)
            transform_large = Compose([
                Resize(self.input_size_large, interpolation=InterpolationMode(self.interpolation)),
                ToTensor(),
                Normalize(mean=self.mean, std=self.std)
            ])

        processed_images = []
        if not isinstance(images, list):
            images = [images]
        for image_pil in images:
            image = transform(image_pil)  # , return_tensors="pt")["pixel_values"].squeeze()
            if self.tiling > 1:
                image_large = transform_large(image_pil)
                h, w = self.input_size
                img_large_split = [image_large[:, i * h:(i + 1) * h, j * w:(j + 1) * w] for i in range(self.tiling) for
                                   j in range(self.tiling)]
                processed_images.extend([image] + img_large_split)
            else:
                processed_images.append(image)
        processed_images = torch.stack(processed_images, dim=0)
        return BatchFeature(
            data={"pixel_values": processed_images}
        )

AutoImageProcessor.register("CenturioTimmImageProcessor", CenturioTimmImageProcessor)

transformers.CenturioTimmImageProcessor = CenturioTimmImageProcessor

class CenturioProcessor(ProcessorMixin):
    attributes = ["image_processor", "tokenizer"]
    optional_attributes = ["chat_template"]
    image_processor_class = "CenturioTimmImageProcessor"
    tokenizer_class = ("AutoTokenizer")
    image_token="<image_placeholder>"

    def __init__(

        self,

        image_processor=None,

        tokenizer=None,

        tiling=1,

        **kwargs,

    ):
        # tokenizer = AutoTokenizer.from_pretrained(tokenizer, trust_remote_code=True, **kwargs)
        # if self.image_token not in tokenizer.additional_special_tokens:
        #     tokenizer.add_tokens(AddedToken(self.image_token, special=True, normalized=False), special_tokens=True)
        # self.tokenizer = tokenizer
        # self.chat_template = tokenizer.chat_template
        # self.image_processor = CenturioTimmImageProcessor(image_processor, tiling=tiling)
        self.image_processor = image_processor
        self.tokenizer = tokenizer
        # super().__init__(self.image_processor, self.tokenizer)


    def __call__(

        self,

        images: ImageInput = None,

        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,

        **kwargs,

    ) -> BatchFeature:
        """

        """
        if images is None and text is None:
            raise ValueError("You have to specify at least one of `images` or `text`.")

        # check if images and text inputs are reversed for BC
        images, text = _validate_images_text_input_order(images, text)

        if images is not None:
            image_inputs = self.image_processor(images)
        else:
            image_inputs = {}

        if isinstance(text, str):
            text = [text]
        elif not isinstance(text, list) and not isinstance(text[0], str):
            raise ValueError("Invalid input text. Please provide a string, or a list of strings")

        prompt_strings = text

        text_inputs = self.tokenizer(prompt_strings, **kwargs)
        return BatchFeature(data={**text_inputs, **image_inputs})

    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
    def batch_decode(self, *args, **kwargs):
        """

        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please

        refer to the docstring of this method for more information.

        """
        return self.tokenizer.batch_decode(*args, **kwargs)

    # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
    def decode(self, *args, **kwargs):
        """

        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to

        the docstring of this method for more information.

        """
        return self.tokenizer.decode(*args, **kwargs)


# q = CenturioProcessor(
#     tokenizer="Qwen/Qwen2.5-7B-Instruct",
#     image_processor="vit_so400m_patch14_siglip_384",
#     tiling=2
# )
# q.save_pretrained("centurio_qwen")
# a = CenturioProcessor(
#     tokenizer="CohereForAI/aya-expanse-8b",
#     image_processor="vit_so400m_patch14_siglip_384",
#     tiling=2
# )
# a.save_pretrained("centurio_aya")
#
# a = CenturioProcessor.from_pretrained("centurio_aya")
# q = CenturioProcessor.from_pretrained("centurio_qwen")

pass