Exemplo n.º 1
0
 def calibrate(self, callback):
     Speaker.talk(_("jarvis.initialize.start"))
     with sr.Microphone() as source:
         self.recognizer.adjust_for_ambient_noise(source, 2)
     self.recognizer.dynamic_energy_threshold = True
     Speaker.talk(_("jarvis.initialize.end"))
     callback()
Exemplo n.º 2
0
    def populateScene(self, speakers):
        for i, s in enumerate(speakers):
            speaker = Speaker(s)
            self.add_speaker(speaker)
            speaker.translate(100*i, 0)

        self.update()
Exemplo n.º 3
0
def _speaker(arguments):
    """
    Speaker subcommand callback
    """
    logging.info('Starting Speaker')
    speaker = Speaker()
    speaker.get_google_translation('en', 'Hello World!')
Exemplo n.º 4
0
    def _do_speak_time(self):
        """Speak aloud the current time.
        """

        def gstmessage_cb(bus, message, pipe):
            if message.type in (Gst.MessageType.EOS, Gst.MessageType.ERROR):
                pipe.set_state(Gst.State.NULL)

        if self._time_speaker is None:
            self._time_speaker = Speaker()

        pipeline = 'espeak text="%(text)s" voice="%(voice)s" pitch="%(pitch)s" \
            rate="%(rate)s" gap="%(gap)s" ! autoaudiosink' % {
            'text': self._untag(self._time_in_letters),
            'voice': self._time_speaker.VOICE,
            'pitch': self._time_speaker.PITCH,
            'rate': self._time_speaker.SPEED,
            'gap': self._time_speaker.WORD_GAP}
        try:
            pipe = Gst.parse_launch(pipeline)
            bus = pipe.get_bus()
            bus.add_signal_watch()
            bus.connect('message', gstmessage_cb, pipe)
            pipe.set_state(Gst.State.PLAYING)
        except:
            self._time_speaker.speak(self._untag(self._time_in_letters))
Exemplo n.º 5
0
    def __init__(self,
                 name,
                 color,
                 verbose=True,
                 silent=False,
                 menu_path=None):
        """
        Constructor
        :param name: the bot's name it will use in the dialogues
        :param color: the color the bot will use in the prompt
        :param verbose: whether the bot should print info about
        the command it receives (dependency tree, lemmas info)
        :param silent: if true, then only use print (no text to speech)
        :param menu_path: the path of the stored menu
        """

        self._name = name
        self._speaker = Speaker(rate=150, volume=1)
        self._listener = Listener(mic_index=0)
        self._prompt = colored(f'{self._name}: ', color)
        self._verbose = verbose
        self._silent = silent

        self._frame_stack = []
        self._current_frame = None

        self._is_over = False

        if menu_path is not None:
            self._load_menu(menu_path)
        else:
            self._menu = {"entries": []}

        # when finished setup, welcome user
        self._say(self._welcome())
Exemplo n.º 6
0
def _speaker(arguments):
    """
    Speaker subcommand callback
    """
    logging.info('Starting Speaker')
    speaker = Speaker()
    speaker.get_google_translation('en', 'Hello World!')
Exemplo n.º 7
0
 def __init__(self):
     self.container = Container()
     self._chatReceiver = ChatReceiver()
     self._chatReceiver.init(self.container.config)
     self._stateSaver = StateSaver()
     self._stateComparer = StateComparer()
     self._translateRequester = TranslateRequester(self.container)
     self._speaker = Speaker(self.terminate)
Exemplo n.º 8
0
    def test_should_say(self):
        speaker = Speaker()
        curr_time = time.time()
        long_time_ago = curr_time - 20

        self.assertTrue(speaker.should_say(long_time_ago))

        self.assertFalse(speaker.should_say(curr_time))
Exemplo n.º 9
0
 def __init__(self, dic):
     self.itms = list([(i, dic[i]) for i in dic])
     random.shuffle(self.itms)
     self.cur_idx = 0
     self.queque = [i for i in range(len(self.itms))]
     self.len = len(self.queque)
     self.hint = None
     self.speaker = Speaker()
Exemplo n.º 10
0
 def resume(self):
     self._get_player_status()
     if not self.playing:
         Speaker.talk(_("speak.movie.nothing_played"))
     elif not self.paused:
         Speaker.talk(_("speak.movie.is_not_paused"))
     else:
         self._send("Player.PlayPause", {"playerid": self.player_id})
Exemplo n.º 11
0
	def __init__(self):
		self.mic     = Mic()
		self.speaker = Speaker()
		self.client  = Client()
		self.modem   = Modem()

		self.selectedMod = 'AM'

		self.modulations = {
			'AM': self.modem.modAm,
			'AMSC': self.modem.modAmsc,
			'FM': self.modem.modFm
		}

		self.demodulations = {
			'AM': self.modem.demodAm,
			'AMSC': self.modem.demodAmsc,
			'FM': self.modem.demodFm
		}

		self.fig, self.axes = plt.subplots(4, 1, figsize=[6,8])
		plt.subplots_adjust(top=0.7)
		for i in range(4):
			self.axes[i].axes.xaxis.set_visible(False)
			self.axes[i].axes.yaxis.set_visible(False)

		self.input_ip       = TextBox(plt.axes([0.1,  0.05, 0.4, 0.05]), '', initial='192.168.0.20')
		self.btn_connect    =  Button(plt.axes([0.5,  0.05, 0.2, 0.05]), 'Connect')
		self.btn_disconnect =  Button(plt.axes([0.7,  0.05, 0.2, 0.05]), 'Disconnect')

		self.btn_am   =  Button(plt.axes([0.1,  0.94, 0.2, 0.05]), 'AM')
		self.btn_amsc =  Button(plt.axes([0.3,  0.94, 0.2, 0.05]), 'AMSC')
		self.btn_fm   =  Button(plt.axes([0.5,  0.94, 0.2, 0.05]), 'FM')

		self.sld_cutoff     = Slider(plt.axes([0.1,  0.91, 0.7, 0.02]), 'Cutoff',  1.,    2000.,  valinit=1000,   valstep=1.)
		self.sld_order      = Slider(plt.axes([0.1,  0.87, 0.7, 0.02]), 'Order',   2,     50,     valinit=5,      valstep=1)
		self.sld_fm_carrier = Slider(plt.axes([0.1,  0.83, 0.7, 0.02]), 'FM Freq', 3000., 20000., valinit=10000., valstep=100.)
		self.sld_fm_devsiat = Slider(plt.axes([0.1,  0.79, 0.7, 0.02]), 'FM Desv', 300.,  4000.,  valinit=1000.,  valstep=10.)
		self.sld_am_carrier = Slider(plt.axes([0.1,  0.75, 0.7, 0.02]), 'AM Freq', 3000., 20000., valinit=3000.,  valstep=100.)

		self.btn_am.on_clicked(self.selectAM)
		self.btn_amsc.on_clicked(self.selectAMSC)
		self.btn_fm.on_clicked(self.selectFM)

		self.btn_connect.on_clicked(self.connect)
		self.btn_disconnect.on_clicked(self.disconnect)

		self.sld_cutoff.on_changed(self.changeCutoff)
		self.sld_order.on_changed(self.changeOrder)
		self.sld_fm_carrier.on_changed(self.changeFmCarrier)
		self.sld_fm_devsiat.on_changed(self.changeFmDevsiat)
		self.sld_am_carrier.on_changed(self.changeAmCarrier)

		plt.show()
 def __init__(self):
     self.spoken_words = None
     self.speaker = Speaker()
     self.doc = None
     self.recognizers = []
     self.recognizers.append(RecognizerSimple())
     self.recognizers.append(RecognizerSimpleMath())
     self.recognizers.append(RecognizerNamedEntities())
     self.recognizers.append(RecognizerTime())
     self.nlp = spacy.load("en_core_web_sm")
     self.answer = utilities.DAVE_STANDARD_ANSWER
