Feature Extraction
Transformers
Safetensors
English
Chinese
emova
Omni-modal-LLM
Multi-modal-LLM
Emotional-spoken-dialogue
custom_code
Eval Results
File size: 12,192 Bytes
709a849
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# 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 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"
    # image_processor_class = "EMOVAImageProcessor"
    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))