File size: 11,123 Bytes
238c51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Upload Service
Handles the core business logic for image uploads and processing
"""
import logging
import io
from typing import Optional, Dict, Any, Tuple
from fastapi import UploadFile
from sqlalchemy.orm import Session

from .. import crud, schemas, storage
from ..services.image_preprocessor import ImagePreprocessor
from ..services.thumbnail_service import ImageProcessingService
from ..services.vlm_service import vlm_manager
from ..utils.image_utils import convert_image_to_dict

logger = logging.getLogger(__name__)

class UploadService:
    """Service for handling image upload operations"""
    
    @staticmethod
    async def process_single_upload(
        file: UploadFile,
        source: Optional[str],
        event_type: str,
        countries: str,
        epsg: str,
        image_type: str,
        title: str,
        model_name: Optional[str],
        # Drone-specific fields
        center_lon: Optional[float] = None,
        center_lat: Optional[float] = None,
        amsl_m: Optional[float] = None,
        agl_m: Optional[float] = None,
        heading_deg: Optional[float] = None,
        yaw_deg: Optional[float] = None,
        pitch_deg: Optional[float] = None,
        roll_deg: Optional[float] = None,
        rtk_fix: Optional[bool] = None,
        std_h_m: Optional[float] = None,
        std_v_m: Optional[float] = None,
        db: Session = None
    ) -> Dict[str, Any]:
        """Process a single image upload"""
        logger.info(f"Processing single upload: {file.filename}")
        
        # Parse and validate input
        countries_list = [c.strip() for c in countries.split(',') if c.strip()] if countries else []
        
        # Set defaults based on image type
        if image_type == "drone_image":
            if not event_type or event_type.strip() == "":
                event_type = "OTHER"
            if not epsg or epsg.strip() == "":
                epsg = "OTHER"
        else:
            if not source or source.strip() == "":
                source = "OTHER"
            if not event_type or event_type.strip() == "":
                event_type = "OTHER"
            if not epsg or epsg.strip() == "":
                epsg = "OTHER"
            
            # Clear drone fields for non-drone images
            center_lon = center_lat = amsl_m = agl_m = None
            heading_deg = yaw_deg = pitch_deg = roll_deg = None
            rtk_fix = std_h_m = std_v_m = None
        
        if not image_type or image_type.strip() == "":
            image_type = "crisis_map"
        
        # Read file content
        content = await file.read()
        
        # Preprocess image
        preprocessing_info = await UploadService._preprocess_image(content, file.filename)
        
        # Upload to storage
        key, sha = await UploadService._upload_to_storage(
            preprocessing_info['processed_content'],
            preprocessing_info['processed_filename'],
            preprocessing_info['mime_type']
        )
        
        # Generate thumbnails and detail versions
        thumbnail_result, detail_result = await UploadService._generate_image_versions(
            preprocessing_info['processed_content'],
            preprocessing_info['processed_filename']
        )
        
        # Create database record
        img = crud.create_image(
            db, source, event_type, key, sha, countries_list, epsg, image_type,
            center_lon, center_lat, amsl_m, agl_m,
            heading_deg, yaw_deg, pitch_deg, roll_deg,
            rtk_fix, std_h_m, std_v_m,
            thumbnail_key=thumbnail_result[0] if thumbnail_result else None,
            detail_key=detail_result[0] if detail_result else None
        )
        
        # Generate caption if requested
        if title or model_name:
            await UploadService._generate_caption(
                img, preprocessing_info['processed_content'], title, model_name, db
            )
        
        # Generate response
        url = storage.get_object_url(key)
        img_dict = convert_image_to_dict(img, url)
        img_dict['preprocessing_info'] = preprocessing_info
        
        logger.info(f"Successfully processed upload: {img.image_id}")
        return {
            'image': schemas.ImageOut(**img_dict),
            'preprocessing_info': preprocessing_info
        }
    
    @staticmethod
    async def process_multi_upload(
        files: list[UploadFile],
        source: Optional[str],
        event_type: str,
        countries: str,
        epsg: str,
        image_type: str,
        title: str,
        model_name: Optional[str],
        # Drone-specific fields
        center_lon: Optional[float] = None,
        center_lat: Optional[float] = None,
        amsl_m: Optional[float] = None,
        agl_m: Optional[float] = None,
        heading_deg: Optional[float] = None,
        yaw_deg: Optional[float] = None,
        pitch_deg: Optional[float] = None,
        roll_deg: Optional[float] = None,
        rtk_fix: Optional[bool] = None,
        std_h_m: Optional[float] = None,
        std_v_m: Optional[float] = None,
        db: Session = None
    ) -> Dict[str, Any]:
        """Process multiple image uploads"""
        logger.info(f"Processing multi upload: {len(files)} files")
        
        results = []
        for file in files:
            try:
                result = await UploadService.process_single_upload(
                    file, source, event_type, countries, epsg, image_type,
                    title, model_name, center_lon, center_lat, amsl_m, agl_m,
                    heading_deg, yaw_deg, pitch_deg, roll_deg,
                    rtk_fix, std_h_m, std_v_m, db
                )
                results.append(result)
            except Exception as e:
                logger.error(f"Failed to process file {file.filename}: {str(e)}")
                results.append({
                    'error': str(e),
                    'filename': file.filename
                })
        
        logger.info(f"Multi upload completed: {len(results)} results")
        return {
            'results': results,
            'total_files': len(files),
            'successful': len([r for r in results if 'error' not in r])
        }
    
    @staticmethod
    async def _preprocess_image(content: bytes, filename: str) -> Dict[str, Any]:
        """Preprocess an image file"""
        logger.debug(f"Preprocessing image: {filename}")
        
        try:
            processed_content, processed_filename, mime_type = ImagePreprocessor.preprocess_image(
                content, 
                filename,
                target_format='PNG',
                quality=95
            )
            
            preprocessing_info = {
                "original_filename": filename,
                "processed_filename": processed_filename,
                "original_mime_type": ImagePreprocessor.detect_mime_type(content, filename),
                "processed_mime_type": mime_type,
                "processed_content": processed_content,
                "was_preprocessed": processed_filename != filename
            }
            
            if processed_filename != filename:
                logger.info(f"Image preprocessed: {filename} -> {processed_filename}")
            
            return preprocessing_info
            
        except Exception as e:
            logger.error(f"Image preprocessing failed: {str(e)}")
            # Fall back to original content
            return {
                "original_filename": filename,
                "processed_filename": filename,
                "original_mime_type": "unknown",
                "processed_mime_type": "image/png",
                "processed_content": content,
                "was_preprocessed": False,
                "error": str(e)
            }
    
    @staticmethod
    async def _upload_to_storage(content: bytes, filename: str, mime_type: str) -> Tuple[str, str]:
        """Upload content to storage and return key and SHA256"""
        logger.debug(f"Uploading to storage: {filename}")
        
        key = storage.upload_fileobj(
            io.BytesIO(content), 
            filename, 
            content_type=mime_type
        )
        
        sha = crud.hash_bytes(content)
        logger.debug(f"Uploaded to key: {key}, SHA: {sha}")
        
        return key, sha
    
    @staticmethod
    async def _generate_image_versions(content: bytes, filename: str) -> Tuple[Optional[Tuple], Optional[Tuple]]:
        """Generate thumbnail and detail versions of the image"""
        logger.debug(f"Generating image versions: {filename}")
        
        try:
            thumbnail_result = ImageProcessingService.create_and_upload_thumbnail(
                content, filename
            )
            
            detail_result = ImageProcessingService.create_and_upload_detail(
                content, filename
            )
            
            if thumbnail_result:
                logger.info(f"Thumbnail generated: {thumbnail_result[0]}")
            if detail_result:
                logger.info(f"Detail version generated: {detail_result[0]}")
            
            return thumbnail_result, detail_result
            
        except Exception as e:
            logger.error(f"Image version generation failed: {str(e)}")
            return None, None
    
    @staticmethod
    async def _generate_caption(img, image_content: bytes, title: str, model_name: Optional[str], db: Session):
        """Generate caption for the uploaded image"""
        if not title and not model_name:
            return
        
        logger.debug(f"Generating caption for image {img.image_id}")
        
        try:
            # Get active prompt for image type
            prompt_obj = crud.get_active_prompt_by_image_type(db, img.image_type)
            if not prompt_obj:
                logger.warning(f"No active prompt found for image type: {img.image_type}")
                return
            
            # Generate caption using VLM service
            result = await vlm_manager.generate_caption(
                image_content=image_content,
                prompt=prompt_obj.label,
                metadata_instructions=prompt_obj.metadata_instructions or "",
                model_name=model_name,
                db_session=db
            )
            
            # Create caption record
            crud.create_caption(
                db=db,
                image_id=img.image_id,
                title=title or result.get("title", ""),
                prompt=prompt_obj.p_code,
                model_code=result.get("model", model_name or "STUB_MODEL"),
                raw_json=result.get("raw_response", {}),
                text=result.get("text", ""),
                metadata=result.get("metadata", {}),
                image_count=1
            )
            
            logger.info(f"Caption generated for image {img.image_id}")
            
        except Exception as e:
            logger.error(f"Caption generation failed: {str(e)}")
            # Continue without caption if generation fails