Exemplo n.º 13
0
    def parse_speakers(self):
        for person in self.tree.getroot().find('Speakers').findall('Speaker'):
            speaker_id = person.attrib['id'].strip()
            speaker_name = person.attrib['name'].strip()
            speaker_code = BLLConstants.SPEAKER_CODES.get_option(speaker_name)
            self.speakers[speaker_id] = Speaker(speaker_id, speaker_code)

            if self.speakers[speaker_id].codeinfo is None:
                de('Unrecognized speaker code: ', speaker_name)
            else:
                self.speakers[speaker_id] = Speaker(speaker_id, speaker_code)
Exemplo n.º 14
0
    def call_function(self, data):
        data = data.lower()

        if _("command.weather") in data:
            Speaker.talk(self.weather.get_one_day())
        elif data == _('command.film.pause'):
            self.kodi.pause()
        elif data == _("command.film.resume") or data == _(
                "command.film.play"):
            self.kodi.resume()
        elif data == _("command.film.status"):
            self.kodi.film_status()
        elif _("command.date.hour") in data:
            self.calendar.get_time()
        else:
            Speaker.talk(_("speak.command.unknown"))
Exemplo n.º 15
0
    def __init__(self, number_of_pixels):
        self.strip = neopixel.NeoPixel(NEOPIXEL_PIN,
                                       number_of_pixels,
                                       brightness=1,
                                       auto_write=False)

        enable = DigitalInOut(POWER_PIN)
        enable.direction = Direction.OUTPUT
        enable.value = False
        switch = DigitalInOut(SWITCH_PIN)
        switch.direction = Direction.INPUT
        switch.pull = Pull.UP

        red_led = pulseio.PWMOut(board.D11, duty_cycle=0, frequency=20000)
        green_led = pulseio.PWMOut(board.D12, duty_cycle=0, frequency=20000)
        blue_led = pulseio.PWMOut(board.D13, duty_cycle=0, frequency=20000)

        self.powerButton = PowerButton(enable, switch, red_led, green_led,
                                       blue_led)

        # Set up accelerometer on I2C bus, 4G range:
        i2c = busio.I2C(board.SCL, board.SDA)
        accel = adafruit_lis3dh.LIS3DH_I2C(i2c)
        accel.range = adafruit_lis3dh.RANGE_4_G
        self.accelerometer = accel

        self.speaker = Speaker(audioio.AudioOut(SPEAKER_PIN), audioio)
Exemplo n.º 16
0
 def __init__(self, address, handler, engine='outloud', rate=75):
     """Initialize HTTP listener."""
     HTTPServer.__init__(self, address, handler)
     self.speaker = Speaker(engine, 'localhost', {
         'punctuations': 'some',
         'rate': rate
     })
Exemplo n.º 17
0
def read_transcription(file, Speaker_list, Speech_segmetns):
    for string in file:
        str = string.split(" ", 1)
        if str[0] == "<Speaker":
            Speaker_list.append(Speaker(str[1]))
        if str[0] == "<SpeechSegment":
            Speech_segmetns.append(Speech_Segment(str[1]))
        if str[0] == "<Word":
            Speech_segmetns[-1].words.append(Word(str[1]))
Exemplo n.º 18
0
def infer_speaker(env, tok):
    import tqdm
    from utils import load_datasets
    listner = Seq2SeqAgent(env, "", tok, args.maxAction)
    speaker = Speaker(env, listner, tok)
    speaker.load(args.load)

    dataset = load_datasets(env.splits)
    key_map = {}
    for i, item in enumerate(dataset):
        key_map[item["path_id"]] = i
    path2inst = speaker.get_insts(wrapper=tqdm.tqdm)
    for path_id in path2inst.keys():
        speaker_pred = tok.decode_sentence(path2inst[path_id])
        dataset[key_map[path_id]]['instructions'] = [speaker_pred]

    with open("tasks/R2R/data/aug_paths_unseen_infer.json", "w") as f:
        json.dump(dataset, f, indent=4, sort_keys=True)
Exemplo n.º 19
0
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__speaker__ Test'
            },
        }

        self.api = Speaker(client_args=client_args)
Exemplo n.º 20
0
def construct_training_scene():
    speaker = Speaker(Vec2(0, 0))
    scene = Scene(3)

    table = Landmark(
        'table',
        RectangleRepresentation(
            rect=BoundingBox([Vec2(-0.4, 0.4), Vec2(0.4, 1.0)])), None,
        ObjectClass.TABLE)

    obj1 = Landmark(
        'green_cup',
        RectangleRepresentation(rect=BoundingBox(
            [Vec2(0.05 - 0.035, 0.9 - 0.035),
             Vec2(0.05 + 0.035, 0.9 + 0.035)]),
                                landmarks_to_get=[]), None, ObjectClass.CUP,
        Color.GREEN)

    obj2 = Landmark(
        'blue_cup',
        RectangleRepresentation(rect=BoundingBox(
            [Vec2(0.05 - 0.035, 0.7 - 0.035),
             Vec2(0.05 + 0.035, 0.7 + 0.035)]),
                                landmarks_to_get=[]), None, ObjectClass.CUP,
        Color.BLUE)

    obj3 = Landmark(
        'pink_cup',
        RectangleRepresentation(rect=BoundingBox(
            [Vec2(0 - 0.035, 0.55 - 0.035),
             Vec2(0 + 0.035, 0.55 + 0.035)]),
                                landmarks_to_get=[]), None, ObjectClass.CUP,
        Color.PINK)

    obj4 = Landmark(
        'purple_prism',
        RectangleRepresentation(rect=BoundingBox(
            [Vec2(-0.3 - 0.03, 0.7 - 0.05),
             Vec2(-0.3 + 0.03, 0.7 + 0.05)]),
                                landmarks_to_get=[]), None, ObjectClass.PRISM,
        Color.PURPLE)

    obj5 = Landmark(
        'orange_prism',
        RectangleRepresentation(rect=BoundingBox(
            [Vec2(0.3 - 0.03, 0.7 - 0.05),
             Vec2(0.3 + 0.03, 0.7 + 0.05)]),
                                landmarks_to_get=[]), None, ObjectClass.PRISM,
        Color.ORANGE)

    scene.add_landmark(table)

    for obj in (obj1, obj2, obj3, obj4, obj5):
        obj.representation.alt_representations = []
        scene.add_landmark(obj)

    return scene, speaker
