File size: 29,466 Bytes
cfa6e1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# coding=utf-8
# Copyright 2024 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 BailingMM2."""

import numpy as np
import re
import sys
from typing import Iterable, List, Union, Dict, Optional, Tuple

import torch
import PIL
from PIL import Image

if sys.version_info >= (3, 11):
    from typing import Unpack
else:
    from typing_extensions import Unpack

from transformers.feature_extraction_utils import BatchFeature
from transformers.image_utils import ImageInput
from transformers.processing_utils import (
    ProcessingKwargs,
    ProcessorMixin,
)
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput

from .bailingmm_utils import (
    get_default_image_gen_hw,
    process_ratio,
    process_reference_vision_info,
    process_vision_info,
)
from .bailingmm_utils_video import VideoInput
import torchvision
import math

DEFAULT_IMAGE_PATCH_TOKEN = "<|image_pad|>"
DEFAULT_IM_START_TOKEN = "<|vision_start|>"
DEFAULT_IM_END_TOKEN = "<|vision_end|>"

DEFAULT_FRAME_PATCH_TOKEN = "<|video_pad|>"
DEFAULT_VID_START_TOKEN = "<|video_start|>"
DEFAULT_VID_END_TOKEN = "<|video_end|>"


USER_PREFIX = "<role>HUMAN</role>"
ASSISTANT_PREFIX = "<role>ASSISTANT</role>"

SYSTEM_PROMPT_LINGV2_FLASH_NOTHINK = "<role>SYSTEM</role>你是一个友好的AI助手。\n\ndetailed thinking off"
SYSTEM_PROMPT_LINGV2_FLASH_THINK = "<role>SYSTEM</role>你是一个友好的AI助手。\n\ndetailed thinking on"

def check_single_quotes(s):
    count = s.count("'")
    if count % 2 != 0:
        return False

    positions = [i for i, char in enumerate(s) if char == "'"]
    for i in range(0, len(positions), 2):
        start = positions[i]
        end = positions[i+1]
        substr = s[start+1:end]
        chinese_count = 0
        for char in substr:
            if '\u4e00' <= char <= '\u9fff':
                chinese_count += 1
        other_count = len(substr) - chinese_count
        total = 3 * chinese_count + other_count
        if total >= 20:
            return False
    return True

def get_text_from_prompt(prompt):
    if "'" in prompt and check_single_quotes(prompt):
        prompt = prompt.replace("'", '"')

    patterns = [r'\"(.*?)\"', r'‘(.*?)’', r'“(.*?)”']

    # keywords = ["write", "add", "text", "change", "characters", "word", "文本", "替换", "文字"]
    
    import re
    texts = []
    patterns = [r'\"(.*?)\"', r'‘(.*?)’', r'“(.*?)”']
    for pattern in patterns:
        texts.extend(re.findall(pattern, prompt))

    if len(texts) == 1:
        assert texts[0] in prompt
        is_remove = False
        remove_keywords = ["remove", "delete", "erase"]
        text_start = min([j for j in [prompt.find(i) for i in ['"', '‘', '“']] if j >= 0])
        for kw in remove_keywords:
            if kw in prompt.lower():
                if prompt.lower().find(kw) < text_start:
                    is_remove = True
                    break
        
        if is_remove:
            texts = []
    
    text = " ".join(texts[-1:])
    if len(text) > 0:
        text = f'Text "{text}"'
        text += ". "

    return text

def crop_to_aspect_max(img: Image.Image, target_ratio: float) -> Image.Image:
    """
    按目标宽高比(宽/高)对PIL.Image进行最大面积中心裁剪,不缩放。
    使用 torchvision.transforms.CenterCrop。

    参数:
        img: PIL.Image.Image 输入图像
        target_ratio: float 目标宽高比(宽/高),必须为正数

    返回:
        裁剪后的 PIL.Image.Image
    """
    if not isinstance(img, Image.Image):
        raise TypeError("img必须是PIL.Image.Image")
    if not math.isfinite(target_ratio) or target_ratio <= 0:
        raise ValueError("target_ratio必须是正的有限数")

    W, H = img.size
    if W <= 0 or H <= 0:
        raise ValueError("图像尺寸无效")

    orig_ratio = W / H

    if orig_ratio >= target_ratio:
        # 图像比目标更宽:使用满高度,左右裁剪
        new_h = H
        new_w = int(math.floor(target_ratio * H))
        new_w = max(1, min(new_w, W))  # 防止因极端比例导致无效尺寸
    else:
        # 图像比目标更窄:使用满宽度,上下裁剪
        new_w = W
        new_h = int(math.floor(W / target_ratio))
        new_h = max(1, min(new_h, H))

    crop = torchvision.transforms.CenterCrop((new_h, new_w))  # size为(h, w)
    return crop(img)

def transform_reference_images(images, image_gen_aspect_ratio=None, image_gen_resolution=512):

    ref_pil = images[0]
    if image_gen_aspect_ratio is not None:
        ref_pil = crop_to_aspect_max(ref_pil, image_gen_aspect_ratio)

    ref_pil = ref_pil.convert("RGB")
    ori_h = ref_pil.size[1]
    ori_w = ref_pil.size[0]
    closest_size, _ = process_ratio(ori_h=ori_h, ori_w=ori_w, highres=image_gen_resolution)
    
    ref_pils = [torchvision.transforms.functional.resize(i, closest_size, interpolation=torchvision.transforms.InterpolationMode.BILINEAR) for i in images]
    
    ref_tensor = torch.cat([
        ((torchvision.transforms.functional.to_tensor(i) - 0.5) * 2.0).unsqueeze(0)
        for i in ref_pils
    ], dim=0)

    return ref_tensor, ref_pil.size[1], ref_pil.size[0]

class BailingMM2ProcessorKwargs(ProcessingKwargs, total=False):
    # see processing_utils.ProcessingKwargs documentation for usage.
    _defaults = {
        "text_kwargs": {"padding": True, "padding_side": "right"},
        "image_kwargs": {},
        "video_kwargs": {},
    }

