File size: 10,130 Bytes
0a4529c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# DEPENDENCIES
import os
import uuid
import psutil
import asyncio
import hashlib
import requests
from typing import Any
from typing import List
from typing import Dict
from typing import Union
from datetime import datetime
from config.settings import get_settings
from config.logging_config import get_logger
from config.logging_config import TimedLogger
from concurrent.futures import ThreadPoolExecutor


# Setup Settings and Logging
settings = get_settings()
logger   = get_logger(__name__)


class IDGenerator:
    """
    Unique ID generation utilities
    """
    @staticmethod
    def generate_document_id() -> str:
        """
        Generate unique document ID
        """
        timestamp   = datetime.now().strftime("%Y%m%d%H%M%S")
        unique_hash = hashlib.md5(str(uuid.uuid4()).encode()).hexdigest()[:8]
        
        return f"doc_{timestamp}_{unique_hash}"
    

    @staticmethod
    def generate_chunk_id(document_id: str, chunk_index: int) -> str:
        """
        Generate unique chunk ID
        """
        return f"chunk_{document_id}_{chunk_index}"
    

    @staticmethod
    def generate_request_id() -> str:
        """
        Generate unique request ID
        """
        return f"req_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
    

    @staticmethod
    def generate_session_id() -> str:
        """
        Generate session ID
        """
        return f"sess_{uuid.uuid4().hex}"


class PerformanceTimer:
    """
    Performance timing utilities
    """
    @staticmethod
    def time_sync(func):
        """
        Decorator to time synchronous functions
        """
        def wrapper(*args, **kwargs):
            start_time = datetime.now()
            result     = func(*args, **kwargs)
            end_time   = datetime.now()
            
            duration   = (end_time - start_time).total_seconds()

            logger.debug(f"Function {func.__name__} took {duration:.3f} seconds")
            
            return result
        
        return wrapper
    

    @staticmethod
    def time_async(func):
        """
        Decorator to time asynchronous functions
        """
        async def wrapper(*args, **kwargs):
            start_time = datetime.now()
            result     = await func(*args, **kwargs)
            end_time   = datetime.now()
            
            duration   = (end_time - start_time).total_seconds()

            logger.debug(f"Async function {func.__name__} took {duration:.3f} seconds")
            
            return result
        
        return wrapper
    

    @staticmethod
    def get_timestamp_ms() -> int:
        """
        Get current timestamp in milliseconds
        """
        return int(datetime.now().timestamp() * 1000)


class BatchProcessor:
    """
    Batch processing utilities
    """
    @staticmethod
    def process_batch_sync(items: List[Any], process_func: callable, batch_size: int = None, **kwargs) -> List[Any]:
        """
        Process items in batches (synchronous)
        """
        if batch_size is None:
            batch_size = settings.EMBEDDING_BATCH_SIZE
        
        results = list()
        
        for i in range(0, len(items), batch_size):
            batch         = items[i:i + batch_size]
            batch_results = [process_func(item, **kwargs) for item in batch]
            
            results.extend(batch_results)
            
            logger.debug(f"Processed batch {i//batch_size + 1}/{(len(items)-1)//batch_size + 1}")
        
        return results
    

    @staticmethod
    async def process_batch_async(items: List[Any], process_func: callable, batch_size: int = None, **kwargs) -> List[Any]:
        """
        Process items in batches (asynchronous)
        """
        if batch_size is None:
            batch_size = settings.ASYNC_BATCH_SIZE
        
        results = list()
        
        for i in range(0, len(items), batch_size):
            batch         = items[i:i + batch_size]
            
            # Create tasks for all items in batch
            tasks         = [process_func(item, **kwargs) for item in batch]
            batch_results = await asyncio.gather(*tasks, return_exceptions = True)
            
            # Handle exceptions
            for j, result in enumerate(batch_results):
                if (isinstance(result, Exception)):
                    logger.error(f"Error processing item {i + j}: {result}")
                    results.append(None)
                
                else:
                    results.append(result)
            
            logger.debug(f"Processed async batch {i//batch_size + 1}/{(len(items)-1)//batch_size + 1}")
        
        return results
    

    @staticmethod
    def process_batch_parallel(items: List[Any], process_func: callable, max_workers: int = None, **kwargs) -> List[Any]:
        """
        Process items in parallel using thread pool
        """
        if max_workers is None:
            max_workers = settings.MAX_WORKERS
        
        with ThreadPoolExecutor(max_workers = max_workers) as executor:
            results = list(executor.map(process_func, items))
        
        return results


class TextUtilities:
    """
    Text processing utilities
    """
    @staticmethod
    def truncate_text(text: str, max_tokens: int, suffix: str = "...") -> str:
        """
        Truncate text to maximum token count (rough estimate)
        """
        # Rough token estimation: ~4 chars per token
        max_chars = max_tokens * 4
        
        if (len(text) <= max_chars):
            return text
        
        # Truncate at word boundary
        truncated  = text[:max_chars - len(suffix)]
        last_space = truncated.rfind(' ')
        
        if (last_space > 0):
            truncated = truncated[:last_space]
        
        return truncated + suffix
    

    @staticmethod
    def count_tokens_accurate(text: str) -> int:
        """
        More accurate token counting (approximation)
        """
        # For English: words * 1.3 + special characters
        words            = text.split()
        word_count       = len(words)
        
        # Count punctuation and special chars
        special_chars    = len(re.findall(r'[^\w\s]', text))
        
        # Estimate tokens (words + punctuation + special formatting)
        estimated_tokens = int(word_count * 1.3 + special_chars * 0.5)
        
        return max(estimated_tokens, 1)
    

    @staticmethod
    def split_into_sections(text: str, max_section_length: int = 1000) -> List[str]:
        """
        Split text into sections at natural boundaries
        """
        if (len(text) <= max_section_length):
            return [text]
        
        sections        = list()
        current_section = ""
        sentences       = re.split(r'[.!?]+', text)
        
        for sentence in sentences:
            sentence = sentence.strip()
            if not sentence:
                continue
            
            # If adding this sentence would exceed limit, start new section
            if ((len(current_section) + len(sentence) > max_section_length) and current_section):
                sections.append(current_section.strip())
                current_section = sentence
            
            else:
                if current_section:
                    current_section += ". " + sentence
                
                else:
                    current_section = sentence
        
        if current_section:
            sections.append(current_section.strip())
        
        return sections


class SystemUtilities:
    """
    System-level utilities
    """
    @staticmethod
    def get_memory_usage() -> Dict[str, Any]:
        """
        Get memory usage information
        """
        try:
            process     = psutil.Process()
            memory_info = process.memory_info()
            
            return {"rss_mb"  : memory_info.rss / 1024 / 1024,  # Resident Set Size
                    "vms_mb"  : memory_info.vms / 1024 / 1024,  # Virtual Memory Size
                    "percent" : process.memory_percent(),
                   }

        except ImportError:
            return {"error": "psutil not available"}
    

    @staticmethod
    def get_system_info() -> Dict[str, Any]:
        """
        Get system information
        """
        try:
            return {"cpu_percent"         : psutil.cpu_percent(interval=1),
                    "memory_total_gb"     : psutil.virtual_memory().total / 1024 / 1024 / 1024,
                    "memory_available_gb" : psutil.virtual_memory().available / 1024 / 1024 / 1024,
                    "memory_used_percent" : psutil.virtual_memory().percent,
                    "disk_usage_percent"  : psutil.disk_usage('/').percent,
                   }

        except ImportError:
            return {"error": "psutil not available"}
    

    @staticmethod
    def is_ollama_available() -> bool:
        """
        Check if Ollama service is available
        """
        try:
            response = requests.get(f"{settings.OLLAMA_BASE_URL}/api/tags", timeout=5)
            return (response.status_code == 200)

        except:
            return False


# Convenience functions
def generate_document_id() -> str:
    """
    Generate a document ID
    """
    return IDGenerator.generate_document_id()


def generate_chunk_id(document_id: str, chunk_index: int) -> str:
    """
    Generate a chunk ID
    """
    return IDGenerator.generate_chunk_id(document_id, chunk_index)


async def process_batch_async(items: List[Any], process_func: callable, **kwargs) -> List[Any]:
    """
    Process batch asynchronously
    """
    return await BatchProcessor.process_batch_async(items, process_func, **kwargs)


def format_duration(seconds: float) -> str:
    """
    Format duration in human-readable format
    """
    if (seconds < 1):
        return f"{seconds * 1000:.0f}ms"

    elif (seconds < 60):
        return f"{seconds:.1f}s"

    elif (seconds < 3600):
        return f"{seconds / 60:.1f}m"

    else:
        return f"{seconds / 3600:.1f}h"