|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""
|
|
Processor class for EMOVA with qwen2vit.
|
|
"""
|
|
|
|
import json
|
|
from typing import List, Union
|
|
|
|
from transformers import AutoProcessor, AutoImageProcessor
|
|
|
|
try:
|
|
from typing import Unpack
|
|
except ImportError:
|
|
from typing_extensions import Unpack
|
|
|
|
from transformers.feature_extraction_utils import BatchFeature
|
|
from .image_utils import ImageInput, VideoInput
|
|
from transformers.processing_utils import (
|
|
ProcessingKwargs,
|
|
ProcessorMixin,
|
|
)
|
|
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
|
|
from transformers.utils import logging
|
|
|
|
from .configuration_emova import EMOVAConfig
|
|
from .image_processing_emova import EMOVAImageProcessor
|
|
|
|
logger = logging.get_logger(__name__)
|
|
|
|
|
|
class EMOVAProcessorKwargs(ProcessingKwargs, total=False):
|
|
_defaults = {
|
|
"text_kwargs": {
|
|
"padding": False,
|
|
},
|
|
}
|
|
|
|
|
|
class EMOVAProcessor(ProcessorMixin):
|
|
r"""
|
|
Constructs a Qwen2-VL processor which wraps a Qwen2-VL image processor and a Qwen2 tokenizer into a single processor.
|
|
[`EMOVAProcessor`] offers all the functionalities of [`EmovaImageProcessor`] and [`Qwen2TokenizerFast`]. See the
|
|
[`~EMOVAProcessor.__call__`] and [`~EMOVAProcessor.decode`] for more information.
|
|
Args:
|
|
image_processor ([`EmovaImageProcessor`], *optional*):
|
|
The image processor is a required input.
|
|
tokenizer ([`Qwen2TokenizerFast`], *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.
|
|
"""
|
|
|
|
attributes = ["image_processor", "tokenizer"]
|
|
valid_kwargs = ["chat_template"]
|
|
image_processor_class = "AutoImageProcessor"
|
|
|
|
tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
|
|
|
|
def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
|
|
super().__init__(image_processor=image_processor, tokenizer=tokenizer, chat_template=chat_template)
|
|
self.speech_tokenizer = None
|
|
|
|
def set_speech_tokenizer(self, tokenizer=None):
|
|
if self.speech_tokenizer and tokenizer:
|
|
logger.info('You are resetting speech tokenizer!')
|
|
return
|
|
self.speech_tokenizer = tokenizer
|
|
logger.info('Setting speech tokenizer!')
|
|
|
|
def prepare_audio_input(self, text, audio, has_image=False):
|
|
if text[0]["role"] == "system":
|
|
system_prompt = text[0]
|
|
valid_index = 1
|
|
else:
|
|
system_prompt = None
|
|
valid_index = 0
|
|
logger.warning("Audio inputs are given, but system prompts are not given.")
|
|
if len(text) > valid_index:
|
|
logger.warning("When audio inputs are given, text inputs except system prompts will be discarded.")
|
|
|
|
audio_chat_format = r'Please recognize the texts, emotion and pitch from the user question speech units and provide the texts, emotion, pitch and speech units for the assistant response. \nEmotion should be chosen from ["neutral", "happy", "sad", "angry", "surprised", "disgusted", "fearful"]. \nPitch should be chosen from ["low", "normal", "high"].\nYour output should be in json format.\nAn output example is:\n{"user question text": "", "user question emotion": "", "user question pitch": "", "assistant response text": "", "assistant response emotion": "", "assistant response pitch": "","assistant response speech": ""}\n\nuser question speech:'
|
|
audio_chat_prompt = audio_chat_format + self.speech_tokenizer.encode(audio)
|
|
|
|
if has_image:
|
|
audio_chat_input = {
|
|
"role": "user",
|
|
"content": [{"type": "image"}, {"type": "text", "text": audio_chat_prompt}],
|
|
}
|
|
else:
|
|
audio_chat_input = {
|
|
"role": "user",
|
|
"content": [{"type": "text", "text": audio_chat_prompt}],
|
|
}
|
|
return [system_prompt, audio_chat_input] if system_prompt else [audio_chat_input]
|
|
|
|
def prepare_audio_output(self, output):
|
|
try:
|
|
if output.startswith('{"{"'):
|
|
return self.prepare_audio_output(output[2:])
|
|
if output.startswith("{"):
|
|
if output.endswith("|>"):
|
|
output += "\"}"
|
|
elif output.endswith("\""):
|
|
output += "}"
|
|
info_dict = json.loads(output)
|
|
content_unit = info_dict['assistant response speech'].strip()
|
|
emotion = info_dict['assistant response emotion'] if 'assistant response emotion' in info_dict else "neutral"
|
|
speed = info_dict['assistant response speed'] if 'assistant response speed' in info_dict else "normal"
|
|
pitch = info_dict['assistant response pitch'] if 'assistant response pitch' in info_dict else "normal"
|
|
except:
|
|
content_unit = output.strip()
|
|
emotion = 'neutral'
|
|
speed = "normal"
|
|
pitch = "normal"
|
|
return content_unit, emotion, speed, pitch
|
|
|
|
def __call__(
|
|
self,
|
|
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
|
images: ImageInput = None,
|
|
audios: Union[str, List[str]] = None,
|
|
**kwargs: Unpack[EMOVAProcessorKwargs],
|
|
) -> 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 Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
|
|
the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
|
|
EmovaImageProcessor's [`~EmovaImageProcessor.__call__`] if `vision_infos` is not `None`.
|
|
|
|
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 PyTorch
|
|
tensor. Both channels-first and channels-last formats are supported.
|
|
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 list of strings (pretokenized), you must set
|
|
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
|
audios (`str`, `List[str]`): Paths to the audio input(s).
|
|
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 PyTorch
|
|
tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
|
|
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
|
If set, will return tensors of a particular framework. Acceptable values are:
|
|
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
|
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
|
- `'np'`: Return NumPy `np.ndarray` objects.
|
|
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
|
|
|
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`.
|
|
- **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
|
|
- **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
|
|
- **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
|
|
"""
|
|
output_kwargs = self._merge_kwargs(
|
|
EMOVAProcessorKwargs,
|
|
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
|
**kwargs,
|
|
)
|
|
if images is not None:
|
|
image_inputs = self.image_processor(images=images, videos=None, **output_kwargs["images_kwargs"])
|
|
image_grid_thw = image_inputs.pop("image_grid_thw")
|
|
image_inputs['image_sizes'] = image_grid_thw
|
|
else:
|
|
image_inputs = {}
|
|
image_sizes = None
|
|
|
|
if audios is not None:
|
|
audios = [audios] if not isinstance(audios, list) else audios
|
|
text = [text] if not isinstance(text[0], list) else text
|
|
assert len(audios) == len(text), "Audio inputs should correspond with text inputs."
|
|
assert self.speech_tokenizer, "Audio inputs are given, while speech tokenizer is not set. Call `EMOVAProcessor.prepare_audio_input()` before processing audio inputs."
|
|
text = [self.prepare_audio_input(txt, audio, has_image=images is not None) for txt, audio in zip(text, audios)]
|
|
|
|
if not isinstance(text, list):
|
|
text = [text]
|
|
|
|
_ = output_kwargs["text_kwargs"].pop("padding_side", None)
|
|
try:
|
|
text = self.apply_chat_template(text, add_generation_prompt=True, padding=True)
|
|
except Exception as e:
|
|
logger.info('Warning: input texts have been applied chat templates!')
|
|
|
|
|
|
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
|
|
|
return BatchFeature(data={**text_inputs, **image_inputs})
|
|
|
|
def batch_decode(self, sequences, output_wav_prefix='output', *args, **kwargs):
|
|
return [self.decode(seq, output_wav_file="{}_{}.wav".format(output_wav_prefix, i), *args, **kwargs)
|
|
for i, seq in enumerate(sequences)]
|
|
|
|
def decode(self, *args, speaker='female', output_wav_file='output.wav', **kwargs):
|
|
output = self.tokenizer.decode(*args, **kwargs)
|
|
if '<|speech_' not in output:
|
|
return output
|
|
content_unit, emotion, speed, pitch = self.prepare_audio_output(output)
|
|
gender = speaker.lower()
|
|
condition = f'gender-{gender}_emotion-{emotion}_speed-{speed}_pitch-{pitch}'
|
|
self.speech_tokenizer.decode(content_unit, condition=condition, output_wav_file=output_wav_file)
|
|
return output_wav_file
|
|
|
|
@property
|
|
def model_input_names(self):
|
|
tokenizer_input_names = self.tokenizer.model_input_names
|
|
image_processor_input_names = self.image_processor.model_input_names
|
|
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
|
|