platypush/platypush/plugins/tts/__init__.py

60 lines
1.6 KiB
Python
Raw Normal View History

2017-12-22 03:14:19 +01:00
import urllib.parse
2021-02-19 20:47:29 +01:00
from typing import Optional
2017-12-22 03:14:19 +01:00
2021-02-19 20:47:29 +01:00
from platypush.context import get_plugin
from platypush.plugins import Plugin, action
2017-12-22 03:14:19 +01:00
2019-07-01 22:26:04 +02:00
2017-12-22 03:14:19 +01:00
class TtsPlugin(Plugin):
2018-06-25 19:57:43 +02:00
"""
Default Text-to-Speech plugin. It leverages Google Translate's unofficial
frontend API.
2018-06-25 19:57:43 +02:00
"""
2017-12-22 03:14:19 +01:00
def __init__(self, language='en-US', **player_args):
"""
:param language: Language code (default: ``en-US``).
:param player_args: Additional arguments to be passed to
:meth:`platypush.plugins.sound.SoundPlugin.play` (like volume,
duration, channels etc.).
"""
2018-01-03 02:23:25 +01:00
super().__init__()
self.language = language
2021-02-19 20:47:29 +01:00
self.player_args = player_args or {}
def _playback(self, resource: str, **kwargs):
audio = get_plugin('sound')
assert audio
audio.play(resource, **{**self.player_args, **kwargs})
2018-01-03 02:23:25 +01:00
@action
def say(
self,
text: str,
language: Optional[str] = None,
**player_args,
):
2018-06-25 19:57:43 +02:00
"""
Say some text.
2018-06-25 19:57:43 +02:00
:param text: Text to say.
:param language: Language code override.
:param player_args: Extends the additional arguments to be passed to
:meth:`platypush.plugins.sound.SoundPlugin.play` (like volume,
duration, channels etc.).
2018-06-25 19:57:43 +02:00
"""
language = language or self.language
url = 'https://translate.google.com/translate_tts?' + urllib.parse.urlencode(
{
2021-02-19 20:47:29 +01:00
'ie': 'UTF-8',
'client': 'tw-ob',
'tl': language,
'q': text,
}
)
2021-02-19 20:47:29 +01:00
self._playback(url, **player_args)
2021-02-19 20:47:29 +01:00
2017-12-22 03:14:19 +01:00
# vim:sw=4:ts=4:et: