# 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 = "HUMAN" ASSISTANT_PREFIX = "ASSISTANT" SYSTEM_PROMPT_LINGV2_FLASH_NOTHINK = "SYSTEM你是一个友好的AI助手。\n\ndetailed thinking off" SYSTEM_PROMPT_LINGV2_FLASH_THINK = "SYSTEM你是一个友好的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 `""`): Special token used to denote image location. video_token (`str`, *optional*, defaults to `"