Skip to content. | Skip to navigation

Personal tools

Navigation

You are here: Home / Members / jhb / speak.py

speak.py

by Jörg Baach last modified Jan 13, 2011 09:27 AM

Python Source icon speak.py — Python Source, 1 kB (1638 bytes)

File contents

#!/usr/bin/env python

#quick hack to for a speak server for navigation commands
#run: python speak.py [language]
#      language can be english (default) or german

#use: http://localhost/turn_left
#     http://localhost/turn_right

# needs espeak installed

from BaseHTTPServer import BaseHTTPRequestHandler
import SocketServer,os,sys
from subprocess import Popen

PORT = 9999

if len(sys.argv) < 2:
    language = 'english'
else:
    language = sys.argv[1]

commands = dict(turn_left=dict(english='please turn left',
                               german='bitte links fahren '),
                turn_right=dict(english='please turn right',
                german='bitte rechts fahren '))

class OurServer(SocketServer.TCPServer):
    allow_reuse_address = True


class TalkHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        path = self.path
        talk = 'error'
        parts = path.split('/')
        command = parts[-1]
        if commands.has_key(command) and commands[command].has_key(language):
            talk = commands[command][language]
            if getattr(self.server,'speakpid',None):
                os.kill(self.server.speakpid,9)
                os.waitpid(self.server.speakpid,0)
            self.server.speakpid = Popen(['/usr/bin/espeak',"-v",language,talk]).pid

        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()

        self.wfile.write(str(talk))
        self.wfile.flush()
        self.connection.shutdown(1)


httpd = OurServer(("", PORT), TalkHandler)

print "serving at port %s in %s" % (PORT, language)
httpd.serve_forever()