File size: 8,115 Bytes
63f0b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, Dict, List, Optional, Union, Callable
import re
import os
from pathlib import Path

from .logger import get_logger
from .exceptions import ValidationError

logger = get_logger(__name__)

class Validator:
    
    @staticmethod
    def required(value: Any, field_name: str = "field") -> Any:
        if value is None:
            raise ValidationError(field_name, None, "value is required")
        
        if isinstance(value, str) and not value.strip():
            raise ValidationError(field_name, value, "value cannot be empty")
        
        if isinstance(value, (list, dict)) and len(value) == 0:
            raise ValidationError(field_name, str(value), "value cannot be empty")
        
        return value
    
    @staticmethod
    def string(
        value: Any,
        field_name: str = "field",
        min_length: int = None,
        max_length: int = None,
        pattern: str = None
    ) -> str:
        if not isinstance(value, str):
            raise ValidationError(field_name, str(value), "must be a string")
        
        if min_length is not None and len(value) < min_length:
            raise ValidationError(
                field_name, 
                value, 
                f"must be at least {min_length} characters long"
            )
        
        if max_length is not None and len(value) > max_length:
            raise ValidationError(
                field_name, 
                value, 
                f"must be no more than {max_length} characters long"
            )
        
        if pattern is not None and not re.match(pattern, value):
            raise ValidationError(
                field_name, 
                value, 
                f"must match pattern: {pattern}"
            )
        
        return value
    
    @staticmethod
    def number(
        value: Any,
        field_name: str = "field",
        min_value: Union[int, float] = None,
        max_value: Union[int, float] = None,
        integer_only: bool = False
    ) -> Union[int, float]:
        try:
            if integer_only:
                num_value = int(value)
            else:
                num_value = float(value)
        except (ValueError, TypeError):
            raise ValidationError(
                field_name, 
                str(value), 
                f"must be a {'integer' if integer_only else 'number'}"
            )
        
        if min_value is not None and num_value < min_value:
            raise ValidationError(
                field_name, 
                str(value), 
                f"must be at least {min_value}"
            )
        
        if max_value is not None and num_value > max_value:
            raise ValidationError(
                field_name, 
                str(value), 
                f"must be no more than {max_value}"
            )
        
        return num_value
    
    @staticmethod
    def file_path(
        value: Any,
        field_name: str = "field",
        must_exist: bool = True,
        allowed_extensions: List[str] = None
    ) -> Path:
        if not isinstance(value, (str, Path)):
            raise ValidationError(field_name, str(value), "must be a valid file path")
        
        path = Path(value)
        
        if must_exist and not path.exists():
            raise ValidationError(field_name, str(value), "file does not exist")
        
        if allowed_extensions:
            extension = path.suffix.lower()
            if extension not in [ext.lower() for ext in allowed_extensions]:
                raise ValidationError(
                    field_name, 
                    str(value), 
                    f"must have one of these extensions: {', '.join(allowed_extensions)}"
                )
        
        return path
    
    @staticmethod
    def choice(
        value: Any,
        field_name: str = "field",
        choices: List[Any] = None
    ) -> Any:
        if choices is not None and value not in choices:
            raise ValidationError(
                field_name, 
                str(value), 
                f"must be one of: {', '.join(str(c) for c in choices)}"
            )
        
        return value
    
    @staticmethod
    def email(value: Any, field_name: str = "field") -> str:
        email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        
        if not isinstance(value, str):
            raise ValidationError(field_name, str(value), "must be a string")
        
        if not re.match(email_pattern, value):
            raise ValidationError(field_name, value, "must be a valid email address")
        
        return value.lower()
    
    @staticmethod
    def url(value: Any, field_name: str = "field") -> str:
        url_pattern = r'^https?://(?:[-\w.])+(?:\:[0-9]+)?(?:/(?:[\w/_.])*(?:\?(?:[\w&=%.])*)?(?:\#(?:\w)*)?)?$'
        
        if not isinstance(value, str):
            raise ValidationError(field_name, str(value), "must be a string")
        
        if not re.match(url_pattern, value):
            raise ValidationError(field_name, value, "must be a valid URL")
        
        return value

def validate_request_data(schema: Dict[str, Dict[str, Any]]):
    def decorator(func: Callable) -> Callable:
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return decorator

def validate_model_config(config: Dict[str, Any]) -> Dict[str, Any]:
    errors = {}
    
    required_fields = ['model_type', 'sample_rate']
    for field in required_fields:
        try:
            Validator.required(config.get(field), field)
        except ValidationError as e:
            errors[field] = [str(e)]
    
    if 'sample_rate' in config:
        try:
            Validator.number(
                config['sample_rate'], 
                'sample_rate',
                min_value=8000,
                max_value=48000,
                integer_only=True
            )
        except ValidationError as e:
            errors['sample_rate'] = [str(e)]
    
    if 'model_type' in config:
        try:
            Validator.choice(
                config['model_type'],
                'model_type',
                choices=['autoencoder', 'diffusion', 'lm']
            )
        except ValidationError as e:
            errors['model_type'] = [str(e)]
    
    if errors:
        logger.error(f"Model configuration validation failed: {errors}")
        raise ValidationError("model_config", str(config), f"validation failed: {errors}")
    
    return config

def validate_training_config(config: Dict[str, Any]) -> Dict[str, Any]:
    errors = {}
    
    if 'modelName' in config:
        try:
            Validator.string(
                config['modelName'],
                'modelName',
                min_length=1,
                max_length=100
            )
        except ValidationError as e:
            errors['modelName'] = [str(e)]
    
    if 'epochs' in config:
        try:
            Validator.number(
                config['epochs'],
                'epochs',
                min_value=1,
                max_value=1000,
                integer_only=True
            )
        except ValidationError as e:
            errors['epochs'] = [str(e)]
    
    if 'batchSize' in config:
        try:
            Validator.number(
                config['batchSize'],
                'batchSize',
                min_value=1,
                max_value=64,
                integer_only=True
            )
        except ValidationError as e:
            errors['batchSize'] = [str(e)]
    
    if 'learningRate' in config:
        try:
            Validator.number(
                config['learningRate'],
                'learningRate',
                min_value=1e-6,
                max_value=1e-1
            )
        except ValidationError as e:
            errors['learningRate'] = [str(e)]
    
    if errors:
        logger.error(f"Training configuration validation failed: {errors}")
        raise ValidationError("training_config", str(config), f"validation failed: {errors}")
    
    return config