Exemplo n.º 21
0
 def display_speakers(self):
     liste_of_dicto=self.model.get_all_speakers()
     str_of_display=""
     
     for dicto in (liste_of_dicto):
         if dicto["statut"]:
             speaker = Speaker(dicto)
             str_of_display += "<p>" + str(speaker)  + "</p>"
     return str_of_display
Exemplo n.º 22
0
	def __init__(self, config, **kargs):
		super(PahoSpeaker, self).__init__(
			topic_sub = config['Paho']['MQTT_TOPIC_SUB'],
			ca = config['Paho']['CA_ROOT_CERT_FILE'],
			cert = config['Paho']['THING_CERT_FILE'],
			key = config['Paho']['THING_PRIVATE_KEY'],
			host = config['Paho']['MQTT_HOST'],
			port = config['Paho']['MQTT_PORT'],
			keepalive = config['Paho']['MQTT_KEEPALIVE_INTERVAL'],
			logging = kargs['logging']
		)
		self.speaker = Speaker(
			key = config['Aws']['ACCESS_KEY'],
			secret = config['Aws']['SECRET_KEY'],
			logging = kargs['logging'],
			on_speak = self._on_speak
		)

		self.topic_pub = config['Paho']['MQTT_TOPIC_PUB']
Exemplo n.º 23
0
 def __init__(self):
     self.recognizer = Recognition()  # 语音识别
     self.nlu = Nlu()  # 语义识别
     self.speaker = Speaker()  # 语音合成
     self.music_player = Music_Player()  # 音乐播放器
     self.weather = Weather(self.speaker)  # 查询天气功能
     self.chat = Chat(self.speaker)  # 闲聊功能
     self.ticket = Ticket(self.speaker)  # 查询车票功能
     self.noun = Noun(self.speaker)  # 名词解释功能
     self.music = Music(self.speaker, self.music_player)  # 播放音乐功能
Exemplo n.º 24
0
    def display(self):
        liste_of_dicto=self.model.get_all()
        str_of_display=""
        
        for dicto in (liste_of_dicto):

            speaker = Speaker(dicto)
            conference = Conference(dicto)
            str_of_display += "<p>"+(str(speaker)+" a animer "+str(conference))+"</p>"
        return str_of_display
Exemplo n.º 25
0
    def __init__(self):
        self._speaker = Speaker()
        self._ifttt = Ifttt({"api_key": config.IFTTT_APIKEY})

        self._status = StatusManager()
        self._actions = [
            Yureyure(self._speaker),
            Hello(self._speaker),
            Joke(self._speaker),
            TimeSignal(self._speaker),
        ]
        self._blow_actions = [
            # よわい
            Soyosoyo(self._speaker),
            # 横揺れ
            Yurayura(self._speaker),
            # 波
            Byubyu(self._speaker)
        ]
        self._blow_action_index = 1
Exemplo n.º 26
0
    def test_processing(self):

        logging.debug('*** Processing test ***')

        outbox = Queue()
        outbox.put('hello')
        outbox.put('world')
        outbox.put(Exception('EOQ'))

        mouth = Queue()

        context = Context()
        speaker = Speaker(outbox, mouth)
        speaker.work(context)

        self.assertEqual(mouth.get(), 'hello')
        self.assertEqual(mouth.get(), 'world')
        with self.assertRaises(Exception):
            mouth.get_nowait()
        with self.assertRaises(Exception):
            outbox.get_nowait()
Exemplo n.º 27
0
def get_output(mode, guide_tolerance, guide_delay):
    guide = None
    # guide_tolerance = 0.15
    # guide_delay = 0
    if mode == "speaker":
        guide = Speaker(tolerance=guide_tolerance, delay=guide_delay)
    elif mode == "beeper":
        guide = Beeper(tolerance=guide_tolerance, delay=guide_delay)
    elif mode == "chirp":
        guide = Chirp(tolerance=guide_tolerance, delay=guide_delay)

    return guide
Exemplo n.º 28
0
    def getSpeakers(self):
        query = 'SELECT * FROM speakers'
        speakers = Database.connectDB(self, query)

        speaker_list = []

        for i in range(len(speakers)):
            speaker_list.append(
                Speaker(speakers[i][0], speakers[i][1], speakers[i][2],
                        speakers[i][3], speakers[i][4], speakers[i][5],
                        speakers[i][6], speakers[i][7], speakers[i][8]))
        return speaker_list
Exemplo n.º 29
0
def valid_speaker(tok, val_envs):
    import tqdm
    listner = Seq2SeqAgent(None, "", tok, args.maxAction)
    speaker = Speaker(None, listner, tok)
    speaker.load(os.path.join(log_dir, 'state_dict', 'best_val_seen_bleu'))
    # speaker.load(os.path.join(log_dir, 'state_dict', 'best_val_unseen_loss'))

    for args.beam in [False, True]:
        print("Using Beam Search %s" % args.beam)
        for env_name, (env, evaluator) in val_envs.items():
            if env_name == 'train':
                continue
            print("............ Evaluating %s ............." % env_name)
            speaker.env = env
            path2inst, loss, word_accu, sent_accu = speaker.valid(
                beam=args.beam, wrapper=tqdm.tqdm)
            path_id = next(iter(path2inst.keys()))
            print("Inference: ", tok.decode_sentence(path2inst[path_id]))
            print("GT: ", evaluator.gt[path_id]['instructions'])
            bleu_score, precisions, _ = evaluator.bleu_score(path2inst)
            print(
                "Bleu, Loss, Word_Accu, Sent_Accu for %s is: %0.4f, %0.4f, %0.4f, %0.4f"
                % (env_name, bleu_score, loss, word_accu, sent_accu))
            print(
                "Bleu 1: %0.4f Bleu 2: %0.4f, Bleu 3 :%0.4f,  Bleu 4: %0.4f" %
                tuple(precisions))
            print("Average Length %0.4f" % utils.average_length(path2inst))
Exemplo n.º 30
0
class Server():
  def __init__(self, master):
    self.netToAudio = NetToAudio()
    self.speaker = Speaker()
    self.master = master

  def listenTo(self, theSocket):
    self.speaker.init()
    self.recvFrom(theSocket)
    self.speaker.destroy()

  def listen(self):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    host = "0.0.0.0"
    s.bind((host, Config.port))
    self.listenTo(s)

  def recvFrom(self, socket):
    print "Listening on ".format(socket.getsockname())
    while True:
      chunk = self.readChunk(socket)
      audio = self.netToAudio.convert(chunk)
      self.speaker.play(audio)

  def readChunk(self, socket):
    data, addr = socket.recvfrom(Config.net_chunksize)
    self.master.callOn(addr)
    return data
Exemplo n.º 31
0
class Test:
    def __init__(self, dic):
        self.itms = list([(i, dic[i]) for i in dic])
        random.shuffle(self.itms)
        self.cur_idx = 0
        self.queque = [i for i in range(len(self.itms))]
        self.len = len(self.queque)
        self.hint = None
        self.speaker = Speaker()
    def get_quest(self, idx):
        return self.itms[idx][1]
    def get_ans(self, idx):
        return self.itms[idx][0]
    def sayAnswer(self):
        self.speaker.say(self.get_ans(self.cur_idx))
    def ask(self):
        if len(self.queque)>0:
            self.cur_idx = self.queque[0]
            del self.queque[0]
            return self.get_quest(self.cur_idx)
        else:
            return None
    def get_hint(self):
        if self.hint == None:
            idx = 0
        else:
            idx = None
        self.hint = hint(self.get_ans(self.cur_idx), self.hint, idx)
        return self.hint
    def is_right_ans(self, ans):
        if self.get_ans(self.cur_idx) == ans:
            self.hint  = False
            return True
        else:
            if len(self.queque)>0:
                if self.queque[-1]!=self.cur_idx:
                    self.queque.append(self.cur_idx)
            else:
                self.queque.append(self.cur_idx)
            return False
Exemplo n.º 32
0
class Drowner:
    def __init__(self, db):
        self.db = db
        self.searcher = YouTubeSearcher()
        self.player = Player()
        self.speaker = Speaker()
        return

    def drown(self, keyword=None):
        if keyword:
            id = self.searcher.search(keyword)
            if id:
                print id
                self.db.register_music(keyword, id)
                self.player.play(id)
        else:
            row = self.db.fetch_music_randomly()
            id = row["url"]
            address = row["address"]
            self.speaker.speak(address + u"のトイレからです")
            self.player.play(id)
        return
Exemplo n.º 33
0
def get_lectures():
    if 'speaker_id' in request.args:
        _speaker_id = int(request.args['speaker_id'])
        _speaker = Speaker.get(_speaker_id)
        if _speaker:
            _lecture = _speaker.lecture
            if _lecture:
                return jsonify({'speaker': _speaker, 'lecture': _lecture})
            else:
                abort(404)
        else:
            abort(404)
    return jsonify({'lectures': lectures})
Exemplo n.º 34
0
    def next(self):  #starts the function to train the model

        model = Speech()
        model.expend_data()
        model.read_data()
        model.preprocess_labels()
        model.preprocess_data()
        model.train(10, 4, 1, 1000)

        model2 = Speaker()
        model2.audio_to_image()
        model2.preprocess()
        model2.train()

        self.switch_window.emit()
Exemplo n.º 35
0
class SpeakerAPITestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__speaker__ Test'
            },
        }

        self.api = Speaker(client_args=client_args)


    def test_issue_gender_recognition_task(self):
        """
            Test Speaker issue_gender_recognition_task works.
        """
        try:
            response = self.api.issue_gender_recognition_task()
            assert 'task_id' in response
        except Exception, e:
            e is SpeakerError
    def __init__(self):
        Follwer.__init__(self)
        self.state = State.NORMAL
        self.recognizer = SpeechRecognizer()
        self.follow(self.recognizer)
        self.answer = str()
        self.recommend_packages = []
        self.interesting_package = None

        Speaker.speak('Please tell your phone number.')
        number = raw_input('Phone number : ')
        self.current_user = Database.find_one('customers', 'phone_number', number)
        self.user_account = Database.find_user_account(self.current_user.id)
        # If phone no is exist, Greeting
        if self.current_user is not None:
            Speaker.speak('Good morning mister %s. How can i help you.' % self.current_user.fullname())
            self.recognizer.start()
        # Otherwise, Goodbye
        else:
            Speaker.speak('Sorry. Your number is not in our system.')
Exemplo n.º 37
0
bitdepth = sampwidth * 8

frames = wav.readframes(frames_chunk * nchannels)

wav.close()

data = {
        'audio_sequence': 1,
        'audio_samplerate': framerate,
        'audio_bitdepth': bitdepth,
        'audio_channels': nchannels,
        'audio_sent_frames': frames_chunk,
        'frames': frames,
}

api = Speaker()

print("Feeding %s audio frames to WS" % (frames_chunk))
response = api.issue_gender_recognition_task(**data)

print("Service replied with status code [%s]" % (response['status_code']))

result_in = response['new_result_in']
task_id = response['task_id']

print("Waiting %s secs to ask for response" % (result_in))

time.sleep(result_in)

data = {
    'task_id': task_id}
Exemplo n.º 38
0
import configs
import webserver
from dictionary import DictLookup

def ask(s):
    return str(raw_input(str(s) + "\n> "))

print "Starting scrabble vision..."
sv = ScrabbleVision()
sv.start()
while not sv.started:
    pass
print "Scrabble vision started. Ready."

print "Starting speaker..."
voice = Speaker()
voice.start()

PICKLE_FILENAME = "game.state"

if len(sys.argv) == 2:
    filename = sys.argv[1] 
    (scoreboard, game_board) = pickle.load( open(filename, "rb") )
    print "Game recovered from file"
    voice.say("Resuming game!")
else:
    #Find out our players
    player_count = int(ask("How many players?"))
    player_list = []
    for i in range(1, player_count+1):
        x = ask("What is Player %d's name?"% i)    
Exemplo n.º 39
0
Arquivo: run.py Projeto: echan3/bolt
import adapter

