File size: 8,422 Bytes
eb5a9e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Image Processor Module

Handles all image processing operations including loading, validation,
resizing, normalization, and format conversion.
"""

import hashlib
import magic
from pathlib import Path
from typing import Tuple, Optional, Union
import numpy as np
from PIL import Image, ImageOps
from loguru import logger

from core.config import config
from core.exceptions import (
    ImageProcessingError,
    InvalidFileError,
    FileSizeError,
    UnsupportedFormatError,
)


class ImageProcessor:
    """
    Process images for analysis.
    
    Handles validation, resizing, normalization, and format conversion
    for images before they are passed to AI models.
    """
    
    def __init__(self):
        """Initialize ImageProcessor."""
        self.max_size = config.MAX_IMAGE_SIZE
        self.max_dimension = config.IMAGE_MAX_DIMENSION
        self.allowed_formats = config.ALLOWED_IMAGE_FORMATS
        logger.info("ImageProcessor initialized")
    
    def load_image(self, image_path: Union[str, Path]) -> Image.Image:
        """
        Load image from file path.
        
        Args:
            image_path: Path to image file
            
        Returns:
            PIL Image object
            
        Raises:
            InvalidFileError: If image cannot be loaded
        """
        try:
            image_path = Path(image_path)
            if not image_path.exists():
                raise InvalidFileError(
                    f"Image file not found: {image_path}",
                    {"path": str(image_path)}
                )
            
            # Validate file
            self.validate_image(image_path)
            
            # Load image
            image = Image.open(image_path)
            
            # Convert to RGB if necessary
            if image.mode != "RGB":
                image = image.convert("RGB")
            
            logger.info(f"Loaded image: {image_path.name} ({image.size})")
            return image
            
        except Exception as e:
            logger.error(f"Failed to load image: {e}")
            raise InvalidFileError(
                f"Cannot load image: {str(e)}",
                {"path": str(image_path), "error": str(e)}
            )
    
    def validate_image(self, image_path: Path) -> bool:
        """
        Validate image file.
        
        Args:
            image_path: Path to image file
            
        Returns:
            True if valid
            
        Raises:
            FileSizeError: If file too large
            UnsupportedFormatError: If format not supported
            InvalidFileError: If file is corrupted
        """
        # Check file size
        file_size = image_path.stat().st_size
        if file_size > self.max_size:
            raise FileSizeError(
                f"Image too large: {file_size / 1024 / 1024:.1f}MB",
                {"max_size": self.max_size, "actual_size": file_size}
            )
        
        # Check file extension
        ext = image_path.suffix.lower()
        if ext not in self.allowed_formats:
            raise UnsupportedFormatError(
                f"Unsupported image format: {ext}",
                {"allowed": self.allowed_formats, "received": ext}
            )
        
        # Check MIME type using magic bytes
        try:
            mime = magic.from_file(str(image_path), mime=True)
            if not mime.startswith("image/"):
                raise InvalidFileError(
                    f"File is not a valid image: {mime}",
                    {"mime_type": mime}
                )
        except Exception as e:
            logger.warning(f"Could not verify MIME type: {e}")
        
        return True
    
    def resize_image(
        self,
        image: Image.Image,
        max_size: Optional[Tuple[int, int]] = None,
        maintain_aspect_ratio: bool = True
    ) -> Image.Image:
        """
        Resize image to specified dimensions.
        
        Args:
            image: PIL Image object
            max_size: Maximum (width, height) tuple
            maintain_aspect_ratio: Whether to maintain aspect ratio
            
        Returns:
            Resized PIL Image
        """
        if max_size is None:
            max_size = config.DEFAULT_IMAGE_SIZE
        
        original_size = image.size
        
        if maintain_aspect_ratio:
            # Calculate new size maintaining aspect ratio
            image.thumbnail(max_size, Image.Resampling.LANCZOS)
        else:
            # Resize to exact dimensions
            image = image.resize(max_size, Image.Resampling.LANCZOS)
        
        logger.debug(f"Resized image: {original_size} -> {image.size}")
        return image
    
    def normalize_image(self, image: Image.Image) -> np.ndarray:
        """
        Normalize image to numpy array with values [0, 1].
        
        Args:
            image: PIL Image object
            
        Returns:
            Normalized numpy array (H, W, C)
        """
        # Convert to numpy array
        img_array = np.array(image, dtype=np.float32)
        
        # Normalize to [0, 1]
        img_array = img_array / 255.0
        
        logger.debug(f"Normalized image to shape: {img_array.shape}")
        return img_array
    
    def apply_exif_orientation(self, image: Image.Image) -> Image.Image:
        """
        Apply EXIF orientation to image.
        
        Args:
            image: PIL Image object
            
        Returns:
            Oriented PIL Image
        """
        try:
            image = ImageOps.exif_transpose(image)
            logger.debug("Applied EXIF orientation")
        except Exception as e:
            logger.warning(f"Could not apply EXIF orientation: {e}")
        
        return image
    
    def get_image_hash(self, image_path: Path) -> str:
        """
        Generate SHA256 hash of image file.
        
        Args:
            image_path: Path to image file
            
        Returns:
            Hex string of hash
        """
        sha256_hash = hashlib.sha256()
        
        with open(image_path, "rb") as f:
            # Read in chunks to handle large files
            for chunk in iter(lambda: f.read(8192), b""):
                sha256_hash.update(chunk)
        
        return sha256_hash.hexdigest()
    
    def process(
        self,
        image_path: Union[str, Path],
        resize: bool = True,
        normalize: bool = False,
        apply_orientation: bool = True
    ) -> Union[Image.Image, np.ndarray]:
        """
        Complete image processing pipeline.
        
        Args:
            image_path: Path to image file
            resize: Whether to resize image
            normalize: Whether to normalize to numpy array
            apply_orientation: Whether to apply EXIF orientation
            
        Returns:
            Processed image (PIL Image or numpy array)
        """
        try:
            # Load image
            image = self.load_image(image_path)
            
            # Apply EXIF orientation
            if apply_orientation:
                image = self.apply_exif_orientation(image)
            
            # Resize if needed
            if resize:
                image = self.resize_image(image)
            
            # Normalize if needed
            if normalize:
                return self.normalize_image(image)
            
            return image
            
        except Exception as e:
            logger.error(f"Image processing failed: {e}")
            raise ImageProcessingError(
                f"Failed to process image: {str(e)}",
                {"path": str(image_path), "error": str(e)}
            )
    
    def get_image_info(self, image_path: Union[str, Path]) -> dict:
        """
        Get information about an image.
        
        Args:
            image_path: Path to image file
            
        Returns:
            Dictionary with image information
        """
        image_path = Path(image_path)
        image = self.load_image(image_path)
        
        return {
            "filename": image_path.name,
            "format": image.format,
            "mode": image.mode,
            "size": image.size,
            "width": image.size[0],
            "height": image.size[1],
            "file_size": image_path.stat().st_size,
            "hash": self.get_image_hash(image_path),
        }