File size: 8,480 Bytes
159c520
 
 
 
 
 
 
 
 
 
 
728b3f2
159c520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728b3f2
159c520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728b3f2
159c520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa8ab3
159c520
cfa8ab3
159c520
 
 
 
 
 
 
 
 
728b3f2
159c520
 
 
 
 
 
 
 
cfa8ab3
159c520
 
 
 
 
 
 
 
cfa8ab3
159c520
 
 
 
 
 
f885ed8
159c520
cfa8ab3
159c520
 
 
 
 
cfa8ab3
159c520
 
 
 
 
 
 
cfa8ab3
159c520
 
 
 
 
 
 
 
 
 
cfa8ab3
159c520
 
 
 
cfa8ab3
159c520
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa8ab3
159c520
 
 
 
 
 
 
 
 
 
 
 
 
cfa8ab3
159c520
 
 
 
 
 
 
cfa8ab3
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
import gradio as gr
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
import numpy as np
import tempfile
import os
from decord import VideoReader, cpu
from scipy.spatial import cKDTree
import math
import warnings
import spaces
warnings.filterwarnings("ignore")

# Global variables for model and tokenizer
model = None
tokenizer = None

def load_model():
    """Load the MiniCPM-V-4.5 model and tokenizer"""
    global model, tokenizer
    
    if model is None:
        print("Loading MiniCPM-V-4.5 model...")
        model = AutoModel.from_pretrained(
            'openbmb/MiniCPM-V-4_5', 
            trust_remote_code=True,
            attn_implementation='sdpa', 
            torch_dtype=torch.bfloat16,
            device_map="auto"
        )
        model = model.eval()
        
        tokenizer = AutoTokenizer.from_pretrained(
            'openbmb/MiniCPM-V-4_5', 
            trust_remote_code=True
        )
        print("Model loaded successfully!")
    
    return model, tokenizer

def map_to_nearest_scale(values, scale):
    """Map values to nearest scale for temporal IDs"""
    tree = cKDTree(np.asarray(scale)[:, None])
    _, indices = tree.query(np.asarray(values)[:, None])
    return np.asarray(scale)[indices]

def group_array(arr, size):
    """Group array into chunks of specified size"""
    return [arr[i:i+size] for i in range(0, len(arr), size)]

def uniform_sample(l, n):
    """Uniformly sample n items from list l"""
    gap = len(l) / n
    idxs = [int(i * gap + gap / 2) for i in range(n)]
    return [l[i] for i in idxs]

def encode_video(video_path, choose_fps=3, max_frames=180, max_packing=3, time_scale=0.1):
    """Encode video frames with temporal IDs for the model"""
    vr = VideoReader(video_path, ctx=cpu(0))
    fps = vr.get_avg_fps()
    video_duration = len(vr) / fps
    
    if choose_fps * int(video_duration) <= max_frames:
        packing_nums = 1
        choose_frames = round(min(choose_fps, round(fps)) * min(max_frames, video_duration))
    else:
        packing_nums = math.ceil(video_duration * choose_fps / max_frames)
        if packing_nums <= max_packing:
            choose_frames = round(video_duration * choose_fps)
        else:
            choose_frames = round(max_frames * max_packing)
            packing_nums = max_packing
    
    frame_idx = [i for i in range(0, len(vr))]
    frame_idx = np.array(uniform_sample(frame_idx, choose_frames))
    
    print(f'Video duration: {video_duration:.2f}s, frames: {len(frame_idx)}, packing: {packing_nums}')
    
    frames = vr.get_batch(frame_idx).asnumpy()
    frame_idx_ts = frame_idx / fps
    scale = np.arange(0, video_duration, time_scale)
    frame_ts_id = map_to_nearest_scale(frame_idx_ts, scale) / time_scale
    frame_ts_id = frame_ts_id.astype(np.int32)
    
    frames = [Image.fromarray(v.astype('uint8')).convert('RGB') for v in frames]
    frame_ts_id_group = group_array(frame_ts_id, packing_nums)
    
    return frames, frame_ts_id_group

@spaces.GPU
def process_input(
    file_input, 
    user_prompt, 
    system_prompt, 
    fps, 
    context_size, 
    temperature, 
    enable_thinking
):
    """Process user input and generate response"""
    try:
        # Load model if not already loaded
        model, tokenizer = load_model()
        
        if file_input is None:
            return "Please upload an image or video file."
        
        # Determine if input is image or video
        file_path = file_input
        file_ext = os.path.splitext(file_path)[1].lower()
        
        is_video = file_ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.m4v']
        
        # Prepare messages
        msgs = []
        
        # Add system prompt if provided
        if system_prompt and system_prompt.strip():
            msgs.append({'role': 'system', 'content': system_prompt.strip()})
        
        if is_video:
            # Process video
            frames, frame_ts_id_group = encode_video(file_path, choose_fps=fps)
            msgs.append({'role': 'user', 'content': frames + [user_prompt]})
            
            # Generate response for video
            answer = model.chat(
                msgs=msgs,
                tokenizer=tokenizer,
                use_image_id=False,
                max_slice_nums=1,
                temporal_ids=frame_ts_id_group,
                enable_thinking=enable_thinking,
                max_new_tokens=context_size,
                temperature=temperature
            )
        else:
            # Process image
            image = Image.open(file_path).convert('RGB')
            msgs.append({'role': 'user', 'content': [image, user_prompt]})
            
            # Generate response for image
            answer = model.chat(
                msgs=msgs,
                tokenizer=tokenizer,
                enable_thinking=enable_thinking,
                max_new_tokens=context_size,
                temperature=temperature
            )
        
        return answer
        
    except Exception as e:
        return f"Error processing input: {str(e)}"

def create_interface():
    """Create and configure Gradio interface"""
    
    with gr.Blocks(title="MiniCPM-V-4.5 Multimodal Chat") as iface:
        gr.Markdown("""
        # MiniCPM-V-4.5 Multimodal Chat
        
        A powerful 8B parameter multimodal model that can understand images and videos with GPT-4V level performance.
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                # File input
                file_input = gr.File(
                    label="Upload Image or Video",
                    file_types=["image", "video"]
                )
                
                # Video FPS setting
                fps_slider = gr.Slider(
                    minimum=1,
                    maximum=30,
                    value=5,
                    step=1,
                    label="Video FPS"
                )
                
                # Context size
                context_size = gr.Slider(
                    minimum=512,
                    maximum=4096,
                    value=2048,
                    step=256,
                    label="Max Output Tokens"
                )
                
                # Temperature
                temperature = gr.Slider(
                    minimum=0.1,
                    maximum=2.0,
                    value=0.6,
                    step=0.1,
                    label="Temperature"
                )
                
                # Thinking mode
                enable_thinking = gr.Checkbox(
                    label="Enable Deep Thinking",
                    value=False
                )
                
            with gr.Column(scale=2):
                # System prompt
                system_prompt = gr.Textbox(
                    label="System Prompt (Optional)",
                    placeholder="Enter system instructions here...",
                    lines=3
                )
                
                # User prompt
                user_prompt = gr.Textbox(
                    label="Your Question",
                    placeholder="Describe what you see in the image/video, or ask a specific question...",
                    lines=4
                )
                
                # Submit button
                submit_btn = gr.Button("Generate Response", variant="primary")
                
                # Output
                output = gr.Textbox(
                    label="Model Response",
                    lines=15
                )
        
        # Event handlers
        submit_btn.click(
            fn=process_input,
            inputs=[
                file_input, 
                user_prompt, 
                system_prompt, 
                fps_slider, 
                context_size, 
                temperature,
                enable_thinking
            ],
            outputs=output
        )
        
        user_prompt.submit(
            fn=process_input,
            inputs=[
                file_input, 
                user_prompt, 
                system_prompt, 
                fps_slider, 
                context_size, 
                temperature,
                enable_thinking
            ],
            outputs=output
        )
    
    return iface

if __name__ == "__main__":
    # Create and launch interface
    demo = create_interface()
    demo.launch(share=True)