if __name__ == '__main__':
    # poi = Vec2(float(sys.argv[1]), 0)
    # l = LineRepresentation()

    # f = l.get_line_features(poi)

    # print 'dist_start = {dist_start}, dist_end = {dist_end}, dist_mid = {dist_mid}'.format(**f)
    # print 'dir_start = {dir_start}, dir_end = {dir_end}, dir_mid = {dir_mid}'.format(**f)

    # print 'Distance from POI to Start landmark is %f' % l.landmarks['start'].distance_to(poi)
    # print 'Distance from POI to End landmark is %f' % l.landmarks['end'].distance_to(poi)
    # print 'Distance from POI to Mid landmark is %f' % l.landmarks['mid'].distance_to(poi)

    speaker = Speaker(Vec2(5.5,4.5))
    scene = Scene(3)

    table = Landmark('table',
                 RectangleRepresentation(rect=BoundingBox([Vec2(5,5), Vec2(6,7)])),
                 None,
                 Landmark.TABLE)

    obj1 = Landmark('obj1',
                 RectangleRepresentation(rect=BoundingBox([Vec2(5,5), Vec2(5.1,5.1)])),
                 None,
                 Landmark.CUP)

    obj2 = Landmark('obj2',
                 RectangleRepresentation(rect=BoundingBox([Vec2(5.5,6), Vec2(5.6,6.1)])),
                 None,
Exemplo n.º 40
0
 def __init__(self, master):
   self.netToAudio = NetToAudio()
   self.speaker = Speaker()
   self.master = master
Exemplo n.º 41
0
import logging
import threading
import RPi.GPIO as GPIO

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(asctime)s %(message)s',
                    )

scaring = threading.Event()
doneplaying = threading.Event()
closedevent = threading.Event()
closedevent.set()
openevent = threading.Event()

light = Light(args=('74:DA:EA:90:FD:87',))
spk = Speaker(args=('/home/pi/sounds',doneplaying))

eyes = Eyes(args=(), kwargs={'lefteye': 12, 'righteye': 13})

def open_callback():
    logging.info('Open callback')
    openevent.set()

    if scaring.is_set():
        spk.cancel()

    # threading.Timer(5, lambda: eyes.turnoff()).start()
    eyes.turnoff()
    light.fullon()
    
