How to pass Encoded Audio String to bytes with json?

Question:

I have been trying to implement the below shell code with python.
I am about to make use of deepaffects speaker identification api . So before its’s use i need to enroll the audio file with user id , in their docs there is no python example given instead of below shell commands.

curl -X POST "https://proxy.api.deepaffects.com/audio/generic/api/v1    /sync/diarization/enroll?apikey=<ACCESS_TOKEN>" -H 'content-type: application/json' -d @data.json

# contents of data.json
{"content": "bytesEncodedAudioString", "sampleRate": 8000, "encoding":   "FLAC", "languageCode": "en-US", "speakerId": "user1" }

So far now I had written the below code.

 import requests

 url = 'https://proxy.api.deepaffects.com/audio/generic/api/v1   /sync/diarization/enroll?apikey=<3XY9aG7AbXZ4AuKyAip7SXfNNdc4mwq3>'

 data = {
     "content": "bytesEncodedAudioString", 
     "sampleRate": 8000, 
     "encoding": "FLAC",
     "languageCode": "en-US", 
     "speakerId": "Pranshu Ranjan",
  }

  headers = {'content-type': 'application/json'}
  r = requests.post(url, data=data, headers=headers) 
  print(r)

But I don’t know how to pass the "content": "bytesEncodedAudioString". I have audio samples in mp3 format in my local directory.
here is the deepAffects api reference and they support multiple audio formats

Asked By: Path- Or

||

Answers:

According to documentation:

content (String) base64 encoding of the audio file.

Just use built-in base64 module to encode your audio file:

import base64
import requests


filepath = "C:Audio...file.mp3"
with open(filepath, 'rb') as f:
    audio_encoded = base64.b64encode(f.read())  # read file into RAM and encode it

data = {
    "content": str(audio_encoded),  # base64 string
    "sampleRate": 8000, 
    "encoding": "FLAC",  # maybe "MP3" should be there?
    "languageCode": "en-US", 
    "speakerId": "My Name",
}

url = ...
r = requests.post(url, json=data)  # note json= here. Headers will be set automatically.
Answered By: Ivan Vinogradov