File size: 11,581 Bytes
159c520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
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

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.name if hasattr(file_input, 'name') else 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", theme=gr.themes.Soft()) 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.
        
        **Features:**
        - πŸ“Έ Single/Multi-image understanding
        - πŸŽ₯ High refresh rate video understanding (up to 10 FPS)
        - πŸ“„ Strong OCR and document parsing
        - 🧠 Controllable fast/deep thinking mode
        - 🌍 Multilingual support (30+ languages)
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                # File input
                file_input = gr.File(
                    label="Upload Image or Video",
                    file_types=["image", "video"],
                    type="filepath"
                )
                
                # Video FPS setting
                fps_slider = gr.Slider(
                    minimum=1,
                    maximum=30,
                    value=5,
                    step=1,
                    label="Video FPS",
                    info="Frames per second for video processing (only applies to videos)"
                )
                
                # Context size
                context_size = gr.Slider(
                    minimum=512,
                    maximum=4096,
                    value=2048,
                    step=256,
                    label="Max Output Tokens",
                    info="Maximum number of tokens to generate"
                )
                
                # Temperature
                temperature = gr.Slider(
                    minimum=0.1,
                    maximum=2.0,
                    value=0.7,
                    step=0.1,
                    label="Temperature",
                    info="Controls randomness in generation"
                )
                
                # Thinking mode
                enable_thinking = gr.Checkbox(
                    label="Enable Deep Thinking",
                    value=False,
                    info="Enable deep thinking mode for complex problem solving"
                )
                
            with gr.Column(scale=2):
                # System prompt
                system_prompt = gr.Textbox(
                    label="System Prompt (Optional)",
                    placeholder="Enter system instructions here...",
                    lines=3,
                    info="Set the behavior and context for the model"
                )
                
                # 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", size="lg")
                
                # Output
                output = gr.Textbox(
                    label="Model Response",
                    lines=15,
                    max_lines=25,
                    show_copy_button=True
                )
                
        # Examples
        gr.Markdown("## πŸ’‘ Example Prompts")
        gr.Examples(
            examples=[
                ["What objects do you see in this image?"],
                ["Describe the scene in detail."],
                ["What is the main action happening in this video?"],
                ["Read and transcribe any text visible in the image."],
                ["What emotions or mood does this image convey?"],
                ["Analyze the composition and visual elements."],
                ["What might happen next in this sequence?"]
            ],
            inputs=[user_prompt],
            label="Click any example to use it"
        )
        
        # Event handlers
        submit_btn.click(
            fn=process_input,
            inputs=[
                file_input, 
                user_prompt, 
                system_prompt, 
                fps_slider, 
                context_size, 
                temperature,
                enable_thinking
            ],
            outputs=output,
            show_progress=True
        )
        
        # Also allow Enter key submission
        user_prompt.submit(
            fn=process_input,
            inputs=[
                file_input, 
                user_prompt, 
                system_prompt, 
                fps_slider, 
                context_size, 
                temperature,
                enable_thinking
            ],
            outputs=output,
            show_progress=True
        )
        
        # Information section
        with gr.Accordion("πŸ“‹ Model Information", open=False):
            gr.Markdown("""
            ### MiniCPM-V-4.5 Specifications
            
            - **Parameters**: 8B (Qwen3-8B + SigLIP2-400M)
            - **Video Compression**: 96x compression rate (6 frames β†’ 64 tokens)
            - **Max Resolution**: Up to 1.8M pixels (1344x1344)
            - **Languages**: 30+ languages supported
            - **Performance**: Surpasses GPT-4o-latest on multiple benchmarks
            
            ### Usage Tips
            
            1. **For Images**: Upload any image format and ask questions about content, objects, text, or analysis
            2. **For Videos**: Adjust FPS based on video content (higher FPS for action, lower for static scenes)
            3. **System Prompt**: Use to set specific roles like "You are an expert art critic" or "Analyze this from a medical perspective"
            4. **Deep Thinking**: Enable for complex reasoning tasks, analysis, or problem-solving
            5. **Temperature**: Lower (0.1-0.3) for factual responses, higher (0.7-1.0) for creative outputs
            
            ### Supported Formats
            - **Images**: JPG, PNG, JPEG, BMP, GIF, WEBP
            - **Videos**: MP4, AVI, MOV, MKV, WEBM, M4V
            """)
    
    return iface

if __name__ == "__main__":
    # Create and launch interface
    demo = create_interface()
    demo.queue(max_size=20)
    demo.launch(
        share=True,
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True
    )