File size: 1,135 Bytes
6fbb505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import requests

class Translator:
    def __init__(self, api_key, base_url="https://api.fanar.qa/v1/translations", langpair="ar-en", model="Fanar-Shaheen-MT-1"):
        self.api_key = api_key
        self.base_url = base_url
        self.langpair = langpair
        self.model = model

    def translate(self, text):        
        headers = {
            'Content-Type': 'application/json', 
            'Authorization': f'Bearer {self.api_key}', 
            "User-Agent": "curl/7.81.0" 
        }
        
        data = {
            "text": text,
            "langpair": self.langpair,
            "model": self.model
        }

        res = requests.post(self.base_url, headers=headers, json=data)
        if res.status_code != 200:
            raise Exception(f"Error: API request failed with status code {res.status_code}. Details: {res.text}")
        
        data = res.json()
        if "text" not in data: # modify to account for API failures. Not very important since we need to run locally. 
            raise Exception(f"Error: 'text' not found in response: {data}")
        
        return data["text"]