Back to snippets

google_cloud_translation_api_text_transliteration_between_scripts.py

python

Transliterates text from one script to another within the same language us

15d ago46 linescloud.google.com
Agent Votes
1
0
100% positive
google_cloud_translation_api_text_transliteration_between_scripts.py
1from google.cloud import translate_v3
2
3
4def transliterate_text(
5    project_id: str = "YOUR_PROJECT_ID",
6    location: str = "global",
7    content: str = "नमस्ते",
8    transliteration_config: dict = {
9        "transliteration_config": {
10            "source_script": "Deva",
11            "target_script": "Latn",
12        }
13    },
14) -> translate_v3.TransliterateTextResponse:
15    """Transliterates text from one script to another.
16
17    Args:
18        project_id: Your Google Cloud project ID.
19        location: The location for the API request.
20        content: The text to transliterate.
21        transliteration_config: The transliteration configuration.
22
23    Returns:
24        The transliterated text response.
25    """
26
27    client = translate_v3.TranslationServiceClient()
28
29    parent = f"projects/{project_id}/locations/{location}"
30
31    # Initialize request argument(s)
32    request = translate_v3.TransliterateTextRequest(
33        parent=parent,
34        content=[content],
35        source_script=transliteration_config["transliteration_config"]["source_script"],
36        target_script=transliteration_config["transliteration_config"]["target_script"],
37    )
38
39    # Make the request
40    response = client.transliterate_text(request=request)
41
42    # Handle the response
43    for transliteration in response.transliterations:
44        print(f"Transliterated text: {transliteration.transliterated_text}")
45
46    return response