-
Notifications
You must be signed in to change notification settings - Fork 0
/
translation_service.py
51 lines (44 loc) · 1.48 KB
/
translation_service.py
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
import os
import logging
import requests
from pydantic import BaseModel
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class TranslationRequest(BaseModel):
src: str
tgt: str
use_multi: str
text: str
class Config:
populate_by_name = True
class TranslationService:
def __init__(self):
self.api_url = os.getenv('TRANSLATION_API_URL')
if not self.api_url:
raise ValueError("TRANSLATION_API_URL environment variable is not set")
def translate(self, text: str, src_language: str, tgt_language: str) -> str:
try:
payload = TranslationRequest(
src=src_language,
tgt=tgt_language,
use_multi="MULTI",
text=text
)
response = requests.post(
self.api_url,
headers={
"accept": "application/json",
"Content-Type": "application/json"
},
json=payload.model_dump()
)
if response.status_code == 200:
return response.json().get("translation")
elif response.status_code == 406:
raise ValueError("Invalid language pair selected")
else:
raise ValueError(f"Translation failed with status code {response.status_code}")
except Exception as e:
logging.error(f"Translation error: {str(e)}")
return text