File size: 12,025 Bytes
e3cb97b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdc056d
e3cb97b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdc056d
e3cb97b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6514731
e3cb97b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
350
351
352
353
354
355
356
"""Base class for translation provider implementations."""

import logging
import re
from abc import ABC, abstractmethod
from typing import List, TYPE_CHECKING

if TYPE_CHECKING:
    from ...domain.models.translation_request import TranslationRequest
    from ...domain.models.text_content import TextContent

from ...domain.interfaces.translation import ITranslationService
from ...domain.exceptions import TranslationFailedException

logger = logging.getLogger(__name__)


class TranslationProviderBase(ITranslationService, ABC):
    """Abstract base class for translation provider implementations."""

    def __init__(self, provider_name: str, supported_languages: dict[str, list[str]] = None):
        """
        Initialize the translation provider.

        Args:
            provider_name: Name of the translation provider
            supported_languages: Dict mapping source languages to supported target languages
        """
        self.provider_name = provider_name
        self.supported_languages = supported_languages or {}
        self.max_chunk_length = 1000  # Default chunk size for text processing

    def translate(self, request: 'TranslationRequest') -> 'TextContent':
        """
        Translate text from source language to target language.

        Args:
            request: The translation request

        Returns:
            TextContent: The translated text

        Raises:
            TranslationFailedException: If translation fails
        """
        try:
            logger.info(f"Starting translation with {self.provider_name} provider")
            logger.info(f"Translating from {request.source_text.language} to {request.target_language}")

            self._validate_request(request)

            # Split text into chunks for processing
            text_chunks = self._chunk_text(request.source_text.text)
            logger.info(f"Split text into {len(text_chunks)} chunks for processing")

            # Translate each chunk
            translated_chunks = []
            for i, chunk in enumerate(text_chunks):
                logger.info(f"Translating chunk {i+1}/{len(text_chunks)}")
                translated_chunk = self._translate_chunk(
                    chunk,
                    request.source_text.language,
                    request.target_language
                )
                translated_chunks.append(translated_chunk)

            # Reassemble translated text
            translated_text = self._reassemble_chunks(translated_chunks)

            # Create TextContent from translation result
            from ...domain.models.text_content import TextContent

            result = TextContent(
                text=translated_text,
                language=request.target_language,
                encoding='utf-8'
            )

            logger.info(f"Translation completed successfully with {self.provider_name}")
            logger.info(f"Original length: {len(request.source_text.text)}, Translated length: {len(translated_text)}")

            return result

        except Exception as e:
            logger.error(f"Translation failed with {self.provider_name}: {str(e)}")
            raise TranslationFailedException(f"Translation failed: {str(e)}") from e

    @abstractmethod
    def _translate_chunk(self, text: str, source_language: str, target_language: str) -> str:
        """
        Translate a single chunk of text using provider-specific implementation.

        Args:
            text: The text chunk to translate
            source_language: Source language code
            target_language: Target language code

        Returns:
            str: The translated text chunk
        """
        pass

    @abstractmethod
    def is_available(self) -> bool:
        """
        Check if the translation provider is available and ready to use.

        Returns:
            bool: True if provider is available, False otherwise
        """
        pass

    @abstractmethod
    def get_supported_languages(self) -> dict[str, list[str]]:
        """
        Get supported language pairs for this provider.

        Returns:
            dict: Mapping of source languages to supported target languages
        """
        pass

    def _chunk_text(self, text: str) -> List[str]:
        """
        Split text into chunks for translation processing.

        Args:
            text: The text to chunk

        Returns:
            List[str]: List of text chunks
        """
        if len(text) <= self.max_chunk_length:
            return [text]

        chunks = []
        current_chunk = ""

        # Split by sentences first to maintain context
        sentences = self._split_into_sentences(text)

        for sentence in sentences:
            # If adding this sentence would exceed chunk limit
            if len(current_chunk) + len(sentence) > self.max_chunk_length:
                if current_chunk:
                    chunks.append(current_chunk.strip())
                    current_chunk = ""

                # If single sentence is too long, split by words
                if len(sentence) > self.max_chunk_length:
                    word_chunks = self._split_long_sentence(sentence)
                    chunks.extend(word_chunks[:-1])  # Add all but last chunk
                    current_chunk = word_chunks[-1]  # Start new chunk with last piece
                else:
                    current_chunk = sentence
            else:
                current_chunk += " " + sentence if current_chunk else sentence

        # Add remaining chunk
        if current_chunk.strip():
            chunks.append(current_chunk.strip())

        logger.info(f"Text chunked into {len(chunks)} pieces")
        return chunks

    def _split_into_sentences(self, text: str) -> List[str]:
        """
        Split text into sentences using basic punctuation rules.

        Args:
            text: The text to split

        Returns:
            List[str]: List of sentences
        """
        # Simple sentence splitting using regex
        # This handles basic cases - more sophisticated NLP libraries could be used
        sentence_endings = r'[.!?]+\s+'
        sentences = re.split(sentence_endings, text)

        # Filter out empty sentences and strip whitespace
        sentences = [s.strip() for s in sentences if s.strip()]

        return sentences

    def _split_long_sentence(self, sentence: str) -> List[str]:
        """
        Split a long sentence into smaller chunks by words.

        Args:
            sentence: The sentence to split

        Returns:
            List[str]: List of word chunks
        """
        words = sentence.split()
        chunks = []
        current_chunk = ""

        for word in words:
            if len(current_chunk) + len(word) + 1 > self.max_chunk_length:
                if current_chunk:
                    chunks.append(current_chunk.strip())
                    current_chunk = word
                else:
                    # Single word is too long, just add it
                    chunks.append(word)
            else:
                current_chunk += " " + word if current_chunk else word

        if current_chunk.strip():
            chunks.append(current_chunk.strip())

        return chunks

    def _reassemble_chunks(self, chunks: List[str]) -> str:
        """
        Reassemble translated chunks into a single text.

        Args:
            chunks: List of translated text chunks

        Returns:
            str: Reassembled text
        """
        # Simple reassembly with space separation
        # More sophisticated approaches could preserve original formatting
        return " ".join(chunk.strip() for chunk in chunks if chunk.strip())

    def _validate_request(self, request: 'TranslationRequest') -> None:
        """
        Validate the translation request.

        Args:
            request: The translation request to validate

        Raises:
            TranslationFailedException: If request is invalid
        """
        if not request.source_text.text.strip():
            raise TranslationFailedException("Source text cannot be empty")

        if request.source_text.language == request.target_language:
            raise TranslationFailedException("Source and target languages cannot be the same")

        # Check if language pair is supported
        if self.supported_languages:
            source_lang = request.source_text.language
            target_lang = request.target_language

            if source_lang not in self.supported_languages:
                raise TranslationFailedException(
                    f"Source language {source_lang} not supported by {self.provider_name}. "
                    f"Supported source languages: {list(self.supported_languages.keys())}"
                )

            if target_lang not in self.supported_languages[source_lang]:
                raise TranslationFailedException(
                    f"Translation from {source_lang} to {target_lang} not supported by {self.provider_name}. "
                    f"Supported target languages for {source_lang}: {self.supported_languages[source_lang]}"
                )

    def _preprocess_text(self, text: str) -> str:
        """
        Preprocess text before translation.

        Args:
            text: The text to preprocess

        Returns:
            str: Preprocessed text
        """
        # Basic text preprocessing
        # Remove excessive whitespace
        text = re.sub(r'\s+', ' ', text)

        # Strip leading/trailing whitespace
        text = text.strip()

        return text

    def _postprocess_text(self, text: str) -> str:
        """
        Postprocess text after translation.

        Args:
            text: The text to postprocess

        Returns:
            str: Postprocessed text
        """
        # Basic text postprocessing
        # Remove excessive whitespace
        text = re.sub(r'\s+', ' ', text)

        # Strip leading/trailing whitespace
        text = text.strip()

        # Fix common spacing issues around punctuation
        text = re.sub(r'\s+([.!?,:;])', r'\1', text)
        text = re.sub(r'([.!?])\s*([A-Z])', r'\1 \2', text)

        return text

    def _handle_provider_error(self, error: Exception, context: str = "") -> None:
        """
        Handle provider-specific errors and convert to domain exceptions.

        Args:
            error: The original error
            context: Additional context about when the error occurred
        """
        error_msg = f"{self.provider_name} error"
        if context:
            error_msg += f" during {context}"
        error_msg += f": {str(error)}"

        logger.error(error_msg, exception=error)
        raise TranslationFailedException(error_msg) from error

    def set_chunk_size(self, chunk_size: int) -> None:
        """
        Set the maximum chunk size for text processing.

        Args:
            chunk_size: Maximum characters per chunk
        """
        if chunk_size <= 0:
            raise ValueError("Chunk size must be positive")

        self.max_chunk_length = chunk_size
        logger.info(f"Chunk size set to {chunk_size} characters")

    def get_translation_stats(self, request: 'TranslationRequest') -> dict:
        """
        Get statistics about a translation request.

        Args:
            request: The translation request

        Returns:
            dict: Translation statistics
        """
        text = request.source_text.text
        chunks = self._chunk_text(text)

        return {
            'provider': self.provider_name,
            'source_language': request.source_text.language,
            'target_language': request.target_language,
            'text_length': len(text),
            'word_count': len(text.split()),
            'chunk_count': len(chunks),
            'max_chunk_length': max(len(chunk) for chunk in chunks) if chunks else 0,
            'avg_chunk_length': sum(len(chunk) for chunk in chunks) / len(chunks) if chunks else 0
        }