def close_callback():
Exemplo n.º 42
0
class ClockActivity(activity.Activity):
    """The clock activity displays a simple clock widget.
    """

    def __init__(self, handle):
        """Create and initialize the clock activity.
        """
        super(ClockActivity, self).__init__(handle)

        # TRANS: Title of the activity
        self.set_title(_('What Time Is It?'))

        # TRANS: The format used when writing the time in full
        # letters.  You must take care to use a font size large enough
        # so that kids can read it easily, but also small enough so
        # that all times combination fit on the screen, even when the
        # screen is rotated.  Pango markup:
        # http://www.pygtk.org/docs/pygtk/pango-markup-language.html
        self._TIME_LETTERS_FORMAT = _('<markup>\
<span lang="en" font_desc="Sans 20">%s</span></markup>')

        # TRANS: The format used to display the weekday and date
        # (example: Tuesday 10/21/2008) We recommend to use the same
        # font size as for the time display.  See
        # http://docs.python.org/lib/module-time.html for available
        # strftime formats.  xgettext:no-python-format
        self._DATE_SHORT_FORMAT = _('<markup>\
<span lang="en" font_desc="Sans 20">\
<span foreground="#B20008">%A</span>, \
<span foreground="#5E008C">%m</span>/\
<span foreground="#B20008">%d</span>/\
<span foreground="#9A5200">%Y</span></span></markup>')

        # Should we write the time in full letters?
        self._time_writer = None
        self._time_in_letters = self.get_title()
        self._time_letters = None
        self._date = None
        self._time_speaker = None

        self._write_time = False
        self._speak_time = False
        self._write_date = False
        self._display_mode_buttons = []

        self._make_display()
        self._make_toolbars()

        # Show the activity on the screen
        self.show_all()

        # We want to be notified when the minutes change
        self._clock.connect("time_minute", self._minutes_changed_cb)

        if not self.powerd_running():
            try:
                bus = dbus.SystemBus()
                proxy = bus.get_object('org.freedesktop.ohm',
                                       '/org/freedesktop/ohm/Keystore')
                self.ohm_keystore = dbus.Interface(
                    proxy, 'org.freedesktop.ohm.Keystore')
            except dbus.DBusException:
                self.ohm_keystore = None

    def write_file(self, file_path):
        self.metadata['write-time'] = str(self._write_time)
        self.metadata['write-date'] = str(self._write_date)
        self.metadata['speak-time'] = str(self._speak_time)
        self.metadata['clock-mode'] = str(self._clock._mode)
        logging.debug('Saving metadata %s', (self.metadata['write-time'],
                      self.metadata['write-date'], self.metadata['speak-time'],
                      self.metadata['clock-mode']))
        # Need write a empty file or the read_file is not called
        with open(file_path, 'w') as data:
            data.write('')

    def read_file(self, file_path):
        logging.debug('Reading metadata %s', (self.metadata['write-time'],
                      self.metadata['write-date'], self.metadata['speak-time'],
                      self.metadata['clock-mode']))
        if 'clock-mode' not in self.metadata.keys():
            display_mode = _MODE_SIMPLE_CLOCK
        else:
            display_mode = int(self.metadata['clock-mode'])

        if 'write-time' in self.metadata.keys():
            self._write_time = str(self.metadata['write-time']) == 'True'

        if 'speak-time' in self.metadata.keys():
            self._speak_time = str(self.metadata['speak-time']) == 'True'

        if 'write-date' in self.metadata.keys():
            self._write_date = str(self.metadata['write-date']) == 'True'

        logging.debug('Read values %s', (self._write_time,
                      self._speak_time, self._write_date,
                      display_mode))

        # apply the changes in the UI
        self._display_mode_buttons[display_mode].set_active(True)
        self._write_time_btn.set_active(self._write_time)
        self._write_date_btn.set_active(self._write_date)
        self._speak_time_btn.set_active(self._speak_time)

    def powerd_running(self):
        self.using_powerd = os.access(POWERD_INHIBIT_DIR, os.W_OK)
        return self.using_powerd

    def _inhibit_suspend(self):
        if self.using_powerd:
            fd = open(POWERD_INHIBIT_DIR + "/%u" % os.getpid(), 'w')
            fd.close()
            return True

        if self.ohm_keystore is not None:
            try:
                self.ohm_keystore.SetKey('suspend.inhibit', 1)
                return self.ohm_keystore.GetKey('suspend.inhibit')
            except dbus.exceptions.DBusException:
                return False
        else:
            return False

    def _allow_suspend(self):
        if self.using_powerd:
            os.unlink(POWERD_INHIBIT_DIR + "/%u" % os.getpid())
            return True

        if self.ohm_keystore is not None:
            try:
                self.ohm_keystore.SetKey('suspend.inhibit', 0)
                return self.ohm_keystore.GetKey('suspend.inhibit')
            except dbus.exceptions.DBusException:
                return False
        else:
            return False

    def _make_toolbars(self):
        """Prepare and set the toolbars of the activity.

        Load and show icons. Associate them to the call back methods.
        """
        self.max_participants = 1
        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_button.show()
        toolbar_box.toolbar.insert(activity_button, 0)

        self._add_clock_controls(toolbar_box.toolbar)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_size_request(0, -1)
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        toolbar_box.toolbar.insert(StopButton(self), -1)

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()
        return toolbar_box

    def _add_clock_controls(self, display_toolbar):

        # First group of radio button to select the type of clock to display
        button1 = RadioToolButton(icon_name="simple-clock")
        button1.set_tooltip(_('Simple Clock'))
        button1.connect("toggled", self._display_mode_changed_cb,
                        _MODE_SIMPLE_CLOCK)
        display_toolbar.insert(button1, -1)
        self._display_mode_buttons.append(button1)
        button2 = RadioToolButton(icon_name="nice-clock",
                                  group=button1)
        button2.set_tooltip(_('Nice Clock'))
        button2.connect("toggled", self._display_mode_changed_cb,
                        _MODE_NICE_CLOCK)
        display_toolbar.insert(button2, -1)
        self._display_mode_buttons.append(button2)
        button3 = RadioToolButton(icon_name="digital-clock",
                                  group=button1)
        button3.set_tooltip(_('Digital Clock'))
        button3.connect("toggled", self._display_mode_changed_cb,
                        _MODE_DIGITAL_CLOCK)
        display_toolbar.insert(button3, -1)
        self._display_mode_buttons.append(button3)

        # A separator between the two groups of buttons
        separator = Gtk.SeparatorToolItem()
        separator.set_draw(True)
        display_toolbar.insert(separator, -1)

        # Now the options buttons to display other elements: date, day
        # of week...  A button in the toolbar to write the time in
        # full letters
        self._write_time_btn = ToggleToolButton("write-time")
        self._write_time_btn.set_tooltip(_('Display time in full letters'))
        self._write_time_btn.connect("toggled", self._write_time_clicked_cb)
        display_toolbar.insert(self._write_time_btn, -1)

        # The button to display the weekday and date
        self._write_date_btn = ToggleToolButton("write-date")
        self._write_date_btn.set_tooltip(_('Display weekday and date'))
        self._write_date_btn.connect("toggled", self._write_date_clicked_cb)
        display_toolbar.insert(self._write_date_btn, -1)

        # Another button to speak aloud the time
        self._speak_time_btn = ToggleToolButton("microphone")
        self._speak_time_btn.set_tooltip(_('Talking clock'))
        self._speak_time_btn.connect("toggled", self._speak_time_clicked_cb)
        display_toolbar.insert(self._speak_time_btn, -1)

        # A separator between the two groups of buttons
        separator = Gtk.SeparatorToolItem()
        separator.set_draw(True)
        display_toolbar.insert(separator, -1)

        # And another button to toggle grabbing the hands
        self._grab_button = ToggleToolButton("grab")
        self._grab_button.set_tooltip(_('Grab the hands'))
        self._grab_button.connect("toggled", self._grab_clicked_cb)
        display_toolbar.insert(self._grab_button, -1)

    def _make_display(self):
        """Prepare the display of the clock.

        The display has two parts: the clock face at the top, and the
        time in full letters at the bottom, when the user selects to
        show it.
        """
        # The clock face
        self._clock = ClockFace()

        # The label to print the time in full letters
        self._time_letters = Gtk.Label()
        self._time_letters.set_no_show_all(True)
        # Following line in ineffective!
        # self._time_letters.set_line_wrap(True)
        # Resize the invisible label so that Gtk will know in advance
        # the height when we show it.
        self._time_letters.set_markup(
            self._TIME_LETTERS_FORMAT % self._time_in_letters)

        # The label to write the date
        self._date = Gtk.Label()
        self._date.set_no_show_all(True)
        self._date.set_markup(
            self._clock.get_time().strftime(self._DATE_SHORT_FORMAT))

        # Put all these widgets in a vertical box
        vbox = Gtk.VBox()
        vbox.pack_start(self._clock, True, True, 0)
        vbox.pack_start(self._time_letters, False, False, 0)
        vbox.pack_start(self._date, False, False, 0)

        # Attach the display to the activity
        self.set_canvas(vbox)
        self._clock.active = True

    def _write_date_clicked_cb(self, button):
        """The user clicked on the "write date" button to display the
        current weekday and date.
        """
        self._write_date = button.get_active()
        if button.get_active():
            self._date.show()
        else:
            self._date.hide()

    def _display_mode_changed_cb(self, radiobutton, display_mode):
        """The user selected a clock display mode (simple clock, nice
        or digital).
        """
        self._clock.set_display_mode(display_mode)
        self._clock.queue_draw()

        is_digital = display_mode == _MODE_DIGITAL_CLOCK

        # Exit grab hands mode if the clock is digital
        if self._clock.grab_hands_mode and is_digital:
            self._grab_button.set_active(False)

        # The hands can't be grabbed in the digital clock mode
        self._grab_button.props.sensitive = not is_digital

    def _write_time_clicked_cb(self, button):
        """The user clicked on the "write time" button to print the
        current time.
        """
        self._write_time = button.get_active()
        if self._write_time:
            self._time_letters.show()
            self._write_and_speak(False)
        else:
            self._time_letters.hide()

    def _speak_time_clicked_cb(self, button):
        """The user clicked on the "speak time" button to hear the
        talking clock.
        """
        self._speak_time = button.get_active()
        self._write_and_speak(self._speak_time)

    def _grab_clicked_cb(self, button):
        """The user clicked on the "grab hands" button to toggle
        grabbing the hands.
        """
        self._clock.change_grab_hands_mode(button.get_active())

    def _minutes_changed_cb(self, clock):
        """Minutes have changed on the clock face: we have to update
        the display of the time in full letters if the user has chosen
        to have it and eventually croak the time.
        """
        # Change time display and talk, if necessary
        self._write_and_speak(True)

        # Update the weekday and date in case it was midnight
        self._date.set_markup(
            clock.get_time().strftime(self._DATE_SHORT_FORMAT))

    def _notify_active_cb(self, widget, event):
        """Sugar notify us that the activity is becoming active or
        inactive.

        When we are inactive, we change the activity status of the
        clock face widget, so that it can stop updating every seconds.
        """
        self._clock.active = self.props.active
        if self.props.active:
            self._inhibit_suspend()
        else:
            self._allow_suspend()

    def _write_and_speak(self, speak):
        # Only update the time in full letters when necessary
        if self._write_time or self._speak_time:
            self._do_write_time()

        # And if requested, say it aloud
        if self._speak_time and speak:
            GObject.idle_add(self._do_speak_time)

    def _do_write_time(self):
        """Translate the time to full letters.
        """
        if self._time_writer is None:
            self._time_writer = TimeWriter()
        hour = self._clock.get_time().hour
        minute = self._clock.get_time().minute
        self._time_in_letters = self._time_writer.write_time(hour, minute)
        self._time_letters.set_markup(
            self._TIME_LETTERS_FORMAT % self._time_in_letters)

    def _do_speak_time(self):
        """Speak aloud the current time.
        """
        if self._time_speaker is None:
            self._time_speaker = Speaker()
        self._time_speaker.speak(self._untag(self._time_in_letters))

    def _untag(self, text):
        """Remove all the tags (pango markup) from a text.
        """
        if text is False or "<" not in text:
            return text
        else:
            result = ""
            for s in re.findall(r"(<.*?>)|([^<>]+)", text):
                result += s[1]
            return result
