IRC text-to-speech using espeak
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

espeaker.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2015-2016 nickolas360 <contact@nickolas360.com>
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from pyrcb2 import IRCBot, Event
  15. from getpass import getpass
  16. from xml.sax.saxutils import escape
  17. import asyncio
  18. import conf
  19. import sys
  20. __version__ = "0.2.1"
  21. USAGE = """\
  22. Usage: espeaker <port> <irc-host> <irc-port> [--ssl] <nickname> <channel>\
  23. """
  24. SSML_TEMPLATE = """
  25. <voice name="{0}">
  26. <prosody pitch="{1}">
  27. {2}
  28. </prosody>
  29. </voice>
  30. """
  31. class ESpeaker:
  32. def __init__(self, channel, port, **kwargs):
  33. self.bot = IRCBot(**kwargs)
  34. self.bot.load_events(self)
  35. self.channel = channel
  36. self.port = port
  37. self.server = None
  38. self.clients = set()
  39. async def start_server(self):
  40. def client_connected(reader, writer):
  41. self.clients.add((reader, writer))
  42. writer.write(conf.connect_message.encode("utf8"))
  43. self.server = await asyncio.start_server(
  44. client_connected, "", self.port,
  45. )
  46. async def stop_server(self):
  47. for reader, writer in self.clients:
  48. writer.close()
  49. for reader, writer in self.clients:
  50. try:
  51. await writer.drain()
  52. except ConnectionError:
  53. pass
  54. self.server.close()
  55. await self.server.wait_closed()
  56. async def broadcast(self, message):
  57. message_bytes = message.encode("utf8")
  58. disconnected = set()
  59. for reader, writer in self.clients:
  60. writer.write(message_bytes)
  61. for reader, writer in self.clients:
  62. try:
  63. await writer.drain()
  64. except (ConnectionError, TimeoutError):
  65. disconnected.add((reader, writer))
  66. self.clients -= disconnected
  67. @Event.privmsg
  68. async def on_privmsg(self, sender, channel, message):
  69. if channel is None:
  70. return
  71. voice, pitch = get_voice(sender)
  72. ssml_data = SSML_TEMPLATE.format(voice, pitch, escape(message))
  73. print("SSML data:", ssml_data[1:], end="")
  74. await self.broadcast(ssml_data)
  75. async def start_async(self, hostname, port, ssl, nickname, password):
  76. await self.bot.connect(hostname, port, ssl=ssl)
  77. await self.bot.register(nickname, password=password)
  78. await self.bot.join(self.channel)
  79. await self.start_server()
  80. await self.bot.listen()
  81. def start(self, hostname, port, ssl, nickname, password):
  82. self.bot.call_coroutine(
  83. self.start_async(hostname, port, ssl, nickname, password),
  84. )
  85. def get_voice(nickname):
  86. if nickname in conf.voices:
  87. return conf.voices[nickname]
  88. return conf.voices.default_factory()
  89. def invalid_args():
  90. print(USAGE, file=sys.stderr)
  91. return 1
  92. def main(argv):
  93. if not (6 <= len(argv) <= 7):
  94. return invalid_args()
  95. ssl = False
  96. if len(argv) == 7:
  97. if argv[4] != "--ssl":
  98. return invalid_args()
  99. ssl = True
  100. del argv[4]
  101. port, irc_host, irc_port, nickname, channel = argv[1:]
  102. port, irc_port = int(port), int(irc_port)
  103. print("Password (empty for none): ", end="", file=sys.stderr, flush=True)
  104. password = getpass("") if sys.stdin.isatty() else input()
  105. espeaker = ESpeaker(channel, port, log_communication=True)
  106. try:
  107. espeaker.start(irc_host, irc_port, ssl, nickname, password)
  108. except KeyboardInterrupt:
  109. pass
  110. loop = asyncio.get_event_loop()
  111. loop.run_until_complete(espeaker.stop_server())
  112. return 0
  113. if __name__ == "__main__":
  114. sys.exit(main(sys.argv))