File size: 8,816 Bytes
45a250f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8205af3
45a250f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
BackgroundFX Pro Models Module.
Comprehensive model management, optimization, and deployment.
"""

from .registry import (
    ModelRegistry,
    ModelInfo,
    ModelStatus,
    ModelTask,
    ModelFramework
)

from .downloader import (
    ModelDownloader,
    DownloadStatus,
    DownloadProgress
)

from .loaders.model_loader import (
    ModelLoader,
    LoadedModel
)

from .optimizer import (
    ModelOptimizer,
    OptimizationResult
)

__all__ = [
    # Registry
    'ModelRegistry',
    'ModelInfo',
    'ModelStatus',
    'ModelTask',
    'ModelFramework',
    
    # Downloader
    'ModelDownloader',
    'DownloadStatus',
    'DownloadProgress',
    
    # Loader
    'ModelLoader',
    'LoadedModel',
    
    # Optimizer
    'ModelOptimizer',
    'OptimizationResult',
    
    # High-level functions
    'create_model_manager',
    'download_all_models',
    'optimize_for_deployment',
    'benchmark_models'
]

# Version
__version__ = '1.0.0'


class ModelManager:
    """
    High-level model management interface.
    Combines registry, downloading, loading, and optimization.
    """
    
    def __init__(self, models_dir: str = None, device: str = 'auto'):
        """
        Initialize model manager.
        
        Args:
            models_dir: Directory for model storage
            device: Device for model loading
        """
        from pathlib import Path
        
        self.models_dir = Path(models_dir) if models_dir else Path.home() / ".backgroundfx" / "models"
        self.device = device
        
        # Initialize components
        self.registry = ModelRegistry(self.models_dir)
        self.downloader = ModelDownloader(self.registry)
        self.loader = ModelLoader(self.registry, device=device)
        self.optimizer = ModelOptimizer(self.loader)
    
    def setup(self, task: str = None, download: bool = True) -> bool:
        """
        Setup models for a specific task.
        
        Args:
            task: Task type (segmentation, matting, etc.)
            download: Download missing models
            
        Returns:
            True if setup successful
        """
        if download:
            return self.downloader.download_required_models(task)
        return True
    
    def get_model(self, model_id: str = None, task: str = None) -> LoadedModel:
        """
        Get a loaded model by ID or task.
        
        Args:
            model_id: Specific model ID
            task: Task type to find best model
            
        Returns:
            Loaded model
        """
        if model_id:
            return self.loader.load_model(model_id)
        elif task:
            from .registry import ModelTask
            task_enum = ModelTask(task)
            best_model = self.registry.get_best_model(task_enum)
            if best_model:
                return self.loader.load_model(best_model.model_id)
        return None
    
    def predict(self, input_data, model_id: str = None, task: str = None, **kwargs):
        """
        Run prediction with a model.
        
        Args:
            input_data: Input data
            model_id: Model ID
            task: Task type
            **kwargs: Additional arguments
            
        Returns:
            Prediction result
        """
        if not model_id and task:
            from .registry import ModelTask
            task_enum = ModelTask(task)
            best_model = self.registry.get_best_model(task_enum)
            if best_model:
                model_id = best_model.model_id
        
        if model_id:
            return self.loader.predict(model_id, input_data, **kwargs)
        return None
    
    def optimize(self, model_id: str, optimization_type: str = 'quantization', **kwargs):
        """
        Optimize a model.
        
        Args:
            model_id: Model to optimize
            optimization_type: Type of optimization
            **kwargs: Optimization parameters
            
        Returns:
            Optimization result
        """
        return self.optimizer.optimize_model(model_id, optimization_type, **kwargs)
    
    def benchmark(self, task: str = None) -> dict:
        """
        Benchmark available models.
        
        Args:
            task: Optional task filter
            
        Returns:
            Benchmark results
        """
        results = {}
        
        models = self.registry.list_models()
        if task:
            from .registry import ModelTask
            task_enum = ModelTask(task)
            models = [m for m in models if m.task == task_enum]
        
        for model_info in models:
            if model_info.status == ModelStatus.AVAILABLE:
                loaded = self.loader.load_model(model_info.model_id)
                if loaded:
                    results[model_info.model_id] = {
                        'name': model_info.name,
                        'framework': model_info.framework.value,
                        'size_mb': model_info.file_size / (1024 * 1024),
                        'speed_fps': model_info.speed_fps,
                        'accuracy': model_info.accuracy,
                        'memory_mb': model_info.memory_mb,
                        'load_time': loaded.load_time
                    }
        
        return results
    
    def cleanup(self, days: int = 30):
        """
        Clean up unused models.
        
        Args:
            days: Days threshold for unused models
            
        Returns:
            List of removed models
        """
        return self.registry.cleanup_unused_models(days)
    
    def get_stats(self) -> dict:
        """Get model management statistics."""
        return {
            'registry': self.registry.get_statistics(),
            'loader': self.loader.get_memory_usage(),
            'downloads': {
                model_id: progress.progress
                for model_id, progress in self.downloader.get_all_progress().items()
            }
        }


# Convenience functions

def create_model_manager(models_dir: str = None, device: str = 'auto') -> ModelManager:
    """
    Create a model manager instance.
    
    Args:
        models_dir: Directory for models
        device: Device for loading
        
    Returns:
        Model manager
    """
    return ModelManager(models_dir, device)


def download_all_models(manager: ModelManager = None, force: bool = False) -> bool:
    """
    Download all available models.
    
    Args:
        manager: Model manager instance
        force: Force re-download
        
    Returns:
        True if all downloads successful
    """
    if not manager:
        manager = create_model_manager()
    
    models = manager.registry.list_models()
    model_ids = [m.model_id for m in models]
    
    futures = manager.downloader.download_models_async(model_ids, force=force)
    
    success = True
    for model_id, future in futures.items():
        try:
            if not future.result():
                success = False
        except:
            success = False
    
    return success


def optimize_for_deployment(manager: ModelManager = None,
                           target: str = 'edge',
                           models: list = None) -> dict:
    """
    Optimize models for deployment.
    
    Args:
        manager: Model manager
        target: Deployment target (edge, cloud, mobile)
        models: Specific models to optimize
        
    Returns:
        Optimization results
    """
    if not manager:
        manager = create_model_manager()
    
    results = {}
    
    # Determine optimization strategy
    if target == 'edge':
        optimization = 'quantization'
        kwargs = {'quantization_type': 'dynamic'}
    elif target == 'mobile':
        optimization = 'coreml' if manager.device == 'mps' else 'tflite'
        kwargs = {}
    elif target == 'cloud':
        optimization = 'tensorrt' if manager.device == 'cuda' else 'onnx'
        kwargs = {'fp16': True}
    else:
        optimization = 'onnx'
        kwargs = {}
    
    # Get models to optimize
    if not models:
        available = manager.registry.list_models(status=ModelStatus.AVAILABLE)
        models = [m.model_id for m in available]
    
    # Optimize each model
    for model_id in models:
        result = manager.optimize(model_id, optimization, **kwargs)
        if result:
            results[model_id] = result
    
    return results


def benchmark_models(manager: ModelManager = None, task: str = None) -> dict:
    """
    Benchmark model performance.
    
    Args:
        manager: Model manager
        task: Optional task filter
        
    Returns:
        Benchmark results
    """
    if not manager:
        manager = create_model_manager()
    
    return manager.benchmark(task)