GoogleCloudTranslate

A Google API cloud based translation service.

Utilities · Google Cloud Translate

Details

IDGoogleCloudTranslate
ProviderGoogle
CategoryUtilities
From Version5.0.0
Docker Imagedemisto/google-cloud-translate:1.0.0.9843526
Supported ModulesAgentix XSIAM

README

A Google API cloud based translation service. This integration was integrated and tested with version 2.0.0 of the Python Client of Google Cloud Translate API.

Use Cases

  • Translate text from spam emails
  • Translate strings found in malware analysis

Detailed Description

In order to use this integration you need the following:

  1. Select or create a Cloud Platform project on GCP
  2. Enable billing for the project
  3. Enable the Google Cloud Translate API
  4. Create a Service Account with access to Google Translate API
  5. Use the Service Account Private Key in JSON format and the GCP project ID to configure a new instance of Google Cloud Translate integration in Cortex XSOAR

Create a Service Account

  1. Go to: https://console.developers.google.com
  2. Select your project
  3. From the side-menu go to IAM & admin > Service accounts > CREATE SERVICE ACCOUNT
  4. Type an account name and description and click CREATE
  5. From the drop down list Select a role select Cloud Translation API User
  6. Click CONTINUE and then click CREATE KEY
  7. Select JSON and click CREATE. The .json file downloads.

Configure GoogleCloudTranslate on Cortex XSOAR

  1. Navigate to Settings > Integrations  > Servers & Services.
  2. Search for GoogleCloudTranslate.
  3. Click Add instance to create and configure a new integration instance.
    • Name: a textual name for the integration instance.
    • Service Account Private Key file contents (JSON)
    • Project in Google Cloud Translate
    • Trust any certificate (not secure)
    • Use system proxy settings
  4. Click Test to validate the new instance.

Commands

You can execute these commands from the Cortex XSOAR CLI, as part of an automation, or in a playbook. After you successfully execute a command, a DBot message appears in the War Room with the command details.

  1. Returns the list of supported two-letter ISO language codes: gct-supported-languages
  2. Returns the translated text: gct-translate-text

1. gct-supported-languages


Returns the list of supported two-letter ISO language codes.

Base Command

gct-supported-languages

Input

There are no input arguments for this command.

 

Context Output
Path Type Description
GoogleCloudTranslate.SupportedLanguages Unknown The list of supported two-letter ISO language codes.

 

Command Example

!gct-supported-languages

Context Example
{
    "GoogleCloudTranslate": {
        "SupportedLanguages": [
            {
                "language_code": "af",
                "support_source": true,
                "support_target": true
            },
            {
                "language_code": "am",
                "support_source": true,
                "support_target": true
            },
            {
                "language_code": "ar",
                "support_source": true,
                "support_target": true
            },
            ...
        ]
    }
}
Human Readable Output

Languages: af, am, ar, az, be, bg, bn, bs, ca, ceb, co, cs, cy, da, de, el, en, eo, es, et, eu, fa, fi, fr, fy, ga, gd, gl, gu, ha, haw, hi, hmn, hr, ht, hu, hy, id, ig, is, it, iw, ja, jw, ka, kk, km, kn, ko, ku, ky, la, lb, lo, lt, lv, mg, mi, mk, ml, mn, mr, ms, mt, my, ne, nl, no, ny, pa, pl, ps, pt, ro, ru, sd, si, sk, sl, sm, sn, so, sq, sr, st, su, sv, sw, ta, te, tg, th, tl, tr, uk, ur, uz, vi, xh, yi, yo, zh-CN, zh-TW, zu

2. gct-translate-text


Returns the translated text.

Base Command

gct-translate-text text="hello world" target="hr"

Input
Argument Name Description Required
text The text to translate. Required
target The two-letter ISO language code of the target language. Default is "en" (English). Optional
source The two-letter ISO language code of the source language. Default is "autodetect". Optional

 

Context Output
Path Type Description
GoogleCloudTranslate.TranslateText.ID String The ID of the request.
GoogleCloudTranslate.TranslateText.detected_language_code String The detected two-letter ISO language code of the source language. Null, if no source argument is defined.
GoogleCloudTranslate.TranslateText.source_language_code String The source language as specified in the source argument. Null, if no source argument is defined.
GoogleCloudTranslate.TranslateText.target_language_code String The two letter ISO language code to which the text was translated.
GoogleCloudTranslate.TranslateText.text String The source (original) text that was translated.
GoogleCloudTranslate.TranslateText.translated_text String The translated text.

 

Command Example

!gct-translate-text text="ciao" target="iw"

Context Example
{
    "GoogleCloudTranslate.TranslateText": {
        "ID": <ID>,
        "detected_language_code": "it",
        "source_language_code": null,
        "target_language_code": "iw",
        "text": "ciao",
        "translated_text": "\u05e9\u05dc\u05d5\u05dd"
    }
}
Human Readable Output

Translation: שלום
Source Language Detected: it

</p>

Additional Information

Known Limitations

The following features are not supported yet:

  • AutoML models
  • Glossaries
  • Labels
  • Batch requests
  • Multple target language codes </ul>

    Troubleshooting

Configuration parameters

  • service_account_json — Service Account Private Key file contents (JSON)
  • project_creds — Project in Google Cloud Translate
  • project — Project in Google Cloud Translate
  • proxy — Use system proxy settings
  • insecure — Trust any certificate (not secure)

Commands (2)

  • gct-supported-languages

    Returns the list of supported two-letter ISO language codes.

  • gct-translate-text

    Returns the translated text.

import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

""" IMPORTS """

import json
import hashlib
import traceback
from google.cloud import translate_v3  # type: ignore[attr-defined]


class Client:
    """Wrapper around the Google Cloud Translate API Client implementing the code
    to handle credentials and proxy under Demisto and a translation between
    the Google Cloud Python library typing system and Python serializable
    dictionaries/lists

    Returns:
        service_account(dict): The desarialized contents of the Service Account Private
            Key JSON file
        project(str): The GCP project ID. If None, the project id is read from the
            service_account. Default: None
        verify(bool): Enable certificate verification. Default: True
        proxy(bool): Enable proxy. Default: False
    """

    def __init__(self, service_account=None, project=None, verify=True):
        self.service_account = service_account
        self.project = project
        self.verify = verify

        self.client = self._get_client()
        self.project_id = self._get_project_id()

    def get_supported_languages(self):
        """Returns languages supported by Google Cloud Translation API

        Returns:
            list: List of supported languages. Each entry is a dictionary
                representing a supported language: language_code is the
                2 letter ISO language code, support_source is a bool
                indicating if the language is a supported source,
                support_target is a bool indicating if the language is
                a supported target for the translation.
        """
        parent = f"projects/{self.project_id}/locations/global"
        result = self.client.get_supported_languages(parent=parent)

        return [
            {
                "language_code": language.language_code,
                "support_source": language.support_source,
                "support_target": language.support_target,
            }
            for language in result.languages
        ]

    def translate_text(self, text, target, source=None):
        """Translates a text from source language to target language.

        Args:
            text (str): The text to be translated
            target (str): ISO 2 letter code of the target language. Default: en
            source (str, optional): ISO 2 letter code of the source language. If
                None, Google Cloud Translate will try to detect the source
                language. Default: None

        Returns:
            dict: Result of translation. The translated_text key is the result
                of the translation, detected_language_code is the ISO 2 letter
                code of the detected language or None if the source language
                was specified.
        """
        parent = f"projects/{self.project_id}/locations/global"
        result = self.client.translate_text(
            request={"contents": [text], "target_language_code": target, "parent": parent, "source_language_code": source}
        )

        return {
            "detected_language_code": result.translations[0].detected_language_code,
            "translated_text": result.translations[0].translated_text,
        }

    def _get_project_id(self):
        return self.project if self.project is not None else self.service_account["project_id"]

    def _get_client(self):
        handle_proxy()

        cur_directory_path = os.getcwd()
        credentials_file_name = demisto.uniqueFile() + ".json"
        credentials_file_path = os.path.join(cur_directory_path, credentials_file_name)

        with open(credentials_file_path, "w") as creds_file:
            json.dump(self.service_account, creds_file)

        return translate_v3.TranslationServiceClient.from_service_account_json(  # type: ignore[call-arg]
            filename=credentials_file_path
        )