Exemplo n.º 43
0
 def _do_speak_time(self):
     """Speak aloud the current time.
     """
     if self._time_speaker is None:
         self._time_speaker = Speaker()
     self._time_speaker.speak(self._untag(self._time_in_letters))
Exemplo n.º 44
0
	def __init__(self, message):
		Speaker.__init__(self, message)
		print "In loudspeaker __init__"
		self.message = message
Exemplo n.º 45
0
    win.add_widget(selectSound)

    def on_effect_press(name, value, *largs):
        effect = EffectWidget(list_sound_widget, name, value, pos = random_position(width, height))
        win.add_widget(effect)

    selectEffect = MTOptionWidget(label = 'Effect', label_visible = True, pos = (500, 200))
    x = 0
    for name, value in list_effect:
        effect = MTQuarterButton(label=name, label_visible=True, color=(0.6+x*0.1, 0.1, 0.3))
        effect.connect('on_press', curry(on_effect_press, name, value))
        selectEffect.add_widget(effect)
        x+=1
    win.add_widget(selectEffect)

    speaker = Speaker(manager)
    speaker.connect_right_speaker()
    speaker.connect_left_speaker()

    speaker_widget = SpeakerWidget(list_sound_widget, pos = (win.width / 2, win.height / 2 + 200))
    win.add_widget(speaker_widget)

    def on_sound_press(filename, *largs):
        sound = manager.create(filename)
        sound_widget = SoundWidget(sound, label=sound.soundid, label_visible=True, pos = random_position(width, height))
        list_sound_widget.append(sound_widget)
        win.add_widget(sound_widget)

    x = 0
    for filename in glob(join(sys.argv[len(sys.argv) - 1], '*.wav')):
        option = MTQuarterButton(label=filename, color=(x / 20.,0,x / 10.))
