class ComputerPlayer(Player):
    def __init__(self, symbol, name):
        super().__init__(symbol, name)
        self.voice = Speech()

    def say(self, text):
        self.voice.say(text)

    def move(self, state: State, opponent):
        board = state.board()
        self.say("Now it's my turn! You will lose!")
        movement = optimum_move(board, opponent.symbol, self.symbol,
                                self.symbol).index
        r, c = movement
        self.say("Please put {0} in {1} row and {2} column".format(
            symbol_name(self.symbol), number_name(r + 1), number_name(c + 1)))
        try:
            dr, dc = wait_for_move(board, state, self.symbol)
            if dr != r or dc != c:
                raise MoveError("Sign was putted not in requested place")
        except MoveError as e:
            self.say("You tried to lie me. I won't play with you, because {0}".
                     format(e))
            raise MoveError("Computer move error")
        self.say("Thank you")
Exemple #2
0
    def get_speech(self, rm='', parti='', anftyp='', antal=100):
        anforande_list = []
        data = self._get(
            self.url, 'anforandelista', {
                'rm': rm,
                'parti': parti,
                'anftyp': anftyp,
                'utformat': 'json',
                'sz': antal
            })

        # Only special rule for a party, hate it. Because Folkpartiet changed name to Libreralerna
        if parti == Party.L.name:
            anforande_list += self.get_speech(rm=rm,
                                              parti='FP',
                                              anftyp=anftyp,
                                              antal=antal)

        if not data:
            return anforande_list

        if data['@antal'] == '0':
            logging.warning(f'No data for {rm}, {parti}, {anftyp}')
        elif data['@antal'] == '1':
            anforande_list.append(Speech(data['anforande']))
        else:
            for anforande_data in data['anforande']:
                anforande_list.append(Speech(anforande_data))

        return anforande_list
Exemple #3
0
    def __init__(self):
        """Initialize brain class of Sara."""
        self.log = logging.getLogger()
        self.log.info('initialize brain...')

        self.config = configs.default_obj()
        if os.path.exists('user.json'):
            self.config = configs.update(self.config, 'user.json')

        self.speech = Speech(self.config.speech)

        self.speech.speak("Load language: " +
                          self.config.language.name[self.config.language.code])
        self.phrases = configs.language_obj(self.config.language.languages_dir,
                                            self.config.language.code)
        self.help = Help(self.config.language, self.phrases)
        self.speech.speak(self.phrases.general.start)

        self.generals = {'quit': False, 'text': '', 'arg': None}

        self.bd = Databases(self.config.sqlite)
        self.assist = Assistant(self.speech, self.config, self.phrases,
                                self.bd)
        if True if "true" == self.config.general.setup else False:
            self.assist.setup()

        self.backups = Backups(self.config.backups, self.bd)
        self.hotkeys = Hotkeys(self.config.hotkeys, self.generals)
        self.recognizer = Recognizer(self.config.recognition,
                                     self.config.language.code, self.generals,
                                     self.speech, self.phrases.recognition)
    def _do_participant_practice_turn(self):
        self.websocket_server.send("hide_answers()")

        # Some introduction by the robot
        self.robot_connection.say(Speech.get(self.lang, 'practice_participant_instruction'))
        self.robot_connection.say(Speech.get(self.lang, 'practice_participant_instruction_2'))

        # The concept to perform is always 'ball' in the practice round
        # When adding a new language, don't forget to translate this term.
        concept = {
            'id': 'ball',
            'description': {
                'nl': 'Bal',
                'en': 'Ball'
            },
            'article': {
                'nl': 'Een',
                'en': 'A'
            },
            'category': 'entertainment',
            'image_filename': 'ball.png'
        }

        self._log("participant_practice_turn()")

        # Show the ball on the tablet screen so the participant knows
        # what to perform a gesture for.
        self.websocket_server.send("show_item(" + json.dumps(concept) + ")")
