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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
# """
# Model utility functions for saving, loading, and inspecting models.
# """
# import os
# import json
# from pathlib import Path
# from typing import Dict, Optional, Union

# import tensorflow as tf
# from tensorflow.keras.models import Model, load_model as keras_load_model

# import sys
# sys.path.append(str(Path(__file__).parent.parent.parent))
# from src.config import MODELS_DIR, CUSTOM_CNN_PATH, MOBILENET_PATH, VGG_PATH


# def save_model(
#     model: Model,
#     save_path: Union[str, Path],
#     save_format: str = 'h5',
#     include_optimizer: bool = True,
#     save_metadata: bool = True,
#     metadata: Optional[Dict] = None
# ) -> None:
#     """
#     Save a trained model to disk.
    
#     Args:
#         model: Keras model to save
#         save_path: Path to save the model
#         save_format: Format to save ('h5' or 'tf')
#         include_optimizer: Whether to include optimizer state
#         save_metadata: Whether to save training metadata
#         metadata: Optional metadata dictionary
#     """
#     save_path = Path(save_path)
    
#     # Create directory if needed
#     save_path.parent.mkdir(parents=True, exist_ok=True)
    
#     if save_format == 'h5':
#         model.save(str(save_path), include_optimizer=include_optimizer)
#     else:
#         # SavedModel format
#         model.save(str(save_path.with_suffix('')), save_format='tf')
    
#     # Save metadata if requested
#     if save_metadata and metadata:
#         metadata_path = save_path.with_suffix('.json')
#         with open(metadata_path, 'w') as f:
#             json.dump(metadata, f, indent=2)
    
#     print(f"Model saved to: {save_path}")


# def load_model(
#     model_path: Union[str, Path],
#     custom_objects: Optional[Dict] = None,
#     compile_model: bool = True
# ) -> Model:
#     """
#     Load a saved model from disk.
    
#     Args:
#         model_path: Path to the saved model
#         custom_objects: Optional custom objects for loading
#         compile_model: Whether to compile the model
        
#     Returns:
#         Loaded Keras model
#     """
#     model_path = Path(model_path)
    
#     if not model_path.exists():
#         # Check if it's a SavedModel directory
#         if model_path.with_suffix('').exists():
#             model_path = model_path.with_suffix('')
#         else:
#             raise FileNotFoundError(f"Model not found: {model_path}")
    
#     model = keras_load_model(
#         str(model_path),
#         custom_objects=custom_objects,
#         compile=compile_model
#     )
    
#     print(f"Model loaded from: {model_path}")
#     return model


# def load_model_metadata(model_path: Union[str, Path]) -> Optional[Dict]:
#     """
#     Load metadata for a saved model.
    
#     Args:
#         model_path: Path to the saved model
        
#     Returns:
#         Metadata dictionary or None
#     """
#     metadata_path = Path(model_path).with_suffix('.json')
    
#     if metadata_path.exists():
#         with open(metadata_path, 'r') as f:
#             return json.load(f)
#     return None


# def get_model_summary(model: Model, print_summary: bool = True) -> Dict:
#     """
#     Get a summary of the model architecture.
    
#     Args:
#         model: Keras model
#         print_summary: Whether to print the summary
        
#     Returns:
#         Dictionary with model statistics
#     """
#     if print_summary:
#         model.summary()
    
#     # Calculate parameters
#     trainable = sum([tf.keras.backend.count_params(w) for w in model.trainable_weights])
#     non_trainable = sum([tf.keras.backend.count_params(w) for w in model.non_trainable_weights])
    
#     summary = {
#         "name": model.name,
#         "total_params": trainable + non_trainable,
#         "trainable_params": trainable,
#         "non_trainable_params": non_trainable,
#         "num_layers": len(model.layers),
#         "input_shape": model.input_shape,
#         "output_shape": model.output_shape
#     }
    
#     return summary


# def get_available_models() -> Dict[str, Dict]:
#     """
#     Get information about available pre-trained models.
    
#     Returns:
#         Dictionary with model information
#     """
#     models = {}
    
#     model_paths = {
#         "custom_cnn": CUSTOM_CNN_PATH,
#         "mobilenet": MOBILENET_PATH,
#         "vgg19": VGG_PATH
#     }
    