class BailingMM2Processor(ProcessorMixin):
    r"""
    Constructs a BailingMM2 processor which wraps a bailingmm2 image processor, bailing audio processor and a LLaMa tokenizer into a single processor.
    Args:
        image_processor ([`BailingMM2ImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`LlamaTokenizerFast`], *optional*):
            The tokenizer is a required input.
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
        image_token (`str`, *optional*, defaults to `"<image>"`):
            Special token used to denote image location.
        video_token (`str`, *optional*, defaults to `"<video>"`):
            Special token used to denote video location.
    """

    attributes = ["image_processor", "tokenizer"]
    optional_attributes = ["chat_template"]

    image_processor_class = "AutoImageProcessor"
    tokenizer_class = "AutoTokenizer"

    valid_kwargs = [
        "chat_template",
        "num_image_tokens",
        "image_token",
        "video_token",
        "use_interleaved_frame_timestamp",
    ]

    def __init__(
        self,
        image_processor=None,
        tokenizer=None,
        chat_template=None,
        image_token=None,
        video_token=None,
        **kwargs: Unpack[BailingMM2ProcessorKwargs],
    ):
        self.image_token = image_token or self._get_token_from_tokenizer(tokenizer, "image_token", DEFAULT_IMAGE_PATCH_TOKEN)
        self.video_token = video_token or self._get_token_from_tokenizer(tokenizer, "video_token", DEFAULT_FRAME_PATCH_TOKEN)
        self.vision_start_token = self._get_token_from_tokenizer(tokenizer, "vision_bos_token", DEFAULT_IM_START_TOKEN)
        self.vision_end_token = self._get_token_from_tokenizer(tokenizer, "vision_eos_token", DEFAULT_IM_END_TOKEN)
        self.video_start_token = self._get_token_from_tokenizer(tokenizer, "video_bos_token", DEFAULT_VID_START_TOKEN)
        self.video_end_token = self._get_token_from_tokenizer(tokenizer, "video_eos_token", DEFAULT_VID_END_TOKEN)
        self.image_token_id = self._get_token_id_from_tokenizer(tokenizer, "image_token_id", self.image_token)
        self.video_token_id = self._get_token_id_from_tokenizer(tokenizer, "video_token_id", self.video_token)

        if chat_template is None:
            chat_template = tokenizer.chat_template

        self.gen_terminator = [tokenizer.eos_token_id]
        super().__init__(image_processor, tokenizer, chat_template=chat_template)

    @staticmethod
    def _get_token_from_tokenizer(tokenizer, name: str, fallback: str, aliases: Tuple[str, ...] = ()) -> str:
        for key in (name, *aliases):
            token = getattr(tokenizer, key, None)
            if token is not None:
                return token

        extra_special_tokens = getattr(tokenizer, "init_kwargs", {}).get("extra_special_tokens", {})
        for key in (name, *aliases):
            token = extra_special_tokens.get(key)
            if token is not None:
                return token

        special_tokens_map = getattr(tokenizer, "special_tokens_map", {})
        for key in (name, *aliases):
            token = special_tokens_map.get(key)
            if token is not None:
                return token

        return fallback

    @staticmethod
    def _get_token_id_from_tokenizer(tokenizer, name: str, token: str, aliases: Tuple[str, ...] = ()) -> int:
        for key in (name, *aliases):
            token_id = getattr(tokenizer, key, None)
            if token_id is not None:
                return token_id
        return tokenizer.convert_tokens_to_ids(token)

    def __call__(
        self,
        images: ImageInput = None,
        videos: VideoInput = None,
        text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
        image_gen_highres = 1024,
        image_gen_aspect_ratio = None,
        image_gen_ref_images: Union["PIL.Image.Image", list["PIL.Image.Image"]] = None,
        **kwargs,
    ) -> BatchFeature:
        """
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        LlavaNextImageProcessor's [`~LlavaNextImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
        of the above two methods for more information.

        Args:
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or torch Tensor.
                tensor. Both channels-first and channels-last formats are supported.
            videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
                The image or batch of videos to be prepared. Each video can be a 4D NumPy array or torch Tensor.
            text (`str`, `List[str]`, `List[List[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as a list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).

        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:

            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
              `None`).
            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
            - **image_num_patches** -- Patch number to be fed to a model. Returned when `images` is not `None`.
            - **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
            - **pixel_values_videos** -- Pixel values of a video input to be fed to a model. Returned when `videos` is not `None`.

        """
        output_kwargs = self._merge_kwargs(
            BailingMM2ProcessorKwargs,
            tokenizer_init_kwargs=self.tokenizer.init_kwargs,
            **kwargs,
        )
        for key in output_kwargs.keys():
            if key != 'audio_kwargs' and 'use_whisper_encoder' in output_kwargs[key]:
                output_kwargs[key].pop('use_whisper_encoder')

        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")

        wrappers = (
            self.vision_start_token + self.image_token + self.vision_end_token,
            self.video_start_token + self.video_token + self.video_end_token,
            self.vision_start_token + self.video_token + self.vision_end_token,
        )
        pattern = "(" + "|".join(re.escape(token) for token in wrappers) + ")"
        # Preserve complete media wrappers; escape literal markers elsewhere.
        text = [
            "".join(part if i % 2 else self.escape_multimodal_tokens(part)
                    for i, part in enumerate(re.split(pattern, sample)))
            for sample in text
        ]

        image_inputs = {}
        video_inputs = {}
        image_gen_inputs = {}

        text_in_text = [get_text_from_prompt(i) for i in text]


        default_image_gen_height, default_image_gen_width = get_default_image_gen_hw(image_gen_highres, image_gen_aspect_ratio)
        
        image_gen_inputs.update({
            "image_gen_text": text_in_text,
            "image_gen_highres": image_gen_highres,
            "image_gen_height": torch.LongTensor([default_image_gen_height]),
            "image_gen_width": torch.LongTensor([default_image_gen_width]),
        })

        if images is not None:
            image_inputs = self.image_processor(images=images, videos=None, **output_kwargs["images_kwargs"])
            image_grid_thw = image_inputs["image_grid_thw"]
            
            text = self._expand_image_tokens(text, image_grid_thw)

            # image_gen_pixel_values_reference, image_gen_height, image_gen_width = None, 512, 512
            if image_gen_ref_images is not None:
                if isinstance(image_gen_ref_images, PIL.Image.Image):
                    image_gen_ref_images = [image_gen_ref_images]
                elif not isinstance(image_gen_ref_images, list) and not isinstance(image_gen_ref_images[0], PIL.Image.Image):
                    raise ValueError("Invalid input image_gen_ref_images. Please provide a PIL.Image.Image, or a list of PIL.Image.Image")

                assert len(image_gen_ref_images) == len(text) # same batch_size 

                image_gen_pixel_values_reference, image_gen_height_list, image_gen_width_list = transform_reference_images(image_gen_ref_images, image_gen_aspect_ratio, image_gen_highres)
            
                image_gen_inputs.update({
                    "image_gen_pixel_values_reference": image_gen_pixel_values_reference,
                    "image_gen_height": torch.LongTensor([image_gen_height_list]),
                    "image_gen_width": torch.LongTensor([image_gen_width_list]),
                    #"image_gen_height": torch.LongTensor([ori_h]),
                    #"image_gen_width": torch.LongTensor([ori_w]),
                })

        if videos is not None:
            video_metas = [_[1] for _ in videos]
            video_contents = [_[0] for _ in videos]
            videos_timestamps_seconds = [_["resmp_ts"] for _ in video_metas]
            video_inputs = self.image_processor(
                images=None,
                videos=video_contents,
                do_resize=False,
                videos_timestamps_seconds=videos_timestamps_seconds,
                **output_kwargs["videos_kwargs"],
            )
            text = self._expand_video_tokens(text, video_inputs)


        # Padding side can be in TextKwargs but is not accepted by the tokenizer
        _ = output_kwargs["text_kwargs"].pop("padding_side", None)
        text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])

        if images is not None or videos is not None:
            input_ids = text_inputs["input_ids"]
            if torch.is_tensor(input_ids):
                mm_token_type_ids = torch.zeros_like(input_ids)
                mm_token_type_ids[input_ids == self.image_token_id] = 1
                mm_token_type_ids[input_ids == self.video_token_id] = 2
            else:
                mm_token_type_ids = []
                for input_ids_sample in input_ids:
                    mm_token_type_ids.append(
                        [
                            1 if token == self.image_token_id else 2 if token == self.video_token_id else 0
                            for token in input_ids_sample
                        ]
                    )
            text_inputs["mm_token_type_ids"] = mm_token_type_ids

        return BatchFeature(data={**text_inputs, **image_inputs, **video_inputs})

    def apply_system_template(self, sys_prompt_exp=None, use_cot_system_prompt=False):
        if use_cot_system_prompt:
            sys_prompt = SYSTEM_PROMPT_LINGV2_FLASH_THINK
        else:
            sys_prompt = SYSTEM_PROMPT_LINGV2_FLASH_NOTHINK
        if sys_prompt_exp is not None:
            sys_prompt = sys_prompt.replace("你是一个友好的AI助手。", sys_prompt_exp)

        return sys_prompt

    def escape_multimodal_tokens(self, value):
        """Escape literal multimodal markers before rendering the chat template."""
        if isinstance(value, str):
            tokens = {
                self.image_token, self.video_token,
                self.vision_start_token, self.vision_end_token,
                self.video_start_token, self.video_end_token,
                "<|placeholder|>",
            }
            for token in sorted(tokens, key=len, reverse=True):
                value = value.replace(token, token[:1] + "\\" + token[1:])
            return value
        if isinstance(value, dict):
            media_fields = {
                "image": {"image", "source"},
                "image_url": {"image_url"},
                "video": {"video", "source"},
                "video_url": {"video_url"},
            }.get(value.get("type") if isinstance(value.get("type"), str) else None, set())
            return {
                key: item if key in media_fields
                else self.escape_multimodal_tokens(item)
                for key, item in value.items()
            }
        if isinstance(value, (list, tuple)):
            return type(value)(self.escape_multimodal_tokens(item) for item in value)
        return value

    def apply_chat_template(
        self,
        conversation: Union[List[Dict[str, str]]],
        sys_prompt_exp: Optional[str] = None,
        use_cot_system_prompt: Optional[bool] = False,
        **kwargs,
    ) -> str:
        """
        Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input
        conversations to turn them into a single tokenizable string.

        Args:
            conversation (`List[Dict, str, str]`):
                The conversation to format.
            sys_prompt_exp (`Optional[str]`, *optional*):
                The system prompt. If not provided, the processor's sysyetm template is used.
            **kwargs:
                Additional keyword arguments
        """
        conversation = self.escape_multimodal_tokens(conversation)
        sys_prompt_exp = self.escape_multimodal_tokens(sys_prompt_exp)
        for key in ("tools", "documents"):
            if key in kwargs:
                kwargs[key] = self.escape_multimodal_tokens(kwargs[key])

        chat_template = kwargs.pop("chat_template", None)
        if chat_template is None:
            chat_template = getattr(self, "chat_template", None) or getattr(self.tokenizer, "chat_template", None)

        if chat_template is not None:
            if "add_generation_prompt" not in kwargs and not kwargs.get("continue_final_message", False):
                kwargs["add_generation_prompt"] = True
            return super().apply_chat_template(
                conversation=conversation,
                chat_template=chat_template,
                **kwargs,
            )

        text = ""
        sys_prompt = self.apply_system_template(sys_prompt_exp, use_cot_system_prompt)
        text = sys_prompt + self.tokenizer.eos_token

        for idx, message in enumerate(conversation):
            assert message["role"] in ["HUMAN", "ASSISTANT"]
            if idx == len(conversation) - 1:
                assert message["role"] == "HUMAN"

            if message["role"] == "HUMAN":
                text += USER_PREFIX
            elif message["role"] == "ASSISTANT":
                text += ASSISTANT_PREFIX

            message_content = str(message["content"])
            image_counts = message_content.count(self.image_token)
            video_counts = message_content.count(self.video_token)

            for content in message["content"]:
                if content["type"] == "image":
                    num_images = 1 if isinstance(content["image"], (str, Image.Image)) else len(content["image"])
                    if image_counts >= num_images:
                        image_counts -= num_images
                    else:
                        image_placeholder = (
                            self.vision_start_token + self.image_token + self.vision_end_token + "\n"
                        ) * (num_images - image_counts)
                        text += image_placeholder.rstrip("\n")
                        image_counts = 0
                elif content["type"] == "video":
                    assert video_counts <= 1, "Video count must be at most 1!"
                    if video_counts == 0:
                        text += self.video_start_token + self.video_token + self.video_end_token
                elif content["type"] == "text":
                    text += content['text']
            text += self.tokenizer.eos_token
        text += ASSISTANT_PREFIX
        
        return text

    def process_vision_info(
        self,
        conversations,
    ):
        return process_vision_info(conversations)

    def process_reference_vision_info(
        self,
        conversations,
    ):
        return process_reference_vision_info(conversations)

    def _expand_image_tokens(
        self,
        text: List[TextInput],
        image_grid_thw: Union[List[int], int],
        special_token: Optional[str] = None,
    ):
        special_token = special_token or self.image_token
        placeholder_token = "<|placeholder|>"
        prompt_strings = []
        image_index = 0
        num_query_token = torch.prod(image_grid_thw, dim=1) // 4
        wrapped_special_token = self.vision_start_token + special_token + self.vision_end_token
        for sample in text:
            num_images = sample.count(special_token)
            if num_images > 0:
                for i in range(image_index, num_images + image_index):
                    image_text = int(num_query_token[i].item()) * placeholder_token
                    replacement = self.vision_start_token + image_text + self.vision_end_token + "\n"
                    if wrapped_special_token in sample:
                        sample = sample.replace(wrapped_special_token, replacement, 1)
                    else:
                        sample = sample.replace(special_token, replacement, 1)
                sample = sample.replace(placeholder_token, special_token)
            image_index += num_images
            prompt_strings.append(sample)
        text = [sample for sample in prompt_strings]
        return text

    def _expand_video_tokens(
        self,
        text: List[TextInput],
        video_inputs: Dict,
        special_token: Optional[str] = None,
    ):
        special_token = special_token or self.video_token
        placeholder_token = "<|placeholder|>"
        prompt_strings = []
        video_index = 0
        video_grid_thw = video_inputs["video_grid_thw"]
        video_timestamps_seconds = video_inputs.pop("video_timestamps_seconds")
        use_interleaved_frame_timestamp = self.image_processor.__dict__.get(
            "use_interleaved_frame_timestamp", False
        )
        for sample in text:
            num_video_placeholder = sample.count(special_token)
            if num_video_placeholder > 0:
                for i in range(video_index, num_video_placeholder + video_index):
                    if not use_interleaved_frame_timestamp:
                        num_query_token = (
                            torch.prod(
                                video_grid_thw[i],
                            )
                            // 4
                        )
                        video_text = int(num_query_token.item()) * placeholder_token
                    else:
                        video_t, video_h, video_w = video_grid_thw[i].tolist()
                        video_text = ""
                        for tix in range(video_t):
                            video_text += (
                                f"<{video_timestamps_seconds[i][tix]:.1f} seconds>"
                                + self.vision_start_token
                                + int(video_h * video_w // 4)
                                * placeholder_token
                                + self.vision_end_token
                            )

                    video_wrapped_special_token = self.video_start_token + special_token + self.video_end_token
                    vision_wrapped_special_token = self.vision_start_token + special_token + self.vision_end_token
                    if video_wrapped_special_token in sample:
                        replacement = self.video_start_token + video_text + self.video_end_token
                        if not use_interleaved_frame_timestamp:
                            replacement += "\n"
                        sample = sample.replace(
                            video_wrapped_special_token,
                            replacement,
                            1,
                        )
                    elif vision_wrapped_special_token in sample:
                        if use_interleaved_frame_timestamp:
                            sample = sample.replace(vision_wrapped_special_token, video_text, 1)
                        else:
                            replacement = self.vision_start_token + video_text + self.vision_end_token + "\n"
                            sample = sample.replace(
                                vision_wrapped_special_token,
                                replacement,
                                1,
                            )
                    elif special_token != self.video_token:
                        sample = sample.replace(
                            special_token,
                            self.video_start_token + video_text + self.video_end_token + "\n",
                            1,
                        )
                    else:
                        sample = sample.replace(special_token, video_text, 1)
                sample = sample.replace(placeholder_token, self.video_token)
            video_index += num_video_placeholder
            prompt_strings.append(sample)
        text = [sample for sample in prompt_strings]
        if use_interleaved_frame_timestamp:
            video_grid_thw = torch.repeat_interleave(
                video_grid_thw, video_grid_thw[:, 0], dim=0
            )
            video_grid_thw[:, 0] = 1
            video_inputs["video_grid_thw"] = video_grid_thw
        return text


    # 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)

    @property
    def model_input_names(self):
        tokenizer_input_names = self.tokenizer.model_input_names
        image_processor_input_names = self.image_processor.model_input_names
        all_names = tokenizer_input_names + image_processor_input_names

        return list(dict.fromkeys(all_names))