# 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 BLIP-2.
"""

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
from ...tokenization_utils_base import AddedToken, BatchEncoding, PreTokenizedInput, TextInput
from ...utils import auto_docstring, logging


logger = logging.get_logger(__name__)


class Blip2ProcessorKwargs(ProcessingKwargs, total=False):
    _defaults = {
        "text_kwargs": {
            "add_special_tokens": True,
            "padding": False,
            "stride": 0,
            "return_overflowing_tokens": False,
            "return_special_tokens_mask": False,
            "return_offsets_mapping": False,
            "return_token_type_ids": False,
            "return_length": False,
            "verbose": True,
        },
    }


@auto_docstring
class Blip2Processor(ProcessorMixin):
    def __init__(self, image_processor, tokenizer, num_query_tokens=None, **kwargs):
        r"""
        num_query_tokens (`int`, *optional*):
            Number of tokens used by the Qformer as queries, should be same as in model's config.
        """
        tokenizer.return_token_type_ids = False
        if not hasattr(tokenizer, "image_token"):
            self.image_token = AddedToken("<image>", normalized=False, special=True)
            tokenizer.add_tokens([self.image_token], special_tokens=True)
        else:
            self.image_token = tokenizer.image_token
        self.num_query_tokens = num_query_tokens

        super().__init__(image_processor, tokenizer)

    @auto_docstring
    def __call__(
        self,
        images: ImageInput | None = None,
        text: str | list[str] | TextInput | PreTokenizedInput | None = None,
        **kwargs: Unpack[Blip2ProcessorKwargs],
    ) -> BatchEncoding:
        if images is None and text is None:
            raise ValueError("You have to specify either images or text.")
        output_kwargs = self._merge_kwargs(
            Blip2ProcessorKwargs,
            tokenizer_init_kwargs=self.tokenizer.init_kwargs,
            **kwargs,
        )

        # BC for explicit return_tensors
        return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
        max_length = output_kwargs["text_kwargs"].pop("max_length", None)
        if max_length is not None:
            output_kwargs["text_kwargs"]["max_length"] = max_length - self.num_query_tokens

        encoding = BatchFeature(tensor_type=return_tensors)
        if text is not None:
            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")

            # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token
            text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])

            if images is not None and self.num_query_tokens is not None:
                # Image tokens should not be padded/truncated or prepended with special BOS token
                image_tokens = self.image_token.content * self.num_query_tokens
                output_kwargs["text_kwargs"]["add_special_tokens"] = False
                output_kwargs["text_kwargs"]["padding"] = False
                output_kwargs["text_kwargs"]["truncation"] = False
                image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"])
                for k in text_encoding:
                    text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]]
            encoding.update(text_encoding)

        # Now add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
        # else, return the text encoding.
        if images is not None:
            image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
            encoding.update(image_encoding)

        # Cast to desired return tensors type
        encoding = BatchFeature(encoding, tensor_type=return_tensors)
        return encoding


__all__ = ["Blip2Processor"]
