File size: 1,922 Bytes
dd7049b
fae2fcb
cbb18dd
dd7049b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724e453
 
 
 
 
 
 
 
 
 
 
fae2fcb
dd7049b
 
 
 
 
fae2fcb
dd7049b
 
 
 
 
 
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
from smolagents import Tool

from typing import Optional


class TranslateTool(Tool):
    name = "google_translate"
    description = """
    Translates text from one language to another using the Google Translate API.
    Supports a wide range of languages using standard language codes (e.g., 'en' for English, 'fr' for French).
    If source_language is not specified, it will be auto-detected. If target_language is not specified, it defaults to English ('en').
    """
    inputs = {
        "text": {
            "type": "string",
            "description": "The text to translate."
        },
        "source_language": {
            "type": "string",
            "description": "The source language code (e.g., 'en' for English, 'fr' for French).",
        },
        "target_language": {
            "type": "string",
            "description": "The target language code (e.g., 'es' for Spanish, 'de' for German).",
        }
    }
    output_type = "string"

    async def translate_text(text: str, src: str, dest: str):
        """
        Translates text from one language to another using the Google Translate API.

        Args:
            text (str): The text to translate.
            src (str): The source language code.
            dest (str): The target language code.

        Returns:
            str: The translated text.
        """
        from googletrans import Translator
        async with Translator() as translator:
            res = await translator.translate(text, src, dest)
            return res

    def forward(self, text: str,  source_language: str, target_language: str):
        import asyncio
        try:
            translator = Translator()
            translation = asyncio.run(translator.translate(text, src=source_language, dest=target_language))
            return translation.text
        except Exception as e:
            return f"Error: Unable to translate due to {e}"