File size: 8,494 Bytes
e275025
 
 
 
 
 
 
 
 
 
 
b216c95
 
 
e275025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b216c95
 
e275025
b216c95
e275025
 
 
 
 
b216c95
e275025
 
 
b216c95
e275025
 
 
b216c95
e275025
 
 
 
 
 
b216c95
e275025
 
b216c95
 
e275025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b216c95
 
e275025
b216c95
e275025
 
 
b216c95
e275025
 
 
 
 
 
 
b216c95
e275025
 
 
 
 
 
b216c95
e275025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b216c95
 
e275025
b216c95
e275025
 
 
 
 
b216c95
e275025
 
 
 
 
 
 
 
b216c95
e275025
 
 
 
 
 
b216c95
e275025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b216c95
 
e275025
b216c95
e275025
 
 
 
 
 
 
b216c95
e275025
b216c95
 
e275025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b216c95
 
e275025
b216c95
e275025
 
 
 
 
b216c95
e275025
 
 
 
 
 
b216c95
e275025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b216c95
 
e275025
b216c95
e275025
 
 
 
 
 
b216c95
e275025
 
 
 
 
 
b216c95
 
e275025
 
 
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
"""
Data validation utilities for Medical Transcriber application.

Provides validation functions for audio files, text, patient data, etc.
"""

from pathlib import Path
from typing import Tuple, Optional

from .constants import AudioFormats, ValidationRules
from .exceptions import ValidationException, AudioFileException
from .logger import get_logger

logger = get_logger(__name__)


class Validator:
    """Centralized validation utility."""
    
    @staticmethod
    def validate_audio_file(file_path: str) -> Path:
        """
        Validate audio file existence and format.
        
        Args:
            file_path: Path to audio file
            
        Returns:
            Validated Path object
            
        Raises:
            AudioFileException: If file doesn't exist or invalid format
            ValidationException: If file path is invalid
        """
        logger.debug(f"Validating audio file: {file_path}")
        
        if not file_path:
            logger.error("Audio file path is required")
            raise ValidationException("audio_file", "", "Audio file path is required")
        
        audio_path = Path(file_path)
        
        if not audio_path.exists():
            logger.error(f"Audio file not found: {audio_path}")
            raise AudioFileException(str(audio_path), "File does not exist")
        
        if not audio_path.is_file():
            logger.error(f"Path is not a file: {audio_path}")
            raise AudioFileException(str(audio_path), "Path is not a file")
        
        if audio_path.suffix.lower() not in AudioFormats.SUPPORTED_EXTENSIONS:
            logger.error(f"Unsupported audio format: {audio_path.suffix}")
            raise AudioFileException(
                str(audio_path),
                f"Unsupported format. Supported: {', '.join(AudioFormats.SUPPORTED_EXTENSIONS)}"
            )
        
        if audio_path.stat().st_size == 0:
            logger.error(f"Audio file is empty: {audio_path}")
            raise AudioFileException(str(audio_path), "File is empty")
        
        logger.info(f"✓ Audio file validated: {audio_path} ({audio_path.stat().st_size} bytes)")
        
        return audio_path
    
    @staticmethod
    def validate_text(text: str, field_name: str = "text") -> str:
        """
        Validate text content.
        
        Args:
            text: Text to validate
            field_name: Name of the field for error messages
            
        Returns:
            Validated text
            
        Raises:
            ValidationException: If text is invalid
        """
        logger.debug(f"Validating text field '{field_name}': {len(text)} chars")
        
        if not text:
            logger.error(f"Text field '{field_name}' cannot be empty")
            raise ValidationException(field_name, "", "Text cannot be empty")
        
        if len(text) < ValidationRules.MIN_TEXT_LENGTH:
            logger.error(f"Text field '{field_name}' is too short ({len(text)} < {ValidationRules.MIN_TEXT_LENGTH})")
            raise ValidationException(
                field_name,
                text,
                f"Text must be at least {ValidationRules.MIN_TEXT_LENGTH} characters"
            )
        
        if len(text) > ValidationRules.MAX_TEXT_LENGTH:
            logger.error(f"Text field '{field_name}' is too long ({len(text)} > {ValidationRules.MAX_TEXT_LENGTH})")
            raise ValidationException(
                field_name,
                text[:50],
                f"Text exceeds maximum length of {ValidationRules.MAX_TEXT_LENGTH} characters"
            )
        
        logger.info(f"✓ Text field '{field_name}' validated: {len(text.strip())} chars")
        return text.strip()
    
    @staticmethod
    def validate_patient_name(name: Optional[str]) -> Optional[str]:
        """
        Validate patient name.
        
        Args:
            name: Patient name
            
        Returns:
            Validated name or None
            
        Raises:
            ValidationException: If name format is invalid
        """
        logger.debug(f"Validating patient name: {name}")
        
        if not name:
            logger.debug("Patient name is optional, skipping validation")
            return None
        
        name = name.strip()
        
        if len(name) < 3:
            logger.error(f"Patient name too short: '{name}' ({len(name)} < 3)")
            raise ValidationException(
                "patient_name",
                name,
                "Patient name must be at least 3 characters"
            )
        
        # Check for only letters, spaces, and hyphens
        if not all(c.isalpha() or c.isspace() or c == '-' for c in name):
            logger.error(f"Patient name contains invalid characters: '{name}'")
            raise ValidationException(
                "patient_name",
                name,
                "Patient name can only contain letters, spaces, and hyphens"
            )
        
        logger.info(f"✓ Patient name validated: '{name}'")
        return name
    
    @staticmethod
    def validate_date(date_str: Optional[str], date_format: str = "%d.%m.%Y") -> Optional[str]:
        """
        Validate date format.
        
        Args:
            date_str: Date string to validate
            date_format: Expected date format
            
        Returns:
            Validated date string or None
            
        Raises:
            ValidationException: If date format is invalid
        """
        logger.debug(f"Validating date: '{date_str}' (format: {date_format})")
        
        if not date_str:
            logger.debug("Date is optional, skipping validation")
            return None
        
        date_str = date_str.strip()
        
        try:
            from datetime import datetime
            datetime.strptime(date_str, date_format)
            logger.info(f"✓ Date validated: '{date_str}'")
            return date_str
        except ValueError as e:
            logger.error(f"Invalid date format: '{date_str}' (expected: {date_format})")
            raise ValidationException(
                "date",
                date_str,
                f"Invalid date format. Expected: {date_format}"
            )
    
    @staticmethod
    def validate_api_key(api_key: Optional[str]) -> Optional[str]:
        """
        Validate API key format.
        
        Args:
            api_key: API key string
            
        Returns:
            Validated API key or None
            
        Raises:
            ValidationException: If API key is invalid
        """
        logger.debug("Validating API key (hidden for security)")
        
        if not api_key:
            logger.debug("API key is optional, skipping validation")
            return None
        
        api_key = api_key.strip()
        
        if len(api_key) < 10:
            logger.error("API key seems too short to be valid")
            raise ValidationException(
                "api_key",
                "***",
                "API key seems too short to be valid"
            )
        
        logger.info(f"✓ API key validated ({len(api_key)} chars)")
        return api_key
    
    @staticmethod
    def validate_file_path(path_str: str, must_exist: bool = False) -> Path:
        """
        Validate file or directory path.
        
        Args:
            path_str: Path string
            must_exist: Whether path must exist
            
        Returns:
            Validated Path object
            
        Raises:
            ValidationException: If path is invalid
        """
        logger.debug(f"Validating file path: {path_str} (must_exist={must_exist})")
        
        if not path_str:
            logger.error("Path cannot be empty")
            raise ValidationException("path", "", "Path cannot be empty")
        
        try:
            path = Path(path_str).resolve()
            
            if must_exist and not path.exists():
                logger.error(f"Path does not exist: {path}")
                raise ValidationException(
                    "path",
                    str(path),
                    "Path does not exist"
                )
            
            logger.info(f"✓ File path validated: {path}")
            
            return path
        except (ValueError, OSError) as e:
            raise ValidationException("path", path_str, f"Invalid path: {str(e)}")