Search code examples
encodingpython-requestsasciihindi

Failing to call hindi voice API due to UnicodeEncodeError


I am trying to call an API, which converts hindi text into voice but whenever I call this:

http://ivrapi.indiantts.co.in/tts?type=indiantts&text='+response+'&api_key=xyx&user_id=abc&action=play&numeric=hcurrency&lang=hi_mohita

where response=any text in hindi

Error:

playwav(urlopen('http://ivrapi.indiantts.co.in/tts?type=indiantts&text='+response+'&api_key=xyz&user_id=abc&action=play&numeric=hcurrency&lang=hi_mohita'))

  File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.5/urllib/request.py", line 466, in open
    response = self._open(req, data)
  File "/usr/lib/python3.5/urllib/request.py", line 484, in _open
    '_open', req)
  File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.5/urllib/request.py", line 1282, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/usr/lib/python3.5/urllib/request.py", line 1254, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "/usr/lib/python3.5/http/client.py", line 1107, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1142, in _send_request
    self.putrequest(method, url, **skips)
  File "/usr/lib/python3.5/http/client.py", line 984, in putrequest
    self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 29-31: ordinal not in range(128)

I have tried encoding and decoding into utf8 and unicode() function and nothing is working.


Solution

  • This worked

    response="मैं आपको बता दूंगा"
    print(response)
    params = {'text':response.encode('UTF-8'), 'api_key': 'abc','user_id':'xyz','action':'play','numeric':'hcurrency','lang':'hi_mohita'}
    print('http://ivrapi.indiantts.co.in/tts?type=indiantts&'+urllib.parse.urlencode(params))
    playwav(urlopen('http://ivrapi.indiantts.co.in/tts?type=indiantts&'+urllib.parse.urlencode(params)))