#     for name, path in model_paths.items():
#         if Path(path).exists():
#             metadata = load_model_metadata(path)
#             models[name] = {
#                 "path": str(path),
#                 "exists": True,
#                 "metadata": metadata
#             }
#         else:
#             models[name] = {
#                 "path": str(path),
#                 "exists": False,
#                 "metadata": None
#             }
    
#     return models


# def compare_models(models: Dict[str, Model]) -> Dict:
#     """
#     Compare multiple models.
    
#     Args:
#         models: Dictionary of model name -> model
        
#     Returns:
#         Comparison dictionary
#     """
#     comparison = {}
    
#     for name, model in models.items():
#         summary = get_model_summary(model, print_summary=False)
#         comparison[name] = {
#             "params": summary["total_params"],
#             "trainable_params": summary["trainable_params"],
#             "layers": summary["num_layers"]
#         }
    
#     return comparison


# def export_to_tflite(
#     model: Model,
#     save_path: Union[str, Path],
#     quantize: bool = False
# ) -> None:
#     """
#     Export model to TensorFlow Lite format.
    
#     Args:
#         model: Keras model to export
#         save_path: Path to save the TFLite model
#         quantize: Whether to apply quantization
#     """
#     converter = tf.lite.TFLiteConverter.from_keras_model(model)
    
#     if quantize:
#         converter.optimizations = [tf.lite.Optimize.DEFAULT]
    
#     tflite_model = converter.convert()
    
#     save_path = Path(save_path)
#     save_path.parent.mkdir(parents=True, exist_ok=True)
    
#     with open(save_path, 'wb') as f:
#         f.write(tflite_model)
    
#     print(f"TFLite model saved to: {save_path}")


# if __name__ == "__main__":
#     print("Available models:")
#     models = get_available_models()
#     for name, info in models.items():
#         status = "✓ Trained" if info["exists"] else "✗ Not trained"
#         print(f"  {name}: {status}")

"""
Model utility functions for saving, loading, and inspecting models.
"""
import os
import json
from pathlib import Path
from typing import Dict, Optional, Union

import tensorflow as tf
from tensorflow.keras.models import Model, load_model as keras_load_model

import sys
sys.path.append(str(Path(__file__).parent.parent.parent))
from src.config import MODELS_DIR, CUSTOM_CNN_PATH, MOBILENET_PATH, VGG_PATH


# ---------------------------------------------------------------------------
# Legacy preprocessing functions
# ---------------------------------------------------------------------------
# Older saved .h5 models used Lambda layers that baked these functions in.
# Current model code uses Rescaling layers instead, but these definitions
# must remain so keras_load_model() can deserialise the old .h5 files.
# ---------------------------------------------------------------------------

def preprocess_mobilenet(x):
    """Legacy MobileNetV2 preprocessor — scales pixels to [-1, 1]."""
    return x / 127.5 - 1.0


def preprocess_vgg(x):
    """Legacy VGG-19 preprocessor — mean-subtracted scaling."""
    return x * 255.0 - 127.5


_LEGACY_CUSTOM_OBJECTS: Dict = {
    "preprocess_mobilenet": preprocess_mobilenet,
    "preprocess_vgg":       preprocess_vgg,
}


def save_model(
    model: Model,
    save_path: Union[str, Path],
    save_format: str = 'h5',
    include_optimizer: bool = True,
    save_metadata: bool = True,
    metadata: Optional[Dict] = None
) -> None:
    """
    Save a trained model to disk.
    
    Args:
        model: Keras model to save
        save_path: Path to save the model
        save_format: Format to save ('h5' or 'tf')
        include_optimizer: Whether to include optimizer state
        save_metadata: Whether to save training metadata
        metadata: Optional metadata dictionary
    """
    save_path = Path(save_path)
    
    # Create directory if needed
    save_path.parent.mkdir(parents=True, exist_ok=True)
    
    if save_format == 'h5':
        model.save(str(save_path), include_optimizer=include_optimizer)
    else:
        # SavedModel format
        model.save(str(save_path.with_suffix('')), save_format='tf')
    
    # Save metadata if requested
    if save_metadata and metadata:
        metadata_path = save_path.with_suffix('.json')
        with open(metadata_path, 'w') as f:
            json.dump(metadata, f, indent=2)
    
    print(f"Model saved to: {save_path}")


