File size: 1,564 Bytes
43c88a7
 
09af6bc
43c88a7
 
09af6bc
 
7f8aad3
 
 
bddd8be
 
43c88a7
7f8aad3
 
09af6bc
 
7f8aad3
 
 
43c88a7
7f8aad3
09af6bc
7f8aad3
09af6bc
9cde6b7
 
09af6bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
from deep_translator.configs import config
from requests.exceptions import HTTPError


def get_request_body(text, api_key, *args):

    if not api_key:
        raise Exception("you need to get an API_KEY for this to work. "
                        "Get one for free here: https://detectlanguage.com/documentation")
    if not text:
        raise Exception("Please provide an input text")

    else:
        try:
            headers = config['headers']
            headers['Authorization'] = headers['Authorization'].format(api_key)
            response = requests.post(config['url'],
                                     json={'q': text},
                                     headers=headers)

            body = response.json().get('data')
            return body

        except HTTPError as e:
            print("Error occured while requesting from server: ", e.args)
            raise e


def single_detection(text, api_key=None, detailed=False, *args, **kwargs):
    """
    function responsible for detecting the language from a text
    """
    body = get_request_body(text, api_key)
    detections = body.get('detections')
    if detailed:
        return detections[0]

    lang = detections[0].get('language', None)
    if lang:
        return lang


def batch_detection(text_list, api_key, detailed=False, *args):
    body = get_request_body(text_list, api_key)
    detections = body.get('detections')
    res = [obj[0] for obj in detections]
    if detailed:
        return res
    else:
        return [obj['language'] for obj in res]