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
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
import time
import json
import csv
import zipfile
from io import BytesIO
from typing import List, Dict, Optional, Callable
from PIL import Image
import traceback

class BatchProcessingManager:
    """
    Manages batch processing of multiple images with progress tracking,
    error handling, and result export functionality.

    Follows the Facade pattern by delegating actual image processing
    to the PixcribePipeline instance.
    """

    def __init__(self, pipeline=None):
        """
        Initialize the Batch Processing Manager.

        Args:
            pipeline: Reference to PixcribePipeline instance for processing images
        """
        self.pipeline = pipeline
        self.results = {}  # Store processing results indexed by image number
        self.timing_data = []  # Track processing time for each image

    def process_batch(
        self,
        images: List[Image.Image],
        platform: str = 'instagram',
        yolo_variant: str = 'l',
        language: str = 'zh',
        progress_callback: Optional[Callable] = None
    ) -> Dict:
        """
        Process a batch of images with progress tracking.

        Args:
            images: List of PIL Image objects to process (max 10)
            platform: Target social media platform
            yolo_variant: YOLO model variant ('m', 'l', 'x')
            language: Caption language ('zh', 'en')
            progress_callback: Optional callback function for progress updates

        Returns:
            Dictionary containing batch processing summary and results

        Raises:
            ValueError: If images list is empty or exceeds 10 images
        """
        # Validate input
        if not images:
            raise ValueError("Images list cannot be empty")

        if len(images) > 10:
            raise ValueError("Maximum 10 images allowed per batch")

        # Initialize results storage
        self.results = {}
        self.timing_data = []
        total_images = len(images)

        # Record batch start time
        batch_start_time = time.time()

        print(f"\n{'='*60}")
        print(f"Starting batch processing: {total_images} images")
        print(f"Platform: {platform} | Variant: {yolo_variant} | Language: {language}")
        print(f"{'='*60}\n")

        # Process each image
        for idx, image in enumerate(images):
            image_start_time = time.time()
            image_index = idx + 1

            try:
                print(f"[{image_index}/{total_images}] Processing image {image_index}...")

                # Call pipeline's process_image method
                result = self.pipeline.process_image(
                    image=image,
                    platform=platform,
                    yolo_variant=yolo_variant,
                    language=language
                )

                # Store successful result
                self.results[image_index] = {
                    'status': 'success',
                    'result': result,
                    'image_index': image_index,
                    'error': None
                }

                print(f"βœ“ Image {image_index} processed successfully")

            except Exception as e:
                # Store error result
                error_trace = traceback.format_exc()
                self.results[image_index] = {
                    'status': 'failed',
                    'result': None,
                    'image_index': image_index,
                    'error': {
                        'type': type(e).__name__,
                        'message': str(e),
                        'traceback': error_trace
                    }
                }

                print(f"βœ— Image {image_index} failed: {str(e)}")

            # Record processing time for this image
            image_elapsed = time.time() - image_start_time
            self.timing_data.append(image_elapsed)

            # Calculate progress information
            completed = image_index
            percent = (completed / total_images) * 100

            # Estimate remaining time based on average processing time
            avg_time = sum(self.timing_data) / len(self.timing_data)
            remaining_images = total_images - completed
            estimated_remaining = avg_time * remaining_images

            # Call progress callback if provided
            if progress_callback:
                progress_info = {
                    'current': completed,
                    'total': total_images,
                    'percent': percent,
                    'estimated_remaining': estimated_remaining,
                    'latest_result': self.results[image_index],
                    'image_index': image_index
                }
                progress_callback(progress_info)

        # Calculate batch summary
        batch_elapsed = time.time() - batch_start_time
        total_processed = len(self.results)
        total_failed = sum(1 for r in self.results.values() if r['status'] == 'failed')
        total_success = total_processed - total_failed

        print(f"\n{'='*60}")
        print(f"Batch processing completed!")
        print(f"Total: {total_processed} | Success: {total_success} | Failed: {total_failed}")
        print(f"Total time: {batch_elapsed:.2f}s | Avg per image: {batch_elapsed/total_processed:.2f}s")
        print(f"{'='*60}\n")

        # Return batch summary
        return {
            'results': self.results,
            'total_processed': total_processed,
            'total_success': total_success,
            'total_failed': total_failed,
            'total_time': batch_elapsed,
            'average_time_per_image': batch_elapsed / total_processed if total_processed > 0 else 0
        }

    def get_result(self, image_index: int) -> Optional[Dict]:
        """
        Get processing result for a specific image.

        Args:
            image_index: Index of the image (1-based)

        Returns:
            Result dictionary or None if index doesn't exist
        """
        return self.results.get(image_index)

    def get_all_results(self) -> Dict:
        """
        Get all processing results.

        Returns:
            Complete results dictionary
        """
        return self.results

    def clear_results(self):
        """Clear all stored results to free memory."""
        self.results = {}
        self.timing_data = []
        print("βœ“ Batch results cleared")

    def export_to_json(self, results: Dict, output_path: str) -> str:
        """
        Export batch results to JSON format.

        Args:
            results: Results dictionary from process_batch
            output_path: Path to save JSON file

        Returns:
            Path to the saved JSON file
        """
        # Prepare export data
        export_data = {
            'batch_summary': {
                'total_processed': results.get('total_processed', 0),
                'total_success': results.get('total_success', 0),
                'total_failed': results.get('total_failed', 0),
                'total_time': results.get('total_time', 0),
                'average_time_per_image': results.get('average_time_per_image', 0)
            },
            'images': []
        }

        # Process each image result
        for img_idx, img_result in results.get('results', {}).items():
            if img_result['status'] == 'success':
                result_data = img_result['result']
                image_export = {
                    'image_index': img_idx,
                    'status': 'success',
                    'captions': result_data.get('captions', []),
                    'detected_objects': [
                        det['class_name'] for det in result_data.get('detections', [])
                    ],
                    'detected_brands': [
                        brand[0] if isinstance(brand, tuple) else brand
                        for brand in result_data.get('brands', [])
                    ],
                    'scene_info': result_data.get('scene', {}),
                    'lighting': result_data.get('lighting', {})
                }
            else:
                image_export = {
                    'image_index': img_idx,
                    'status': 'failed',
                    'error': img_result.get('error', {})
                }

            export_data['images'].append(image_export)

        # Write to JSON file
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(export_data, f, ensure_ascii=False, indent=2)

        print(f"βœ“ Batch results exported to JSON: {output_path}")
        return output_path

    def export_to_csv(self, results: Dict, output_path: str) -> str:
        """
        Export batch results to CSV format.

        Args:
            results: Results dictionary from process_batch
            output_path: Path to save CSV file

        Returns:
            Path to the saved CSV file
        """
        # Define CSV headers
        headers = [
            'image_index',
            'status',
            'caption_professional',
            'caption_creative',
            'caption_authentic',
            'detected_objects',
            'detected_brands',
            'hashtags'
        ]

        # Prepare rows
        rows = []
        for img_idx, img_result in results.get('results', {}).items():
            if img_result['status'] == 'success':
                result_data = img_result['result']
                captions = result_data.get('captions', [])

                # Extract captions by tone
                caption_professional = ''
                caption_creative = ''
                caption_authentic = ''
                all_hashtags = []

                for cap in captions:
                    tone = cap.get('tone', '').lower()
                    caption_text = cap.get('caption', '')
                    hashtags = cap.get('hashtags', [])

                    if 'professional' in tone:
                        caption_professional = caption_text
                    elif 'creative' in tone:
                        caption_creative = caption_text
                    elif 'authentic' in tone or 'casual' in tone:
                        caption_authentic = caption_text

                    all_hashtags.extend(hashtags)

                # Remove duplicates from hashtags
                all_hashtags = list(set(all_hashtags))

                row = {
                    'image_index': img_idx,
                    'status': 'success',
                    'caption_professional': caption_professional,
                    'caption_creative': caption_creative,
                    'caption_authentic': caption_authentic,
                    'detected_objects': ', '.join([
                        det['class_name'] for det in result_data.get('detections', [])
                    ]),
                    'detected_brands': ', '.join([
                        brand[0] if isinstance(brand, tuple) else brand
                        for brand in result_data.get('brands', [])
                    ]),
                    'hashtags': ' '.join([f'#{tag}' for tag in all_hashtags])
                }
            else:
                row = {
                    'image_index': img_idx,
                    'status': 'failed',
                    'caption_professional': '',
                    'caption_creative': '',
                    'caption_authentic': '',
                    'detected_objects': '',
                    'detected_brands': '',
                    'hashtags': ''
                }

            rows.append(row)

        # Write to CSV file
        with open(output_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=headers)
            writer.writeheader()
            writer.writerows(rows)

        print(f"βœ“ Batch results exported to CSV: {output_path}")
        return output_path

    def export_to_zip(self, results: Dict, images: List[Image.Image], output_path: str) -> str:
        """
        Export batch results to ZIP archive with images and text files.

        Args:
            results: Results dictionary from process_batch
            images: List of original PIL Image objects
            output_path: Path to save ZIP file

        Returns:
            Path to the saved ZIP file
        """
        with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for img_idx, img_result in results.get('results', {}).items():
                if img_result['status'] == 'success':
                    # Save original image
                    image_filename = f"image_{img_idx:03d}.jpg"

                    # Convert PIL image to bytes
                    img_buffer = BytesIO()
                    images[img_idx - 1].save(img_buffer, format='JPEG', quality=95)
                    img_buffer.seek(0)

                    zipf.writestr(image_filename, img_buffer.read())

                    # Save caption text file
                    text_filename = f"image_{img_idx:03d}.txt"
                    text_content = self._format_result_as_text(img_result['result'])
                    zipf.writestr(text_filename, text_content)

                    print(f"βœ“ Added to ZIP: {image_filename} and {text_filename}")

        print(f"βœ“ Batch results exported to ZIP: {output_path}")
        return output_path

    def _format_result_as_text(self, result: Dict) -> str:
        """
        Format a single image result as plain text for ZIP export.

        Args:
            result: Single image processing result dictionary

        Returns:
            Formatted text string
        """
        lines = []
        lines.append("=" * 60)
        lines.append("PIXCRIBE - AI GENERATED SOCIAL MEDIA CONTENT")
        lines.append("=" * 60)
        lines.append("")

        # Captions section
        captions = result.get('captions', [])
        for i, cap in enumerate(captions, 1):
            tone = cap.get('tone', 'Unknown').upper()
            caption_text = cap.get('caption', '')
            hashtags = cap.get('hashtags', [])

            lines.append(f"CAPTION {i} - {tone} STYLE")
            lines.append("-" * 60)
            lines.append(caption_text)
            lines.append("")
            lines.append("Hashtags:")
            lines.append(' '.join([f'#{tag}' for tag in hashtags]))
            lines.append("")
            lines.append("")

        # Detected objects section
        detections = result.get('detections', [])
        if detections:
            lines.append("DETECTED OBJECTS")
            lines.append("-" * 60)
            object_names = [det['class_name'] for det in detections]
            lines.append(', '.join(object_names))
            lines.append("")

        # Detected brands section
        brands = result.get('brands', [])
        if brands:
            lines.append("DETECTED BRANDS")
            lines.append("-" * 60)
            brand_names = [
                brand[0] if isinstance(brand, tuple) else brand
                for brand in brands
            ]
            lines.append(', '.join(brand_names))
            lines.append("")

        # Scene information
        scene_info = result.get('scene', {})
        if scene_info:
            lines.append("SCENE ANALYSIS")
            lines.append("-" * 60)

            if 'lighting' in scene_info:
                lighting = scene_info['lighting'].get('top', 'Unknown')
                lines.append(f"Lighting: {lighting}")

            if 'mood' in scene_info:
                mood = scene_info['mood'].get('top', 'Unknown')
                lines.append(f"Mood: {mood}")

            lines.append("")

        lines.append("=" * 60)
        lines.append("Generated by Pixcribe V5 - AI Social Media Caption Generator")
        lines.append("=" * 60)

        return '\n'.join(lines)


print("βœ“ BatchProcessingManager defined")