def load_model(
    model_path: Union[str, Path],
    custom_objects: Optional[Dict] = None,
    compile_model: bool = True
) -> Model:
    """
    Load a saved model from disk.
    
    Args:
        model_path: Path to the saved model
        custom_objects: Optional custom objects for loading
        compile_model: Whether to compile the model
        
    Returns:
        Loaded Keras model
    """
    model_path = Path(model_path)

    # Always include legacy preprocessing functions so that old .h5 models
    # saved with Lambda layers can be loaded without extra steps.
    merged_objects = dict(_LEGACY_CUSTOM_OBJECTS)
    if custom_objects:
        merged_objects.update(custom_objects)

    if not model_path.exists():
        # Check if it's a SavedModel directory
        if model_path.with_suffix('').exists():
            model_path = model_path.with_suffix('')
        else:
            raise FileNotFoundError(f"Model not found: {model_path}")

    model = keras_load_model(
        str(model_path),
        custom_objects=merged_objects,
        compile=compile_model
    )
    
    print(f"Model loaded from: {model_path}")
    return model


def load_model_metadata(model_path: Union[str, Path]) -> Optional[Dict]:
    """
    Load metadata for a saved model.
    
    Args:
        model_path: Path to the saved model
        
    Returns:
        Metadata dictionary or None
    """
    metadata_path = Path(model_path).with_suffix('.json')
    
    if metadata_path.exists():
        with open(metadata_path, 'r') as f:
            return json.load(f)
    return None


def get_model_summary(model: Model, print_summary: bool = True) -> Dict:
    """
    Get a summary of the model architecture.
    
    Args:
        model: Keras model
        print_summary: Whether to print the summary
        
    Returns:
        Dictionary with model statistics
    """
    if print_summary:
        model.summary()
    
    # Calculate parameters
    trainable = sum([tf.keras.backend.count_params(w) for w in model.trainable_weights])
    non_trainable = sum([tf.keras.backend.count_params(w) for w in model.non_trainable_weights])
    
    summary = {
        "name": model.name,
        "total_params": trainable + non_trainable,
        "trainable_params": trainable,
        "non_trainable_params": non_trainable,
        "num_layers": len(model.layers),
        "input_shape": model.input_shape,
        "output_shape": model.output_shape
    }
    
    return summary


def get_available_models() -> Dict[str, Dict]:
    """
    Get information about available pre-trained models.
    
    Returns:
        Dictionary with model information
    """
    models = {}
    
    model_paths = {
        "custom_cnn": CUSTOM_CNN_PATH,
        "mobilenet": MOBILENET_PATH,
        "vgg19": VGG_PATH
    }
    
    for name, path in model_paths.items():
        if Path(path).exists():
            metadata = load_model_metadata(path)
            models[name] = {
                "path": str(path),
                "exists": True,
                "metadata": metadata
            }
        else:
            models[name] = {
                "path": str(path),
                "exists": False,
                "metadata": None
            }
    
    return models


def compare_models(models: Dict[str, Model]) -> Dict:
    """
    Compare multiple models.
    
    Args:
        models: Dictionary of model name -> model
        
    Returns:
        Comparison dictionary
    """
    comparison = {}
    
    for name, model in models.items():
        summary = get_model_summary(model, print_summary=False)
        comparison[name] = {
            "params": summary["total_params"],
            "trainable_params": summary["trainable_params"],
            "layers": summary["num_layers"]
        }
    
    return comparison


def export_to_tflite(
    model: Model,
    save_path: Union[str, Path],
    quantize: bool = False
) -> None:
    """
    Export model to TensorFlow Lite format.
    
    Args:
        model: Keras model to export
        save_path: Path to save the TFLite model
        quantize: Whether to apply quantization
    """
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    
    if quantize:
        converter.optimizations = [tf.lite.Optimize.DEFAULT]
    
    tflite_model = converter.convert()
    
    save_path = Path(save_path)
    save_path.parent.mkdir(parents=True, exist_ok=True)
    
    with open(save_path, 'wb') as f:
        f.write(tflite_model)
    
    print(f"TFLite model saved to: {save_path}")


if __name__ == "__main__":
    print("Available models:")
    models = get_available_models()
    for name, info in models.items():
        status = "✓ Trained" if info["exists"] else "✗ Not trained"
        print(f"  {name}: {status}")