Skip to content

Instantly share code, notes, and snippets.

@saidsef
Last active January 15, 2018 03:44
Show Gist options
  • Save saidsef/9d54167b9cc48da7795d9ec692728f94 to your computer and use it in GitHub Desktop.
Save saidsef/9d54167b9cc48da7795d9ec692728f94 to your computer and use it in GitHub Desktop.
AWS Polly - Read to me
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Said Sef. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
import boto3
import tempfile
import logging
from voices import Voices
from os import system, uname, path, unlink, remove, rmdir
class Polly(object):
def __init__(self):
logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
v = Voices()
self.voice = v.get_voice('polly')
self.polly = boto3.client("polly", region_name='eu-west-1')
self.tmpdir = tempfile.mkdtemp()
self.file_name = 'article.mp3'
self.file_path = path.join(self.tmpdir, self.file_name)
def _info(self):
return (type(self), tuple(map(self.__getattribute__)))
def play(self, text, format='mp3'):
resp = self.polly.synthesize_speech(OutputFormat=format, Text=text, VoiceId=self.voice)
soundBytes = resp['AudioStream'].read()
with open(self.file_path, 'w') as fh:
fh.write(soundBytes)
if 'Darwin' in uname():
system('afplay %s' % (self.file_path)) # Works only on Mac OS, sorry
remove(self.file_path)
def __del__(self):
if path.exists(self.file_path):
unlink(self.file_path)
rmdir(self.tmpdir)
#!/usr/bin/env python
# Copyright (c) 2018, Said Sef. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
from random import shuffle, choice
class Voices(object):
def __init__(self):
self.macosx = ['Moira', 'Samantha', 'Tessa', 'Alex', 'Daniel']
self.polly = ['Joanna', 'Joey', 'Brian', 'Amy', 'Emma']
def list(self, platform):
''' Returns list of Voices or the platform name '''
if 'macosx' in platform:
return self.macosx
elif 'polly' in platform:
return self.polly
else:
return platform
def get_voice(self, platform):
''' Returns single voice from the list '''
if 'macosx' in platform:
return choice(self.macosx)
elif 'polly' in platform:
return choice(self.polly)
else:
return platform
def __del__(self):
del self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment