-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguage_detection.py
More file actions
81 lines (70 loc) · 2.83 KB
/
language_detection.py
File metadata and controls
81 lines (70 loc) · 2.83 KB
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
from lara_sdk import AccessKey, Translator
import os
"""
Language detection examples for the Lara Python SDK
This example demonstrates:
- Detecting language of a single string
- Detecting language of multiple strings
- Using hint parameter to improve detection
- Using passlist to restrict detected languages
"""
def main():
# All examples can use environment variables for credentials:
# export LARA_ACCESS_KEY_ID="your-access-key-id"
# export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
# Falls back to placeholders if not set
access_key_id = os.getenv("LARA_ACCESS_KEY_ID", "your-access-key-id")
access_key_secret = os.getenv("LARA_ACCESS_KEY_SECRET", "your-access-key-secret")
credentials = AccessKey(access_key_id, access_key_secret)
lara = Translator(credentials)
try:
# Example 1: Detect language of a single string
print("=== Single String Detection ===")
result1 = lara.detect("Bonjour, comment allez-vous?")
print("Text: Bonjour, comment allez-vous?")
print(f"Detected language: {result1.language}")
print(f"Content type: {result1.content_type}\n")
# Example 2: Detect language of multiple strings
print("=== Multiple Strings Detection ===")
texts = [
"Hello, how are you?",
"Hola, ¿cómo estás?",
"Ciao, come stai?"
]
result2 = lara.detect(texts)
print(f"Texts: {texts}")
print(f"Detected language: {result2.language}")
print(f"Content type: {result2.content_type}\n")
# Example 3: Using hint parameter
print("=== Detection with Hint ===")
result3 = lara.detect("Hello", hint="en")
print("Text: Hello")
print(f"Hint: en")
print(f"Detected language: {result3.language}")
print(f"Content type: {result3.content_type}\n")
# Example 4: Using passlist to restrict detected languages
print("=== Detection with Passlist ===")
result4 = lara.detect(
"Guten Tag",
passlist=["de-DE", "en-US", "fr-FR"]
)
print("Text: Guten Tag")
print(f"Passlist: ['de-DE', 'en-US', 'fr-FR']")
print(f"Detected language: {result4.language}")
print(f"Content type: {result4.content_type}\n")
# Example 5: Combined hint and passlist
print("=== Detection with Hint and Passlist ===")
result5 = lara.detect(
"Buongiorno",
hint="it",
passlist=["it-IT", "es-ES", "pt-PT"]
)
print("Text: Buongiorno")
print(f"Hint: it")
print(f"Passlist: ['it-IT', 'es-ES', 'pt-PT']")
print(f"Detected language: {result5.language}")
print(f"Content type: {result5.content_type}\n")
except Exception as error:
print(f"Error: {error}")
if __name__ == "__main__":
main()