File size: 15,481 Bytes
f8b306b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
DeepFashion2 Evaluation Module
Provides evaluation capabilities using DeepFashion2 dataset as benchmark
for the Vestiq fashion analysis system.
"""

import torch
import numpy as np
from typing import Dict, List, Tuple, Optional
from sklearn.metrics import accuracy_score, precision_recall_fscore_support, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
import json
from tqdm import tqdm

from deepfashion2_utils import (
    DeepFashion2Config, 
    DeepFashion2Dataset, 
    DeepFashion2CategoryMapper,
    create_deepfashion2_dataloader
)

class DeepFashion2Evaluator:
    """Evaluate fashion models using DeepFashion2 dataset"""
    
    def __init__(self, config: DeepFashion2Config, analyzer=None):
        """
        Initialize evaluator
        
        Args:
            config: DeepFashion2 configuration
            analyzer: HuggingFaceFashionAnalyzer instance
        """
        self.config = config
        self.analyzer = analyzer
        self.category_mapper = DeepFashion2CategoryMapper()
        self.results = {}
    
    def evaluate_detection_accuracy(self, split: str = 'validation', 
                                  max_samples: Optional[int] = None) -> Dict:
        """
        Evaluate fashion object detection accuracy on DeepFashion2
        
        Args:
            split: Dataset split to evaluate on
            max_samples: Maximum number of samples to evaluate (None for all)
            
        Returns:
            Dictionary containing evaluation metrics
        """
        if not self.analyzer:
            raise ValueError("Analyzer not provided")
        
        print(f"Evaluating detection accuracy on {split} split...")
        
        # Load dataset
        dataset = DeepFashion2Dataset(
            root_dir=self.config.dataset_root,
            split=split,
            transform=None,
            load_annotations=True
        )
        
        if max_samples:
            dataset.image_files = dataset.image_files[:max_samples]
        
        # Evaluation metrics
        true_categories = []
        predicted_categories = []
        detection_scores = []
        
        for i in tqdm(range(len(dataset)), desc="Evaluating detection"):
            try:
                item = dataset[i]
                image_path = item['image_path']
                annotations = item['annotations']
                
                # Get ground truth categories
                gt_categories = dataset.get_categories_in_image(annotations)
                gt_yainage_categories = [
                    self.category_mapper.map_to_yainage90(cat) 
                    for cat in gt_categories
                ]
                gt_yainage_categories = list(set(gt_yainage_categories))
                
                if not gt_yainage_categories:
                    continue
                
                # Get model predictions
                with open(image_path, 'rb') as f:
                    image_bytes = f.read()
                
                detection_results = self.analyzer.detect_fashion_objects(
                    self.analyzer.process_image_from_bytes(image_bytes)
                )
                
                if 'detected_items' in detection_results:
                    pred_categories = [
                        item['category'] for item in detection_results['detected_items']
                        if item['confidence'] > 0.5
                    ]
                    pred_categories = list(set(pred_categories))
                    
                    # Calculate detection score (IoU-like for categories)
                    if pred_categories and gt_yainage_categories:
                        intersection = set(pred_categories) & set(gt_yainage_categories)
                        union = set(pred_categories) | set(gt_yainage_categories)
                        score = len(intersection) / len(union) if union else 0
                        detection_scores.append(score)
                    
                    # Store for classification metrics
                    for gt_cat in gt_yainage_categories:
                        true_categories.append(gt_cat)
                        predicted_categories.append(
                            gt_cat if gt_cat in pred_categories else 'none'
                        )
                
            except Exception as e:
                print(f"Error processing image {i}: {e}")
                continue
        
        # Calculate metrics
        metrics = self._calculate_classification_metrics(
            true_categories, predicted_categories
        )
        
        metrics['detection_scores'] = detection_scores
        metrics['mean_detection_score'] = np.mean(detection_scores) if detection_scores else 0
        metrics['num_samples'] = len(dataset)
        
        self.results['detection_accuracy'] = metrics
        return metrics
    
    def evaluate_feature_extraction(self, split: str = 'validation',
                                  max_samples: Optional[int] = None) -> Dict:
        """
        Evaluate feature extraction quality using DeepFashion2
        
        Args:
            split: Dataset split to evaluate on
            max_samples: Maximum number of samples to evaluate
            
        Returns:
            Dictionary containing feature evaluation metrics
        """
        if not self.analyzer:
            raise ValueError("Analyzer not provided")
        
        print(f"Evaluating feature extraction on {split} split...")
        
        dataset = DeepFashion2Dataset(
            root_dir=self.config.dataset_root,
            split=split,
            transform=None,
            load_annotations=True
        )
        
        if max_samples:
            dataset.image_files = dataset.image_files[:max_samples]
        
        features_by_category = {}
        feature_dimensions = []
        
        for i in tqdm(range(len(dataset)), desc="Extracting features"):
            try:
                item = dataset[i]
                image_path = item['image_path']
                annotations = item['annotations']
                
                # Get ground truth categories
                gt_categories = dataset.get_categories_in_image(annotations)
                gt_yainage_categories = [
                    self.category_mapper.map_to_yainage90(cat) 
                    for cat in gt_categories
                ]
                
                if not gt_yainage_categories:
                    continue
                
                # Extract features
                with open(image_path, 'rb') as f:
                    image_bytes = f.read()
                
                feature_results = self.analyzer.extract_fashion_features(
                    self.analyzer.process_image_from_bytes(image_bytes)
                )
                
                if 'feature_vector' in feature_results:
                    features = np.array(feature_results['feature_vector'])
                    feature_dimensions.append(feature_results['feature_dimension'])
                    
                    # Group features by category
                    for category in gt_yainage_categories:
                        if category not in features_by_category:
                            features_by_category[category] = []
                        features_by_category[category].append(features)
                
            except Exception as e:
                print(f"Error processing image {i}: {e}")
                continue
        
        # Calculate feature quality metrics
        metrics = {
            'feature_dimension': np.mean(feature_dimensions) if feature_dimensions else 0,
            'categories_found': list(features_by_category.keys()),
            'samples_per_category': {
                cat: len(feats) for cat, feats in features_by_category.items()
            }
        }
        
        # Calculate intra-category similarity and inter-category distance
        if len(features_by_category) > 1:
            intra_similarities = []
            inter_distances = []
            
            categories = list(features_by_category.keys())
            for i, cat1 in enumerate(categories):
                cat1_features = np.array(features_by_category[cat1])
                
                # Intra-category similarity
                if len(cat1_features) > 1:
                    similarities = []
                    for j in range(len(cat1_features)):
                        for k in range(j+1, len(cat1_features)):
                            sim = np.dot(cat1_features[j], cat1_features[k])
                            similarities.append(sim)
                    intra_similarities.extend(similarities)
                
                # Inter-category distance
                for j, cat2 in enumerate(categories[i+1:], i+1):
                    cat2_features = np.array(features_by_category[cat2])
                    for feat1 in cat1_features:
                        for feat2 in cat2_features:
                            dist = np.linalg.norm(feat1 - feat2)
                            inter_distances.append(dist)
            
            metrics['mean_intra_similarity'] = np.mean(intra_similarities) if intra_similarities else 0
            metrics['mean_inter_distance'] = np.mean(inter_distances) if inter_distances else 0
            metrics['feature_separability'] = (
                metrics['mean_inter_distance'] - metrics['mean_intra_similarity']
            )
        
        self.results['feature_extraction'] = metrics
        return metrics
    
    def _calculate_classification_metrics(self, y_true: List[str], 
                                        y_pred: List[str]) -> Dict:
        """Calculate classification metrics"""
        if not y_true or not y_pred:
            return {}
        
        # Get unique labels
        labels = list(set(y_true + y_pred))
        
        # Calculate metrics
        accuracy = accuracy_score(y_true, y_pred)
        precision, recall, f1, support = precision_recall_fscore_support(
            y_true, y_pred, labels=labels, average='weighted', zero_division=0
        )
        
        # Per-class metrics
        precision_per_class, recall_per_class, f1_per_class, support_per_class = \
            precision_recall_fscore_support(
                y_true, y_pred, labels=labels, average=None, zero_division=0
            )
        
        per_class_metrics = {}
        for i, label in enumerate(labels):
            per_class_metrics[label] = {
                'precision': precision_per_class[i],
                'recall': recall_per_class[i],
                'f1': f1_per_class[i],
                'support': support_per_class[i]
            }
        
        return {
            'accuracy': accuracy,
            'precision': precision,
            'recall': recall,
            'f1': f1,
            'per_class_metrics': per_class_metrics,
            'confusion_matrix': confusion_matrix(y_true, y_pred, labels=labels).tolist(),
            'labels': labels
        }
    
    def generate_evaluation_report(self, output_dir: str = "./evaluation_results") -> str:
        """Generate comprehensive evaluation report"""
        output_path = Path(output_dir)
        output_path.mkdir(exist_ok=True)
        
        report_file = output_path / "deepfashion2_evaluation_report.json"
        
        # Compile all results
        full_report = {
            'config': {
                'dataset_root': self.config.dataset_root,
                'categories': self.config.categories,
                'image_size': self.config.image_size
            },
            'results': self.results,
            'summary': self._generate_summary()
        }
        
        # Save report
        with open(report_file, 'w') as f:
            json.dump(full_report, f, indent=2)
        
        print(f"Evaluation report saved to: {report_file}")
        return str(report_file)
    
    def _generate_summary(self) -> Dict:
        """Generate evaluation summary"""
        summary = {}
        
        if 'detection_accuracy' in self.results:
            det_results = self.results['detection_accuracy']
            summary['detection'] = {
                'accuracy': det_results.get('accuracy', 0),
                'f1_score': det_results.get('f1', 0),
                'mean_detection_score': det_results.get('mean_detection_score', 0)
            }
        
        if 'feature_extraction' in self.results:
            feat_results = self.results['feature_extraction']
            summary['features'] = {
                'feature_dimension': feat_results.get('feature_dimension', 0),
                'categories_evaluated': len(feat_results.get('categories_found', [])),
                'feature_separability': feat_results.get('feature_separability', 0)
            }
        
        return summary
    
    def plot_confusion_matrix(self, output_dir: str = "./evaluation_results"):
        """Plot confusion matrix for detection results"""
        if 'detection_accuracy' not in self.results:
            print("No detection results available for plotting")
            return
        
        results = self.results['detection_accuracy']
        if 'confusion_matrix' not in results:
            return
        
        cm = np.array(results['confusion_matrix'])
        labels = results['labels']
        
        plt.figure(figsize=(10, 8))
        sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', 
                   xticklabels=labels, yticklabels=labels)
        plt.title('Fashion Object Detection Confusion Matrix')
        plt.xlabel('Predicted')
        plt.ylabel('Actual')
        
        output_path = Path(output_dir)
        output_path.mkdir(exist_ok=True)
        plt.savefig(output_path / 'confusion_matrix.png', dpi=300, bbox_inches='tight')
        plt.close()
        
        print(f"Confusion matrix saved to: {output_path / 'confusion_matrix.png'}")

def run_full_evaluation(analyzer, config: Optional[DeepFashion2Config] = None,
                       max_samples: int = 100) -> str:
    """
    Run full evaluation pipeline
    
    Args:
        analyzer: HuggingFaceFashionAnalyzer instance
        config: DeepFashion2 configuration
        max_samples: Maximum samples to evaluate
        
    Returns:
        Path to evaluation report
    """
    if config is None:
        config = DeepFashion2Config()
    
    evaluator = DeepFashion2Evaluator(config, analyzer)
    
    print("Starting DeepFashion2 evaluation...")
    
    # Run detection evaluation
    try:
        evaluator.evaluate_detection_accuracy(max_samples=max_samples)
        print("βœ“ Detection evaluation completed")
    except Exception as e:
        print(f"βœ— Detection evaluation failed: {e}")
    
    # Run feature extraction evaluation
    try:
        evaluator.evaluate_feature_extraction(max_samples=max_samples)
        print("βœ“ Feature extraction evaluation completed")
    except Exception as e:
        print(f"βœ— Feature extraction evaluation failed: {e}")
    
    # Generate report
    report_path = evaluator.generate_evaluation_report()
    
    # Plot confusion matrix
    try:
        evaluator.plot_confusion_matrix()
        print("βœ“ Confusion matrix plotted")
    except Exception as e:
        print(f"βœ— Confusion matrix plotting failed: {e}")
    
    return report_path