Exemplo n.º 46
0
def speak(phrase):
    """Voicing function"""
    s = Speaker(get_google_voice, play_file_in_mpg123)
    s.voice(phrase)
    def receive(self, msg):
        self.recognizer.stop()      # Pause Speech recognizer

        print('Callcenter receive msg : ' + msg)

        if KeywordProcessing.contains_keyword('exit', msg):
            self.answer = str('Do you want to exit.')
            self.state = State.EXIT_CONFIRM
        elif KeywordProcessing.contains_keyword('reset', msg):
            self.answer = str('How can i help you.')
            self.state = State.NORMAL
        elif KeywordProcessing.contains_keyword('operator', msg):
            self.answer = str('Do you want to talk to operator.')
            self.state = State.TALK_TO_OPERATOR
        elif self.state == State.NORMAL:
            # Package category
            if KeywordProcessing.contains_keyword('package', msg):
                # Recommend package
                if KeywordProcessing.contains_keyword('package_category', msg):
                    package_category = [c for c in KeywordProcessing.keywords['package_category'] if c in msg][0]
                    # Find interesting packages
                    if self.user_account.package.payment == 'prepaid':
                        self.recommend_packages = Database.find_list('prepaids', 'type', package_category)
                    else:
                        self.recommend_packages = Database.find_list('postpaids', 'type', package_category)
                    # Generate answer
                    self.answer = str('We recommend %d packages for you. ' % len(self.recommend_packages))
                    index = 1
                    for package in self.recommend_packages:
                        self.answer += str('package number %d %s . ' % (index, package.name))
                        index += 1
                    self.answer += str('Which one you want to have a detail. Or you want to listen again.')
                    self.state = State.SELECT_PACKAGE   # Change state
                # Current package
                else:
                    self.answer = str('Your current package is %s' % self.user_account.package.description())
                    self.state = State.REPEAT   # Change state

            # How to
            elif KeywordProcessing.contains_keyword('how_to', msg):
                if KeywordProcessing.contains_keyword('topup', msg):
                    self.answer = str('Please select your topup method. Online or phone.')
                    self.state = State.SELECT_TOPUP_METHOD
                elif KeywordProcessing.contains_keyword('pay', msg):
                    self.answer = str('Please select your payment method. Online or phone.')
                    self.state = State.SELECT_PAYMENT_METHOD
                elif KeywordProcessing.contains_keyword('setup', msg):
                    self.answer = str('What is your operating system.')
                    self.state = State.SELECT_PHONE_OS

            # Bill category
            elif KeywordProcessing.contains_keyword('balance', msg) or KeywordProcessing.contains_keyword('expire', msg):
                if self.user_account.package.payment == 'postpaid':
                    self.answer = str('Sorry, I don\'t understand your question')
                elif KeywordProcessing.contains_keyword('balance', msg):
                    self.answer = self.user_account.report()
                    self.state = State.REPEAT
                elif KeywordProcessing.contains_keyword('expire', msg):
                    self.answer = str('Your account will expire on %s %s %s.' % (self.user_account.expiration_date.strftime('%d'), self.user_account.expiration_date.strftime('%B'), self.user_account.expiration_date.strftime('%Y')))
                    self.state = State.REPEAT

            elif KeywordProcessing.contains_keyword('bill', msg):
                if self.user_account.package.payment == 'postpaid':
                    if KeywordProcessing.contains_keyword('unpaid', msg):
                        all_bills = Database.find_list('bills', 'customer', ObjectId(self.current_user.id))
                        unpaid_bills = [bill for bill in all_bills if not bill.paid]
                        if(len(unpaid_bills) > 0):
                            self.answer = str('You have %d bills unpaid.' % len(unpaid_bills))
                        else:
                            self.answer = str('You don\' have any unpaid bill.')
                    elif KeywordProcessing.contains_keyword('how_to', msg) and KeywordProcessing.contains_keyword('pay', msg):
                        self.answer = str('Please select your payment method. Online or phone.')
                        self.state = State.SELECT_PAYMENT_METHOD
                    elif KeywordProcessing.contains_keyword('when', msg):
                        self.answer = str('Your bill is due on %d %s.' % (self.user_account.payment_date.strftime('%d'), self.user_account.payment_date.strftime('%B')))
                    else:
                        self.answer = self.user_account.report()
                        self.state = State.REPEAT
                else:
                    self.answer = str('Sorry, I don\'t understand your question')

            # Troubleshooting
            elif KeywordProcessing.contains_keyword('cannot', msg):
                # Prepaid user
                if self.user_account.package.payment == 'prepaid':
                    if KeywordProcessing.contains_keyword('internet', msg):
                        if not self.user_account.package.is_internet_avail():
                            self.answer = str('Sorry, your current package is not support internet using.')
                        else:
                            self.answer = str('Sorry, i can\'t find any problem in your account. Do you want to talk to the operator.')
                            self.state = State.TALK_TO_OPERATOR
                    elif KeywordProcessing.contains_keyword('call', msg):
                        if self.user_account.balance <= self.user_account.package.internal_calling_rate:
                            self.answer = str('Sorry, your current balance is not enough.')
                        else:
                            self.answer = str('Sorry, i can\'t find any problem in your account. Do you want to talk to the operator.')
                            self.state = State.TALK_TO_OPERATOR

                #Postpaid user
                else:
                    if KeywordProcessing.contains_keyword('internet', msg):
                        if not self.user_account.package.is_internet_avail():
                            self.answer = str('Sorry, your current package is not support internet using.')
                        elif len([bill for bill in Database.find_list('bills', 'customer', self.current_user.id) if not bill.paid]) > 3:
                            self.answer = str('Sorry, your account was suspended because you haven\'t pay monthly fee.')
                        else:
                            self.answer = str('Sorry, i can\'t find any problem in your account. Do you want to talk to the operator.')
                            self.state = State.TALK_TO_OPERATOR
                    elif KeywordProcessing.contains_keyword('call', msg):
                        if self.user_account.package.payment == 'postpaid' and len([bill for bill in Database.find_list('bills', 'customer', self.current_user.id) if not bill.paid]) > 3:
                            self.answer = str('Sorry, your account was suspended because you haven\'t pay monthly fee.')
                        else:
                            self.answer = str('Sorry, i can\'t find any problem in your account. Do you want to talk to the operator.')
                            self.state = State.TALK_TO_OPERATOR

        elif self.state == State.REPEAT:
            # Repeat
            if KeywordProcessing.contains_keyword('confirm', msg):
                pass
            # Back to normal
            elif KeywordProcessing.contains_keyword('cancel', msg):
                self.answer = 'How can i help you.'
                self.state = State.NORMAL

        elif self.state == State.SELECT_PACKAGE:
            # Repeat
            if KeywordProcessing.contains_keyword('confirm', msg):
                pass
            elif KeywordProcessing.contains_keyword('cancel', msg):
                self.answer = 'How can i help you.'
                self.state = State.NORMAL
            # Explain user's interesting package detail
            elif KeywordProcessing.contains_keyword('ordinal', msg) and KeywordProcessing.get_index(msg) - 1 < len(self.recommend_packages):
                index = KeywordProcessing.get_index(msg) - 1
                self.interesting_package = self.recommend_packages[index]
                self.answer = str(self.interesting_package.description())
                self.answer += str(' Do you want to use this package.')
                self.state = State.CHANGE_PACKAGE
            else:
                self.answer = str('Sorry, i don\'t understand.')

        elif self.state == State.CHANGE_PACKAGE:
            if KeywordProcessing.contains_keyword('confirm', msg):
                if self.user_account.package.payment == 'prepaid':
                    # Change package of account
                    Database.update('accounts', 'customer', self.current_user.id, 'package', self.interesting_package.id)
                elif self.user_account.package.payment == 'postpaid':
                    # Create new bill
                    new_bill = Bill(self.current_user, self.interesting_package, 0, 0, 0, 0, datetime.datetime.now(), 0)
                    Database.insert('bills', new_bill.tojson())
                self.answer = 'package changing is complete.'
                # Get new user account
                self.user_account = Database.find_user_account(self.current_user.id)
                self.state = State.NORMAL
            elif KeywordProcessing.contains_keyword('cancel', msg):
                self.answer = 'How can i help you.'
                self.state = State.NORMAL
            else:
                self.answer = str('Sorry, i don\'t understand.')

        elif self.state == State.SELECT_PHONE_OS:
            if KeywordProcessing.contains_keyword('phone_os', msg):
                self.answer = Database.find_one('setups', 'os', msg).setup
                self.state = State.REPEAT
            else:
                self.answer = str('Sorry, we cannot find your operating system.')

        elif self.state == State.SELECT_PAYMENT_METHOD:
            if KeywordProcessing.contains_keyword('payment_method', msg):
                self.answer = Database.find_one('how_to_pays', 'method', msg).step
                self.state = State.REPEAT
            else:
                self.answer = str('Sorry, your payment method is not available.')

        elif self.state == State.SELECT_TOPUP_METHOD:
            if KeywordProcessing.contains_keyword('payment_method', msg):
                self.answer = Database.find_one('how_to_topups', 'method', msg).step
                self.state = State.REPEAT
            else:
                self.answer = str('Sorry, your payment method is not available.')

        elif self.state == State.TALK_TO_OPERATOR:
            if KeywordProcessing.contains_keyword('confirm', msg):
                self.answer = str('Transfer to operator. please wait for seconds.')
            elif KeywordProcessing.contains_keyword('cancel', msg):
                self.answer = str('How can i help you.')
                self.state = State.NORMAL

        elif self.state == State.EXIT_CONFIRM:
            if KeywordProcessing.contains_keyword('confirm', msg):
                self.answer = str('Thank you for using our service')
                self.state = State.EXIT
                self.recognizer.shutdown()
            elif KeywordProcessing.contains_keyword('cancel', msg):
                self.answer = str('How can i help you')
                self.state = State.NORMAL

        if self.answer is not None:
            Speaker.speak(self.answer)

        if self.state == State.REPEAT:
            Speaker.speak('Do you want to listen again.')

        self.recognizer.resume()    # Resume Speech recognizer