Exemple #5
0
    def populateSpeech(self):
        url = self._build_url({'mode': MenuNavigator.COMMAND_SPEECH_INPUT})
        li = xbmcgui.ListItem(__addon__.getLocalizedString(32200), iconImage=__icon__)
        li.addContextMenuItems([], replaceItems=True)  # Clear the Context Menu
        self._addPlayerToContextMenu(li)  # Add the Sonos player to the menu
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False)

        url = self._build_url({'mode': MenuNavigator.COMMAND_SPEECH_SAVE})
        li = xbmcgui.ListItem(__addon__.getLocalizedString(32203), iconImage=__icon__)
        li.addContextMenuItems([], replaceItems=True)  # Clear the Context Menu
        self._addPlayerToContextMenu(li)  # Add the Sonos player to the menu
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False)

        # Add a blank line before the filters
        li = xbmcgui.ListItem("", iconImage=__icon__)
        li.addContextMenuItems([], replaceItems=True)
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, url="", listitem=li, isFolder=False)

        # Create the speech class (Not going to call the Sonos System do no need for the device)
        speech = Speech()
        phrases = speech.loadSavedPhrases()
        del speech

        # Loop through all the phrases and add them to the screen
        for phrase in phrases:
            url = self._build_url({'mode': 'action', 'action': ActionManager.ACTION_SPEECH_SAY_PHRASE, 'itemId': phrase})
            li = xbmcgui.ListItem(phrase, iconImage=__icon__)
            # Add the remove button to the context menu
            cmd = self._build_url({'mode': 'action', 'action': ActionManager.ACTION_SPEECH_REMOVE_PHRASE, 'itemId': phrase})
            ctxtMenu = []
            ctxtMenu.append((__addon__.getLocalizedString(32204), 'RunPlugin(%s)' % cmd))
            li.addContextMenuItems(ctxtMenu, replaceItems=True)  # Clear the Context Menu
            xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False)

        xbmcplugin.endOfDirectory(self.addon_handle)
Exemple #6
0
 def command_autopilot(self):
     text = 'Runing autopilot!'
     speech = Speech()
     speech.create_voice(text)
     process = RaspieAutopilotProcess()
     process.start()
     return True
Exemple #7
0
def main():
    ted = TEDrecord()
    speech = Speech()
    tedmqtt = TEDMQTT()
    print("TEDiot is starting...press the button to start talking...")
    while True:
        input_state = GPIO.input(18)
        if input_state == False:
            print("Now TEDiot is listening you...")
            ted.startRecording()
            audioResult = speech.speechToText()
            if not (ted.isPlaying):
                if any(word in audioResult for word in speech.keyWordsPlay):
                    ted.isPlaying = True
                    print("Starting button thread...")
                    fileLog(audioResult)
                    t1 = Thread(target=buttonThread, args=(ted, speech))
                    t1.start()
                    ted.playWAV(audioResult)
                    #t1 = Thread(target=ted.playWAV(audioResult))
                elif any(word in audioResult
                         for word in speech.keyWordsUpdate):
                    print("Updating the cloud...")
                    tedmqtt.update()
                else:
                    print("Command not found!")
class Bot:
    def __init__(self):
        """
            here the main speech module is speech which is in the file
            here the dictionary modusle is PyDictionary which will be using 
        """
        self.speech = Speech()
        self.dictionary = PyDictionary()
        self.universal = Universal(self.speech)
        self.meaning = Meaning(self.speech)
        self.synonym = Synonym(self.speech)
        self.antonym = Antonym(self.speech)

    def speak(self):
        sent = self.speech.listen()
        print(sent)
        if 'meaning of' in sent:
            self.meaning.Start_Meaning(sent)
        elif 'synonyms' in sent:
            self.synonym.Start_Synonym(sent)
        elif 'antonyms' in sent:
            self.antonym.Start_Antonym(sent)
        else:
            if (self.universal.check(sent) == False):
                self.speech.speak("Invalid Response how can I help you")
        return sent
Exemple #9
0
 def __init__(self):
     self._messageDuration = Config.MESSAGE_DURATION
     self._speech = Speech("audio/")
     self._startPlayingVideoTime = None
     self._messageBox = MessageBox()
     if Config.ENABLE_BROWSER:
         print("Initing browser intent")
         self._browserService = BrowserService()
Exemple #10
0
def writeLogMsg(t, className, topic, message):
    ts = datetime.datetime.utcnow()
    txt = t + ": " + str(
        ts) + ", " + className + "." + topic + " -> '" + message + "'"
    print(txt)
    _FILESTREAM.write(txt + _LINEENDING)
    if _SPEECH:
        Speech.sayText(message)
