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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
"""
Molmo 2 Custom Inference Handler for Hugging Face Inference Endpoints
Model: allenai/Molmo2-8B

For ProofPath video assessment - video pointing, tracking, and grounded analysis.
Unique capability: Returns pixel-level coordinates for objects in videos.
"""

from typing import Dict, List, Any, Optional, Tuple, Union
import torch
import numpy as np
import base64
import io
import tempfile
import os
import re


class EndpointHandler:
    def __init__(self, path: str = ""):
        """
        Initialize Molmo 2 model for video pointing and tracking.
        
        Args:
            path: Path to the model directory (provided by HF Inference Endpoints)
        """
        from transformers import AutoProcessor, AutoModelForImageTextToText
        
        # Use the model path provided by the endpoint, or default to HF hub
        model_id = path if path else "allenai/Molmo2-8B"
        
        # Determine device
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        
        # Load processor and model
        self.processor = AutoProcessor.from_pretrained(
            model_id,
            trust_remote_code=True,
            dtype="auto",
            device_map="auto" if torch.cuda.is_available() else None
        )
        
        self.model = AutoModelForImageTextToText.from_pretrained(
            model_id,
            trust_remote_code=True,
            torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
            device_map="auto" if torch.cuda.is_available() else None,
        )
        
        if not torch.cuda.is_available():
            self.model = self.model.to(self.device)
        
        self.model.eval()
        
        # Molmo 2 limits: 128 frames max at 2fps
        self.max_frames = 128
        self.default_fps = 2.0
        
        # Regex patterns for parsing Molmo output
        self.COORD_REGEX = re.compile(r"<(?:points|tracks).*? coords=\"([0-9\t:;, .]+)\"/?>")
        self.FRAME_REGEX = re.compile(r"(?:^|\t|:|,|;)([0-9\.]+) ([0-9\. ]+)")
        self.POINTS_REGEX = re.compile(r"([0-9]+) ([0-9]{3,4}) ([0-9]{3,4})")
    
    def _parse_video_points(
        self, 
        text: str, 
        image_w: int, 
        image_h: int,
        extract_ids: bool = False
    ) -> List[Tuple]:
        """
        Extract video pointing coordinates from Molmo output.
        
        Molmo outputs coordinates in XML-like format:
        <points alt="object" coords="8.5 0 183 216; 8.5 1 245 198"/>
        
        Where:
        - 8.5 = timestamp/frame
        - 0, 1 = instance IDs
        - 183 216, 245 198 = x, y coordinates (scaled by 1000)
        
        Returns: List of (timestamp, x, y) or (timestamp, id, x, y) tuples
        """
        all_points = []
        
        for coord_match in self.COORD_REGEX.finditer(text):
            for frame_match in self.FRAME_REGEX.finditer(coord_match.group(1)):
                timestamp = float(frame_match.group(1))
                
                for point_match in self.POINTS_REGEX.finditer(frame_match.group(2)):
                    instance_id = point_match.group(1)
                    # Coordinates are scaled by 1000
                    x = float(point_match.group(2)) / 1000 * image_w
                    y = float(point_match.group(3)) / 1000 * image_h
                    
                    if 0 <= x <= image_w and 0 <= y <= image_h:
                        if extract_ids:
                            all_points.append((timestamp, int(instance_id), x, y))
                        else:
                            all_points.append((timestamp, x, y))
        
        return all_points
    
    def _parse_multi_image_points(
        self,
        text: str,
        widths: List[int],
        heights: List[int]
    ) -> List[Tuple]:
        """Parse pointing coordinates across multiple images."""
        all_points = []
        
        for coord_match in self.COORD_REGEX.finditer(text):
            for frame_match in self.FRAME_REGEX.finditer(coord_match.group(1)):
                # For multi-image, frame_id is 1-indexed image number
                image_idx = int(frame_match.group(1)) - 1
                
                if 0 <= image_idx < len(widths):
                    w, h = widths[image_idx], heights[image_idx]
                    
                    for point_match in self.POINTS_REGEX.finditer(frame_match.group(2)):
                        x = float(point_match.group(2)) / 1000 * w
                        y = float(point_match.group(3)) / 1000 * h
                        
                        if 0 <= x <= w and 0 <= y <= h:
                            all_points.append((image_idx + 1, x, y))
        
        return all_points
    
    def _load_image(self, image_data: Any):
        """Load a single image from various formats."""
        from PIL import Image
        import requests
        
        if isinstance(image_data, Image.Image):
            return image_data
        elif isinstance(image_data, str):
            if image_data.startswith(('http://', 'https://')):
                response = requests.get(image_data, stream=True)
                return Image.open(response.raw).convert('RGB')
            elif image_data.startswith('data:'):
                header, encoded = image_data.split(',', 1)
                image_bytes = base64.b64decode(encoded)
                return Image.open(io.BytesIO(image_bytes)).convert('RGB')
            else:
                image_bytes = base64.b64decode(image_data)
                return Image.open(io.BytesIO(image_bytes)).convert('RGB')
        elif isinstance(image_data, bytes):
            return Image.open(io.BytesIO(image_data)).convert('RGB')
        else:
            raise ValueError(f"Unsupported image input type: {type(image_data)}")
    
    def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Process video or images with Molmo 2.
        
        Expected input formats:
        
        1. Video QA:
        {
            "inputs": <video_url_or_base64>,
            "parameters": {
                "prompt": "What happens in this video?",
                "max_new_tokens": 2048
            }
        }
        
        2. Video Pointing (Molmo's unique capability):
        {
            "inputs": <video_url>,
            "parameters": {
                "prompt": "Point to all the people in this video.",
                "mode": "pointing",
                "max_new_tokens": 2048
            }
        }
        
        3. Video Tracking:
        {
            "inputs": <video_url>,
            "parameters": {
                "prompt": "Track the person in the red shirt.",
                "mode": "tracking",
                "max_new_tokens": 2048
            }
        }
        
        4. Image Pointing:
        {
            "inputs": <image_url>,
            "parameters": {
                "prompt": "Point to the Excel cell B2.",
                "mode": "pointing"
            }
        }
        
        5. Multi-image comparison:
        {
            "inputs": [<image1>, <image2>],
            "parameters": {
                "prompt": "Compare these images."
            }
        }
        
        Returns:
        {
            "generated_text": "...",
            "points": [(timestamp, x, y), ...],  # If pointing mode
            "tracks": {"object_id": [(t, x, y), ...]},  # If tracking mode
            "video_metadata": {...}
        }
        """
        inputs = data.get("inputs")
        if inputs is None:
            inputs = data.get("video") or data.get("image") or data.get("images")
        if inputs is None:
            raise ValueError("No input provided. Use 'inputs', 'video', 'image', or 'images' key.")
        
        params = data.get("parameters", {})
        mode = params.get("mode", "default")
        prompt = params.get("prompt", "Describe this content.")
        max_new_tokens = params.get("max_new_tokens", 2048)
        
        try:
            if isinstance(inputs, list):
                return self._process_multi_image(inputs, prompt, params, max_new_tokens)
            elif self._is_video(inputs, params):
                return self._process_video(inputs, prompt, params, max_new_tokens)
            else:
                return self._process_image(inputs, prompt, params, max_new_tokens)
                
        except Exception as e:
            return {"error": str(e), "error_type": type(e).__name__}
    
    def _is_video(self, inputs: Any, params: Dict) -> bool:
        """Determine if input is video."""
        if params.get("input_type") == "video":
            return True
        if params.get("input_type") == "image":
            return False
        
        if isinstance(inputs, str):
            lower = inputs.lower()
            video_exts = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.m4v']
            return any(ext in lower for ext in video_exts)
        
        return False
    
    def _process_video(
        self,
        video_data: Any,
        prompt: str,
        params: Dict,
        max_new_tokens: int
    ) -> Dict[str, Any]:
        """Process video with Molmo 2."""
        try:
            from molmo_utils import process_vision_info
        except ImportError:
            # Fallback if molmo_utils not available
            return self._process_video_fallback(video_data, prompt, params, max_new_tokens)
        
        mode = params.get("mode", "default")
        
        # Prepare video URL or path
        if isinstance(video_data, str) and video_data.startswith(('http://', 'https://')):
            video_source = video_data
        else:
            # Write to temp file
            if isinstance(video_data, str):
                video_bytes = base64.b64decode(video_data)
            else:
                video_bytes = video_data
            
            with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as f:
                f.write(video_bytes)
                video_source = f.name
        
        try:
            messages = [
                {
                    "role": "user",
                    "content": [
                        dict(type="text", text=prompt),
                        dict(type="video", video=video_source),
                    ],
                }
            ]
            
            # Process video with molmo_utils
            _, videos, video_kwargs = process_vision_info(messages)
            videos, video_metadatas = zip(*videos)
            videos, video_metadatas = list(videos), list(video_metadatas)
            
            # Get chat template
            text = self.processor.apply_chat_template(
                messages, 
                tokenize=False, 
                add_generation_prompt=True
            )
            
            # Process inputs
            inputs = self.processor(
                videos=videos,
                video_metadata=video_metadatas,
                text=text,
                padding=True,
                return_tensors="pt",
                **video_kwargs,
            )
            inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
            
            # Generate
            with torch.inference_mode():
                generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
            
            # Decode
            generated_tokens = generated_ids[0, inputs['input_ids'].size(1):]
            generated_text = self.processor.tokenizer.decode(
                generated_tokens, 
                skip_special_tokens=True
            )
            
            # Get video dimensions
            video_w = video_metadatas[0].get("width", 1920)
            video_h = video_metadatas[0].get("height", 1080)
            
            result = {
                "generated_text": generated_text,
                "video_metadata": {
                    "width": video_w,
                    "height": video_h,
                    **{k: v for k, v in video_metadatas[0].items() if k not in ["width", "height"]}
                }
            }
            
            # Parse coordinates based on mode
            if mode in ["pointing", "tracking"]:
                points = self._parse_video_points(
                    generated_text, 
                    video_w, 
                    video_h,
                    extract_ids=(mode == "tracking")
                )
                
                if mode == "tracking":
                    # Group by object ID for tracking
                    from collections import defaultdict
                    tracks = defaultdict(list)
                    for point in points:
                        obj_id = point[1]
                        tracks[obj_id].append((point[0], point[2], point[3]))
                    result["tracks"] = dict(tracks)
                    result["num_objects_tracked"] = len(tracks)
                else:
                    result["points"] = points
                    result["num_points"] = len(points)
            
            return result
            
        finally:
            # Clean up temp file if created
            if not isinstance(video_data, str) or not video_data.startswith(('http://', 'https://')):
                if os.path.exists(video_source):
                    os.unlink(video_source)
    
    def _process_video_fallback(
        self,
        video_data: Any,
        prompt: str,
        params: Dict,
        max_new_tokens: int
    ) -> Dict[str, Any]:
        """Fallback video processing without molmo_utils."""
        # Extract frames manually
        import cv2
        from PIL import Image
        
        # Write video to temp file
        if isinstance(video_data, str):
            if video_data.startswith(('http://', 'https://')):
                import requests
                response = requests.get(video_data, stream=True)
                video_bytes = response.content
            else:
                video_bytes = base64.b64decode(video_data)
        else:
            video_bytes = video_data
        
        with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as f:
            f.write(video_bytes)
            video_path = f.name
        
        try:
            # Extract frames at 2fps, max 128
            cap = cv2.VideoCapture(video_path)
            fps = cap.get(cv2.CAP_PROP_FPS)
            total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            duration = total_frames / fps if fps > 0 else 0
            
            # Sample frames
            target_frames = min(self.max_frames, int(duration * self.default_fps), total_frames)
            frame_indices = np.linspace(0, total_frames - 1, max(1, target_frames), dtype=int)
            
            frames = []
            for idx in frame_indices:
                cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
                ret, frame = cap.read()
                if ret:
                    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    frames.append(Image.fromarray(frame_rgb))
            
            video_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            video_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            cap.release()
            
            # Process as multi-image
            content = [dict(type="text", text=prompt)]
            for frame in frames:
                content.append(dict(type="image", image=frame))
            
            messages = [{"role": "user", "content": content}]
            
            inputs = self.processor.apply_chat_template(
                messages,
                tokenize=True,
                add_generation_prompt=True,
                return_tensors="pt",
                return_dict=True,
            )
            inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
            
            with torch.inference_mode():
                generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
            
            generated_tokens = generated_ids[0, inputs['input_ids'].size(1):]
            generated_text = self.processor.tokenizer.decode(
                generated_tokens, 
                skip_special_tokens=True
            )
            
            mode = params.get("mode", "default")
            result = {
                "generated_text": generated_text,
                "video_metadata": {
                    "width": video_w,
                    "height": video_h,
                    "duration": duration,
                    "sampled_frames": len(frames)
                }
            }
            
            if mode in ["pointing", "tracking"]:
                points = self._parse_video_points(
                    generated_text, 
                    video_w, 
                    video_h,
                    extract_ids=(mode == "tracking")
                )
                
                if mode == "tracking":
                    from collections import defaultdict
                    tracks = defaultdict(list)
                    for point in points:
                        tracks[point[1]].append((point[0], point[2], point[3]))
                    result["tracks"] = dict(tracks)
                else:
                    result["points"] = points
            
            return result
            
        finally:
            if os.path.exists(video_path):
                os.unlink(video_path)
    
    def _process_image(
        self,
        image_data: Any,
        prompt: str,
        params: Dict,
        max_new_tokens: int
    ) -> Dict[str, Any]:
        """Process a single image."""
        image = self._load_image(image_data)
        mode = params.get("mode", "default")
        
        messages = [
            {
                "role": "user",
                "content": [
                    dict(type="text", text=prompt),
                    dict(type="image", image=image),
                ],
            }
        ]
        
        inputs = self.processor.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=True,
            return_tensors="pt",
            return_dict=True,
        )
        inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
        
        with torch.inference_mode():
            generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
        
        generated_tokens = generated_ids[0, inputs['input_ids'].size(1):]
        generated_text = self.processor.tokenizer.decode(
            generated_tokens, 
            skip_special_tokens=True
        )
        
        result = {
            "generated_text": generated_text,
            "image_size": {"width": image.width, "height": image.height}
        }
        
        if mode == "pointing":
            points = self._parse_video_points(generated_text, image.width, image.height)
            result["points"] = points
            result["num_points"] = len(points)
        
        return result
    
    def _process_multi_image(
        self,
        images_data: List,
        prompt: str,
        params: Dict,
        max_new_tokens: int
    ) -> Dict[str, Any]:
        """Process multiple images."""
        images = [self._load_image(img) for img in images_data]
        mode = params.get("mode", "default")
        
        content = [dict(type="text", text=prompt)]
        for image in images:
            content.append(dict(type="image", image=image))
        
        messages = [{"role": "user", "content": content}]
        
        inputs = self.processor.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=True,
            return_tensors="pt",
            return_dict=True,
        )
        inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
        
        with torch.inference_mode():
            generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
        
        generated_tokens = generated_ids[0, inputs['input_ids'].size(1):]
        generated_text = self.processor.tokenizer.decode(
            generated_tokens, 
            skip_special_tokens=True
        )
        
        result = {
            "generated_text": generated_text,
            "num_images": len(images),
            "image_sizes": [{"width": img.width, "height": img.height} for img in images]
        }
        
        if mode == "pointing":
            widths = [img.width for img in images]
            heights = [img.height for img in images]
            points = self._parse_multi_image_points(generated_text, widths, heights)
            result["points"] = points
            result["num_points"] = len(points)
        
        return result