File size: 5,396 Bytes
4e4961e
 
 
 
 
 
 
 
 
 
 
 
5009cb8
 
 
 
 
 
 
 
 
 
4e4961e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5009cb8
 
4e4961e
 
 
 
 
 
 
 
 
 
 
 
 
 
5009cb8
4e4961e
 
 
 
 
 
 
5009cb8
4e4961e
 
 
 
 
 
 
 
 
 
5009cb8
4e4961e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5009cb8
 
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
"""Translation service interface.

This module defines the interface for text translation services that convert
text from one language to another. The interface supports multiple translation
providers and models with language detection and quality assessment.

The interface is designed to be:
- Provider-agnostic: Works with any translation implementation
- Language-flexible: Supports automatic language detection
- Quality-aware: Provides confidence scores and alternative translations
- Context-sensitive: Handles domain-specific translation needs
"""

from abc import ABC, abstractmethod
from typing import TYPE_CHECKING

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


class ITranslationService(ABC):
    """Interface for translation services.

    This interface defines the contract for translating text between languages
    using various translation models and providers. Implementations should
    handle language detection, context preservation, and quality optimization.

    Example:
        ```python
        # Use through dependency injection
        translation_service = container.resolve(ITranslationService)

        # Create translation request
        request = TranslationRequest(
            text_content=source_text,
            target_language="zh",
            source_language="en"  # Optional, can be auto-detected
        )

        # Translate text
        result = translation_service.translate(request)

        print(f"Original: {request.text_content.text}")
        print(f"Translated: {result.text}")
        print(f"Confidence: {result.confidence}")
        ```
    """

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

        Converts text content from one language to another while preserving
        meaning, context, and formatting where possible. The method should
        handle language detection, domain adaptation, and quality assessment.

        Implementation considerations:
        - Language detection and validation
        - Context preservation and domain adaptation
        - Handling of special characters and formatting
        - Quality assessment and confidence scoring
        - Caching for repeated translations
        - Fallback mechanisms for unsupported language pairs

        Args:
            request: The translation request containing:
                - text_content: Source text with language information
                - target_language: Target language code (ISO 639-1)
                - source_language: Source language code (optional, can be auto-detected)
                - context: Optional context information for better translation
                - domain: Optional domain specification (technical, medical, etc.)

        Returns:
            TextContent: The translated text containing:
                - text: Translated text content
                - language: Target language code
                - confidence: Translation confidence score (0.0-1.0)
                - metadata: Additional information including:
                  - detected_source_language: Auto-detected source language
                  - alternative_translations: Other possible translations
                  - processing_time: Translation duration
                  - model_used: Translation model identifier

        Raises:
            TranslationFailedException: If translation fails due to:
                - Unsupported language pair
                - Model loading or inference errors
                - Network issues (for cloud-based translation)
                - Text processing errors (encoding, length limits)
            ValueError: If request parameters are invalid:
                - Empty text content
                - Invalid language codes
                - Unsupported translation options

        Example:
            ```python
            # Create source text
            source_text = TextContent(
                text="Hello, how are you today?",
                language="en"
            )

            # Create translation request
            request = TranslationRequest(
                text_content=source_text,
                target_language="zh",
                context="casual_conversation"
            )

            # Perform translation
            try:
                result = service.translate(request)

                print(f"Original ({source_text.language}): {source_text.text}")
                print(f"Translated ({result.language}): {result.text}")

                if result.confidence > 0.9:
                    print("High confidence translation")
                elif result.confidence > 0.7:
                    print("Medium confidence translation")
                else:
                    print("Low confidence translation - review recommended")

                # Check for alternatives
                if hasattr(result, 'metadata') and 'alternatives' in result.metadata:
                    print("Alternative translations:")
                    for alt in result.metadata['alternatives'][:3]:
                        print(f"  - {alt}")

            except TranslationFailedException as e:
                print(f"Translation failed: {e}")
            ```
        """
        pass