Exemple #11
0
 def sayPhrase(self, phrase):
     # Make sure a Sonos speaker was found
     if self.sonosDevice is not None:
         # Create the speech class and play the message
         speech = Speech(self.sonosDevice)
         # Now get the Sonos Sytem to say the message
         speech.say(phrase)
         del speech
Exemple #12
0
 def command_weatcher(self):
     weather = Weather()
     weatcherData = weatcher.check_weather()
     text = weather['forecast']['txt_forecast']['forecastday'][0][
         'fcttext_metric']
     speech = Speech()
     speech.create_voice(text)
     return True
Exemple #13
0
 def sayPhrase(self, phrase):
     # Make sure a Sonos speaker was found
     if self.sonosDevice is not None:
         # Create the speech class and play the message
         speech = Speech(self.sonosDevice)
         # Now get the Sonos Sytem to say the message
         speech.say(phrase)
         del speech
Exemple #14
0
def main():
    manege.init()
    s = Speech()
    s.record()
    dat = s.get_result()
    if dat != None:
        print(dat)
        manege.main(dat)
Exemple #15
0
 def key_control(self):
     for event in pygame.event.get():
         if event.type == pygame.KEYDOWN and event.key == pygame.K_POWER:
             self.shutdown()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_0:
             self.shutdown()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_9:
             self.display_text('Restarting raspie...')
             PyMove().gpio_cleanup()
             time.sleep(2)
             subprocess.call(['.././start.sh'])
             sys.exit()
         if event.type == pygame.KEYUP and event.key == pygame.K_1:
             self.run_autopilot()
             
             autopilot_process.start()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_8:
             print 'Cleaning up gpio'
             PyMove().gpio_cleanup()
         if event.type == pygame.KEYUP and event.key == pygame.K_2:
             text = "Good Morning! My name is Shadow. I am prototype of home asistant robot. I was programmed to listen to your commands."
             self.display_text(text)
             Speech().create_voice(text)
         if event.type == pygame.KEYUP and event.key == pygame.K_3:
             text = "Let's dance!"
             speech = Speech()
             speech.create_voice(text)
             self.display_text(text)
             PyMove().run_left_start()
             time.sleep(1)
             PyMove().run_left_stop()
             PyMove().run_right_start()
             time.sleep(1)
             PyMove().run_right_stop()
             PyMove().run_up_start()
             time.sleep(1)
             PyMove().run_up_stop()
             PyMove().run_down_start()
             time.sleep(1)
             PyMove().run_down_stop()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_4:
             self.play_sound('sounds/Very_Excited_R2D2.mp3')                               
         if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
             PyMove().run_up_start()
         elif event.type == pygame.KEYUP and event.key == pygame.K_UP:
             PyMove().run_up_stop()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
             PyMove().run_down_start()
         elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
             PyMove().run_down_stop()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
             PyMove().run_left_start()
         elif event.type == pygame.KEYUP and event.key == pygame.K_LEFT:
             PyMove().run_left_stop()
         if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
             PyMove().run_right_start()
         elif event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:
             PyMove().run_right_stop()
Exemple #16
0
 def __init__(self):
     self.nlg = NLG(user_name=self.my_name)
     self.speech = Speech(launch_phrase=self.launch_phrase,
                          debugger_enabled=self.debugger_enabled)
     self.actions = Actions(self.location)
     if os.path.isfile('unknown_commands.csv') == False:
         with open('unknown_commands.csv', 'w') as csvfile:
             writer = csv.DictWriter(csvfile,
                                     fieldnames=self.unknown_fieldnames)
             writer.writeheader()
Exemple #17
0
 def __init__(self, transition_model, observation_model=None, states=None):
     self.transition_model = transition_model
     self.observation_model = observation_model
     self.states_number = transition_model.shape[0]
     self.belief = np.zeros((self.states_number, 1))
     if states is None:
         self.belief.fill(1. / self.states_number)
     else:
         self.belief = states
     self.speech = Speech()
Exemple #18
0
def tts_phrase():
    zones = {zone.player_name: zone for zone in soco.discover()}
    data = request.get_data()
    if isinstance(data, str):  # handle jquery nonsense
        data = json.loads(data)
    zone = zones[data['zone']]
    text = data['text']
    speech = Speech(zone)
    speech.say(text)
    return 'success'
 def __init__(self):
     """
         here the main speech module is speech which is in the file
         here the dictionary modusle is PyDictionary which will be using 
     """
     self.speech = Speech()
     self.dictionary = PyDictionary()
     self.universal = Universal(self.speech)
     self.meaning = Meaning(self.speech)
     self.synonym = Synonym(self.speech)
     self.antonym = Antonym(self.speech)
Exemple #20
0
 def dispatch(self):
     if (not self.params.has_key("id")) or (not self.params.has_key("type") or (not self.params.has_key("text"))):
         return Render.render_400()
     try:
         pa = self.params
         speech_obj = Speech(pa["id"], pa["text"], pa["lan"], pa["type"])
         speech_obj.speak()
         # response back to client
         response = Render(speech_obj)
         return response.render()
     except Exception, e:
         return Render.render_400(e)
Exemple #21
0
 def __init__(self, name=None, speech_input=False, facebook_input=False):
     self.phrases = Phrases()
     self.speech = Speech()
     self.knowledge = Knowledge(weather_api_token=weather_api_token)
     self.name = name
     self.facebook_input = facebook_input
     if self.facebook_input:
         self.facebook_response = list()
     self.speech_input = speech_input
     self.witai = Wit("S73IKQDWJ22OJMOSD6AOT4CSJOWXIPX6")
     self.fs = Fatsecret("90fe184a283449ed8a83e35790c04d65", "054e80b2be154337af191be2c9e11c28")
     self.translator = Translator()
Exemple #22
0
    def __init__(self):
        """Initialize running class."""
        self.__LOW = 33
        self.__MIDLE = 27
        self.config = ConfigParser()
        self.config.read('settings.ini')
        self.size_x = self.config.getint('screen', 'size_x')
        self.size_y = self.config.getint('screen', 'size_y')
        self.difficult = self.config.get('board', 'difficult')

        with open('languages.dat', 'rb') as lang_file:
            self.phrases = pickle.load(lang_file)[self.config.get(
                'total', 'language')]

        self.speech = Speech(self.config)
        self.speech.speak(self.phrases['start'])

        pygame.init()
        pygame.font.init()

        self.screen = pygame.display.set_mode((self.size_x, self.size_y))
        pygame.display.set_caption('Sudoku')

        self.board = Board(self.config, self.screen)
        self.player = Player(self.board, self.speech, self.phrases)
        self.game_over = True
        self.win = False
        self.handle_numbers = {'K_' + str(num): num for num in range(10)}
        self.handle_numbers.update(
            {'K_KP' + str(num): num
             for num in range(10)})

        self.fontObj = pygame.font.SysFont('arial', 50)
        self.clock = pygame.time.Clock()

        self.gen = Generator()
        self.new_game()
        try:
            save_file = open('autosave.sav', 'rb')
        except IOError as e:
            pass
        else:
            with save_file:
                data = pickle.load(save_file)
                self.grid = data['grid']
                self.origin = data['origin']
                self.board.cells = data['cells']
                for cell in self.board.cells:
                    if 0 != cell.status:
                        cell.set_text()
                self.speech.speak(self.phrases['load'])
                self.player.speak()
Exemple #23
0
    def __init__(self, config_provider, disk, display, replay):
        self.config_provider = config_provider
        self.disk = disk
        self.display = display
        self.replay = replay

        # cameras
        self.cameras = self._create_cameras()
        self.camera_number = 0

        # speech recognition
        self.speech = Speech()
        self.speech.start()
Exemple #24
0
    def __init__(self, filename):
        self._conf = yaml.load(open(filename))

        self._rec = sr.Recognizer()
        self._micro = sr.Microphone(sample_rate=16000)

        with self._micro as source:
            self._rec.adjust_for_ambient_noise(source)

        self._dcs = DcsClient(self._conf['dcs'])

        self._player = PlayerManager()

        self._speech = Speech(self._conf['aip'])
 def __init__(self, files):
     if not files:
         self.corpus = PlaintextCorpusReader('./data/speeches', '.*')
     else:
         self.corpus = PlaintextCorpusReader('./data/speeches', files)
     self.speech = Speech(self.corpus.raw(), self.corpus.words(), self.corpus.sents(),self.corpus.paras(), None, None, None, None)
     self.speeches = build_speeches_dict(self.corpus)
     self.years = [int(year.split('.')[0]) for year in self.corpus.fileids()]
     complementary_years = list(set(os.listdir("./data/speeches")) - set([str(years) + '.txt' for years in self.years]))
     if not files:
         self.complementary = None
         self.unique_words = None
     else:
         self.complementary = ComplementaryCorpus(complementary_years)
         self.unique_words = [word for word in self.speech.tokens if word not in self.complementary.speech.tokens]
Exemple #26
0
 def listen_commands(self):
     text = "How I can help You."
     speech = Speech()
     speech.create_voice(text)
     r = SpeechRecognizer()
     command = (r.recognize()).lower()
     print 'Recognized command: {0}'.format(command)
     if 'weatcher' in command:
         self.command_weatcher()
     if 'autopilot' in command:
         self.command_autopilot()
     if 'dance' in command:
         self.command_dance()
     if 'exterminate' in command:
         self.command_exterminate()
    def _do_robot_second_turn(self):
        self._log("robot_second_turn()")
        self.robot_connection.say(Speech.get(self.lang, 'robot_turn_start'))

        self._pick_and_perform()

        self.websocket_server.send("enable_answers()")
Exemple #28
0
 def __init__(self):
     self.commans = (Play(), Variable(), Speech(), Info())  #, Sinoptik())
     self.db = DBConnector()
     # Очищаем список команд. Список не актуален.
     self.db.IUD("delete from core_execute")
     self.last_processed_ID = -1
     self.db.commit()
     self.run()
Exemple #29
0
 def load_modules(self):
     self._speech = Speech(self.session)
     self._motion = Motion(self.session)
     self._tablet = Tablet(self.session)
     self._face_detection = FaceDetection(self.session, self)
     self._wave_detection = WavingDetection(self.session)
     self._audio_player = AudioPlayer(self.session)
     self._speech_recognition = SpeechRecognition(self.session)
     self._system = System(self.session)
Exemple #30
0
    def test_intervals_overlapping_for_included_interval(self):
        speech = Speech(path_to_wav="",
                        interval=Interval(0, 15.5),
                        word_intervals=[
                            WordInterval(0, 14, "woooow"),
                        ])

        self.assertEqual(intersecting_utterances(speech, Interval(0, 14)),
                         [Interval(0, 14)])
Exemple #31
0
class SpeechTestCase(unittest.TestCase):
    """-"""
    def setUp(self):
        """-"""
        audio_dir = os.path.dirname(os.path.abspath(__file__)) + "/../audio"
        self.speech_test = Speech(audio_dir)

    def tearDown(self):
        """-"""
        self.speech_test = None

    def test_speak(self):
        """-"""
        self.assertEqual(self.speech_test.speak('hello'), "tts.mp3")

    def test_speak_weather(self):
        """-"""
        self.assertEqual(self.speech_test.speak_weather(), "tts.mp3")
    def _do_robot_turn(self):
        # Hide previous results screen from the participant's turn (if applicable)
        self.websocket_server.send("hide_classification()")
        self.num_answer_attempts = 0
        self.current_concept = self.concepts_robot[self.concept_index]
        self.concepts_used.append(self.current_concept)

        print "Showing: " + self.current_concept["id"]

        if self.concept_index < (self.num_concepts-1) and self.concept_index > 0:
            self.robot_connection.say(Speech.get(self.lang, 'robot_turn'))

        # The robot indicates that we're about to start the last round
        elif self.concept_index == (self.num_concepts - 1):
            self.robot_connection.say(Speech.get(self.lang, 'robot_last_turn'))

        self.robot_connection.say(Speech.get(self.lang, 'robot_turn_start'))

        self._pick_and_perform()

        # Randomly pick three distractor objects. At the moment they can be any of the available concepts.
        answers = list()
        answers.append(self.current_concept)

        for i in range(0, 3):
            answer = Concepts.items[random.randint(0, len(Concepts.items)-1)]

            while answer in answers or answer in self.concepts_used:
                answer = Concepts.items[random.randint(0, len(Concepts.items)-1)]

            answers.append(answer)

        # Shuffle answers
        random.shuffle(answers)

        answer_data = dict()
        answer_data["answers"] = answers
        answer_data["correct_answer"] = self.current_concept["id"]

        # Send them to the tablet
        self.websocket_server.send("show_answers(" + json.dumps(answer_data) + ")")
        self._log("robot_turn(concept=" + self.current_concept["id"] + ",answers_presented=" + json.dumps(answer_data) + ")")

        self.robot_connection.say(Speech.get(self.lang, 'robot_turn_end'))
Exemple #33
0
    def __init__(self):
        """Initialize running class."""
        self.config = ConfigParser()
        self.config.read('settings.ini')
        self.size_x = self.config.getint('screen', 'size_x')
        self.size_y = self.config.getint('screen', 'size_y')

        with open('languages.dat', 'rb') as lang_file:
            self.phrases = pickle.load(lang_file)[self.config.get('total', 'language')]

        self.speech = Speech(self.config)
        self.speech.speak(self.phrases['start'])

        pygame.init()
        pygame.font.init()

        self.screen = pygame.display.set_mode((self.size_x, self.size_y))
        pygame.display.set_caption(self.phrases['title'])

        self.board = Board(self.config, self.screen)
        self.player = Player(self.board, self.speech, self.phrases)
        self.game_over = True
        self.timer = 0

        self.fontObj = pygame.font.SysFont('arial', 50)
        self.clock = pygame.time.Clock()
        pygame.time.set_timer(pygame.USEREVENT, 1000)

        self.new_game()
        try:
            save_file = open('autosave.sav', 'rb')
        except IOError as e:
            pass
        else:
            with save_file:
                data = pickle.load(save_file)
                self.board.cells = data['cells']
                self.board.find_mines = data['find_mines']
                self.timer = data['timer']
                self.speech.speak(self.phrases['load'])
                for cell in self.board.cells:
                    cell.status = 0 if 9 != cell.status else cell.status
                self.board.calc_around_cells()
                self.player.speak()
Exemple #34
0
    def __init__(self, config_provider, disk, display, replay):
        self.config_provider = config_provider
        self.disk = disk
        self.display = display
        self.replay = replay

        # cameras
        self.cameras = self._create_cameras()
        self.camera_number = 0

        # speech recognition
        self.speech = Speech()
        self.speech.start()
Exemple #35
0
    def populateSpeech(self):
        url = self._build_url({"mode": MenuNavigator.COMMAND_SPEECH_INPUT})
        li = xbmcgui.ListItem(__addon__.getLocalizedString(32200), iconImage=__icon__)
        li.addContextMenuItems([], replaceItems=True)  # Clear the Context Menu
        self._addPlayerToContextMenu(li)  # Add the Sonos player to the menu
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False)

        url = self._build_url({"mode": MenuNavigator.COMMAND_SPEECH_SAVE})
        li = xbmcgui.ListItem(__addon__.getLocalizedString(32203), iconImage=__icon__)
        li.addContextMenuItems([], replaceItems=True)  # Clear the Context Menu
        self._addPlayerToContextMenu(li)  # Add the Sonos player to the menu
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False)

        # Add a blank line before the filters
        li = xbmcgui.ListItem("", iconImage=__icon__)
        li.addContextMenuItems([], replaceItems=True)
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, url="", listitem=li, isFolder=False)

        # Create the speech class (Not going to call the Sonos System do no need for the device)
        speech = Speech()
        phrases = speech.loadSavedPhrases()
        del speech

        # Loop through all the phrases and add them to the screen
        for phrase in phrases:
            url = self._build_url(
                {"mode": "action", "action": ActionManager.ACTION_SPEECH_SAY_PHRASE, "itemId": phrase}
            )
            li = xbmcgui.ListItem(phrase, iconImage=__icon__)
            # Add the remove button to the context menu
            cmd = self._build_url(
                {"mode": "action", "action": ActionManager.ACTION_SPEECH_REMOVE_PHRASE, "itemId": phrase}
            )
            ctxtMenu = []
            ctxtMenu.append((__addon__.getLocalizedString(32204), "RunPlugin(%s)" % cmd))
            li.addContextMenuItems(ctxtMenu, replaceItems=True)  # Clear the Context Menu
            xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=url, listitem=li, isFolder=False)

        xbmcplugin.endOfDirectory(self.addon_handle)
Exemple #36
0
IO.pinMode(REDPIN, IO.OUTPUT)
IO.pinMode(YELPIN, IO.OUTPUT)
IO.pinMode(GRNPIN, IO.OUTPUT)
IO.pinMode(SRNPIN, IO.OUTPUT)
IO.pinMode(BTNPIN, IO.INPUT)

# audio, maps to existing pwm channel for line out audio jack
IO.pinMode(AUDIOPIN, IO.PWM_OUTPUT)

# Set PWM range to 100 (duty cycle can be 0-100)
wiringpi.softPwmCreate(REDPIN, 0, 100)
wiringpi.softPwmCreate(YELPIN, 0, 100)
wiringpi.softPwmCreate(GRNPIN, 0, 100)

LCD = Lcd(LCD_ROWS, LCD_CHARS, LCD_BITS, PIN_LCD_RS, PIN_LCD_E, PINS_LCD_DB)
SPEECH = Speech()

# Siren state machine functions
def siren_on (fsm):
    """Turn on Siren"""
    IO.digitalWrite(SRNPIN, IO.HIGH)
    time.sleep(1.7)

def siren_off (fsm):
    """Turn off Siren"""
    IO.digitalWrite(SRNPIN, IO.LOW)
    time.sleep(0.5)

# Button state machine functions
def button_up (fsm):
    """Button is not pressed/ up"""
Exemple #37
0
 def shutdown(self):
     self.display_text('Shutting down...')
     speech = Speech()
     speech.play_sound('sounds/Sad_R2D2.mp3')
     os.system("shutdown now -h")
Exemple #38
0
 def restart_raspie(self):
     speech = Speech()
     speech.play_sound('sounds/Very_Excited_R2D2.mp3')
     gpio.cleanup()
     python = sys.executable
     os.execl(python, python, * sys.argv)
Exemple #39
0
 def key_control(self, q_state):
     q_state.put('open')
     while True:
         if not q_state.empty():
             close = q_state.get()
             if close == 'exit':
                 print 'exiting key_control...'
                 break
             else:
                 pass
         for event in pygame.event.get():
             if event.type == pygame.KEYDOWN and event.key == pygame.K_POWER:
                 self.shutdown()
             if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
                 self.display_text('Closing raspie...')
                 q_state.put('exit')
                 gpio.cleanup()
                 time.sleep(2)
                 sys.exit()
             if event.type == pygame.KEYUP and event.key == pygame.K_2:
                 autopilot_process = Process(target=self.autopilot_process, args=(q_state,))
                 autopilot_process.start()
                     
             if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
                 print 'Cleaning up gpio'
                 gpio.cleanup()
             if event.type == pygame.KEYDOWN and event.key == pygame.K_4:
                 text = "Co słychać?"
                 speech = Speech()
                 speech.create_voice(text)
                 self.display_text(text)
             if event.type == pygame.KEYDOWN and event.key == pygame.K_5:
                 text = "Let's dance!"
                 speech = Speech()
                 speech.create_voice(text)
                 self.display_text(text)
                 self.run_left_start()
                 time.sleep(1)
                 self.run_left_stop()
                 self.run_right_start()
                 time.sleep(1)
                 self.run_right_stop()
                 self.run_up_start()
                 time.sleep(1)
                 self.run_up_stop()
                 self.run_down_start()
                 time.sleep(1)
                 self.run_down_stop()
             if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
                 self.run_up_start()
             elif event.type == pygame.KEYUP and event.key == pygame.K_UP:
                 self.run_up_stop()
             if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
                 self.run_down_start()
             elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
                 self.run_down_stop()
             if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
                 self.run_left_start()
             elif event.type == pygame.KEYUP and event.key == pygame.K_LEFT:
                 self.run_left_stop()
             if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
                 self.run_right_start()
             elif event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:
                 self.run_right_stop()
Exemple #40
0
def welcome():
    print "started..."
    speech = Speech()
    speech.play_sound('sounds/Processing_R2D2.mp3')
Exemple #41
0
class Edit:

    # initialise
    def __init__(self, config_provider, disk, display, replay):
        self.config_provider = config_provider
        self.disk = disk
        self.display = display
        self.replay = replay

        # cameras
        self.cameras = self._create_cameras()
        self.camera_number = 0

        # speech recognition
        self.speech = Speech()
        self.speech.start()

    # create cameras
    def _create_cameras(self):

        # note: configure camera names to match speech recognition 
        camera_names = self.config_provider.edit_camera_names.split(',')

        cameras = []

        for camera_number in range(self.config_provider.number_of_cameras):
            cameras.append(camera_names[camera_number])

        return cameras

    # edit frame
    def frame(self, frame_number):

        # get camera name using speech recognition
        camera_name = self.speech.get_current_speech()

        # get camera number from camera name
        if camera_name in self.cameras:
            self.camera_number = self.cameras.index(camera_name) 

        # apply frame delay
        sleep(self.config_provider.frame_delay)

        # load frame from disk
        frame = self.disk.load_frame(self.config_provider.edit_load_from, self.camera_number, frame_number, self.config_provider.frame_format)

        # ensure frame loaded from disk
        if frame is None:
            return False

        # replay record
        if self.config_provider.edit_display_record:
            self.replay.record(frame_number, self.disk, self.config_provider.number_of_cameras, self.config_provider.edit_load_from, self.config_provider.frame_format)

        # display frame
        if self.config_provider.edit_display_frame:
            self.display.frame(frame)

        # save frame to disk
        self.disk.save_frame(frame, self.config_provider.edit_save_to, None, frame_number, self.config_provider.frame_format)

        return True
Exemple #42
0
 def removePhrase(self, phrase):
     speech = Speech(self.sonosDevice)
     speech.removePhrase(phrase)
     del speech
     # Refresh the screen now that an item has been removed
     xbmc.executebuiltin("Container.Refresh")
Exemple #43
0
 def setUp(self):
     """-"""
     audio_dir = os.path.dirname(os.path.abspath(__file__)) + "/../audio"
     self.speech_test = Speech(audio_dir)
Exemple #44
0
            actionMgr = ActionManager()
            actionMgr.performAction(actionType[0], itemId[0], title)
            del actionMgr

    elif mode[0] == MenuNavigator.COMMAND_CONTROLLER:
        log("SonosPlugin: Mode is launchController")
        xbmc.executebuiltin("ActivateWindow(home)", True)
        xbmc.executebuiltin("RunScript(script.sonos)")

    elif mode[0] == MenuNavigator.COMMAND_SPEECH_INPUT:
        log("SonosPlugin: Mode is Speech Input")
        sonosDevice = Sonos.createSonosDevice()
        # Make sure a Sonos speaker was found
        if sonosDevice is not None:
            # Create the speech class and prompt the user for the message
            speech = Speech(sonosDevice)
            msg = speech.promptForInput()
            if msg is not None:
                # Now get the Sonos Sytem to say the message
                speech.say(msg)
            del speech
            del sonosDevice

    elif mode[0] == MenuNavigator.COMMAND_SPEECH_SAVE:
        log("SonosPlugin: Mode is Speech Save")
        # Create the speech class and prompt the user for the message
        # (No need for a device to save a message)
        speech = Speech()
        speech.addPhrase()
        # Refresh the screen now that an item has been removed
        xbmc.executebuiltin("Container.Refresh")
Exemple #45
0
from speech import Speech

import subprocess
from PIL import Image
from pytesser import *
import sys
import RPi.GPIO as GPIO
from time import sleep

# specific parameter
# the program is executed after the user pressed the start button on the raspberry pi 
touch_power=2    #
touch_gnd=6      #
touch_signal=18  # Getting high voltages when the user pressed the button
key=1
speech = Speech()

#initalizing GPIO pins on the raspberry pi
GPIO.setmode(GPIO.BCM)
GPIO.setup(touch_signal,GPIO.IN)

# loop forever
while True:
  if GPIO.input(touch_signal)== GPIO.HIGH:
    print(key)
    if key==1:
    
      # taking pictures using the webcam connected to the raspberry pi.
      subprocess.Popen(['sudo','fswebcam','-r','1024X768','-S','20','Pic.jpg'],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
      sleep(2)
      # transform pictures into pure text