def test_module(client):
    """
    Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful.

    Args:
        client (Client): instance of the Client class

    Returns:
        'ok' if test passed, anything else will fail the test.
    """

    try:
        client.get_supported_languages()
        return "ok"

    except Exception as e:
        return f"Test failed: {str(e)}"


def supported_languages(client):
    """Returns the list of supported languages

    Args:
        client (Client): instance of the Client class

    Returns:
        The list of supported languages

        readable_output (str): This will be presented in the war room - should be in markdown syntax - human readable
        outputs (dict): Dictionary/JSON - saved in the incident context in order to be used as inputs for other tasks in the
                 playbook
        raw_response (dict): Used for debugging/troubleshooting purposes - will be shown only if the command executed with
                      raw-response=true
    """
    result = client.get_supported_languages()

    # readable output will be in markdown format - https://www.markdownguide.org/basic-syntax/
    readable_output = "Languages: {}".format(", ".join([language["language_code"] for language in result]))
    outputs = {"GoogleCloudTranslate": {"SupportedLanguages": result}}

    return (
        readable_output,
        outputs,
        result,  # raw response - the original response
    )


def translate_text(client, args):
    """Translates text

    Args:
        client (Client): instance of the Client class
        args (dict): dictionary of arguments. The argument text is the text to
            be translated, target is the ISO 2 letter code of the target language
            (default: en), source is the ISO 2 letter code of the source language
            (default: auto detect)

    Returns:
        The list of supported languages

        readable_output (str): This will be presented in the war room - should be in markdown syntax - human readable
        outputs (dict): Dictionary/JSON - saved in the incident context in order to be used as inputs for other tasks in the
                 playbook
        raw_response (dict): Used for debugging/troubleshooting purposes - will be shown only if the command executed with
                      raw-response=true
    """
    text = args.get("text", "")
    target = args.get("target", "en")
    source = args.get("source", None)

    result = client.translate_text(text, target, source=source)

    readable_output = "Translation: {}\nSource Language Detected: {}".format(
        result["translated_text"], result["detected_language_code"]
    )

    id_ = hashlib.md5(f"{target}-{source}-{text}".encode()).hexdigest()  # nosec

    outputs = {
        "GoogleCloudTranslate.TranslateText(val.ID && val.ID==obj.ID)": {
            "ID": id_,
            "text": text,
            "translated_text": result["translated_text"],
            "source_language_code": source,
            "detected_language_code": result["detected_language_code"],
            "target_language_code": target,
        }
    }

    return (
        readable_output,
        outputs,
        result,  # raw response - the original response
    )


def main():
    """
    PARSE AND VALIDATE INTEGRATION PARAMS
    """
    service_account_json = demisto.params().get("project_creds", {}).get("password") or demisto.params().get(
        "service_account_json"
    )
    try:
        service_account = json.loads(service_account_json)
    except Exception:
        return_error("Invalid JSON provided")

    project = demisto.params().get("project_creds", {}).get("identifier") or demisto.params().get("project", None)

    verify_certificate = not demisto.params().get("insecure", False)

    LOG(f"Command being called is {demisto.command()}")
    try:
        client = Client(
            service_account=service_account,
            project=project,
            verify=verify_certificate,
        )

        if demisto.command() == "test-module":
            # This is the call made when pressing the integration Test button.
            result = test_module(client)
            demisto.results(result)

        elif demisto.command() == "gct-supported-languages":
            return_outputs(*supported_languages(client))

        elif demisto.command() == "gct-translate-text":
            return_outputs(*translate_text(client, demisto.args()))

    # Log exceptions
    except Exception as e:
        LOG(traceback.format_exc())
        return_error(f"Failed to execute {demisto.command()} command. Error: {str(e)}")

    finally:
        LOG.print_log()


if __name__ in ("__main__", "__builtin__", "builtins"):
    main()