Exemplo n.º 1
0
    def __init__(self, DNA=None, saveState=None):
        self.x = self.y = 0.0
        self.facing = 0.0  #In radians, 0 is facing east
        self.velocity = 0.0
        self.angularVelocity = 0.0  #positive is turning anticlockwise
        self.mouthPos = (0, 0)
        self.energy = self.MAX_ENERGY

        self.pulser = Pulser()

        self.fAntenna = Antenna(self, 0, 10)
        self.lAntenna = Antenna(self, -5, 7)
        self.rAntenna = Antenna(self, 5, 7)
        self.antennae = []

        self.lEye = Eye(self, 10, 8, 500)
        self.rEye = Eye(self, -10, 8, 500)
        self.eyes = [self.lEye, self.rEye]

        self.fBooster = Booster(self)
        self.lTurn = AngularBooster(self, 0.05)
        self.rTurn = AngularBooster(self, -0.05)

        self.brain = Brain([self.pulser] + self.antennae + self.eyes, 5,
                           [self.lTurn, self.fBooster, self.rTurn])

        if saveState != None:
            self.loadFromString(saveState)
        elif DNA != None:
            self.loadFromDNA(DNA)
Exemplo n.º 2
0
 def __init__(self, mic, profile, logger):
     self.persona = profile['persona']
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, logger)
     self.notifier = Notifier(profile, logger)
     self.logger = logger
    def __init__(self,
                 number,
                 env,
                 coordinator,
                 epsilon=0.1,
                 gamma=0.95,
                 params_update_iter=30,
                 max_episodes=1000):
        self.name = 'agent_' + str(number)
        self.number = number
        self.env = env
        self.coordinator = coordinator
        self.n_states = env.n_states
        self.n_actions = env.n_actions
        self.epsilon = epsilon
        self.gamma = gamma
        self.params_update_iter = params_update_iter
        self.max_episodes = max_episodes
        self.agent_episodes = 0

        self.agent = Brain(scope=self.name, env=env)
        self.global_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,
                                               'global')
        self.local_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,
                                              self.name)
Exemplo n.º 4
0
class Player:

    def __init__(self):

        self.pos = np.array([width/2,7*height/8])
        self.acc = np.array([0,0])
        self.dead = False
        self.reachedGoal = False
        self.fitness = 0
        self.brain = Brain(400)
        self.brain.randomise()

    def update(self):
        while (len(self.brain.memory) > self.brain.step):
            self.acc = self.brain.memory[self.brain.step]
            self.brain.step += 1
            self.pos = np.add(self.pos,self.acc)
            if (self.pos[0] == goalPos[0] and self.pos[1] == goalPos[1]):
                self.reachedGoal = True
            if (self.pos[0] >= width or self.pos[0] <= 0 or self.pos[1] >= height or self.pos[1] <= 0 or self.brain.step >= self.brain.size):
                self.dead = True

    def calculateFitness(self):
        if self.reachedGoal == True:
            self.fitness = 1.0 / (16.0 * 1000.0 / float(brain.step ** 2))
        else:
            self.distanceToGoal = np.abs(np.sum(np.dot(goalPos,self.pos)))
            self.fitness = 1.0 / (self.distanceToGoal ** 2)

    def clonePlayer(self):
        temp = Player()
        temp.brain = self.brain.clone()
        return temp
Exemplo n.º 5
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)

    def delegateInput(self, text):
        """A wrapper for querying brain."""
        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:
            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
Exemplo n.º 6
0
 def __init__(self, persona, mic, profile):
     self._logger = logging.getLogger(__name__)
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile)
     self.notifier = Notifier(profile)
Exemplo n.º 7
0
async def on_message(context):
    # manage if context.message.attachments is empty
    image_url = context.message.attachments[0].url
    # improve image format detection
    image_format_jpg = image_url[-3:]
    image_format_jpeg = image_url[-4:]
    if image_format_jpg.lower() == 'jpg' or image_format_jpeg.lower() == 'jpeg':
        try:
            brain = Brain()
            results = brain.analyze_image(image_url)[0]
            message = discord.Embed(
                title="Let's have a look..")
            for statistic in results:
                name = statistic[1]
                value = f'{round(statistic[2] * 100, 2)} %'
                message.add_field(name=name, value=value, inline=False)
            message.set_image(url=image_url)
            message.colour = 0x00ff00
            await context.message.channel.send(embed=message)
        except:
            error = discord.Embed(
                title="Ops.. Something went wrong", description="I'm sorry, something went wrong. Please, try again.")
            error.colour = 0xff0000
            await context.message.channel.send(embed=error)
            raise discord.DiscordException
    else:
        invalid_format = discord.Embed(
            title="Invalid format", description="I'm sorry, this format is not supported. Please, try again with a .jpg or .jpeg!")
        invalid_format.colour = 0xff0000
        await context.message.channel.send(embed=invalid_format)
class Conversation(object):

    def __init__(self, persona, mic, profile, dispatcherClient):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, dispatcherClient)
        
    def delegateInput(self, text):
        """A wrapper for querying brain."""
        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # # Print notifications until empty
            # notifications = self.notifier.getAllNotifications()
            # for notif in notifications:
            #     self.mic.say(notif)

            threshold, transcribed = self.mic.passiveListen(self.persona)
            if not transcribed or not threshold:
                continue

            input = self.mic.activeListen(threshold)
            if input:
                self.delegateInput(input)
            else:
                self.mic.say("Pardon?")
Exemplo n.º 9
0
    def __init__(self, state_size, action_size, bee_index, brain_name,
                       learning_rate,memory,memory_capacity,prioritization_scale,
                       target_type,target_frequency,maximum_exploration,batch_size,test, number_nodes, dueling, optimizer):
        self.state_size = state_size
        self.action_size = action_size
        self.bee_index = bee_index
        self.learning_rate = learning_rate
        self.gamma = 0.95
        self.brain = Brain(self.state_size, self.action_size, brain_name, batch_size, learning_rate, test, number_nodes, dueling, optimizer)
        self.memory_model = memory

        if self.memory_model == 'UER':
            self.memory = UER(memory_capacity)

        elif self.memory_model == 'PER':
            self.memory = PER(memory_capacity, prioritization_scale)

        else:
            print('Invalid memory model!')

        self.target_type = target_type
        self.update_target_frequency = target_frequency
        self.max_exploration_step = maximum_exploration
        self.batch_size = batch_size
        self.step = 0
        self.test = test
        if self.test:
            self.epsilon = MIN_EPSILON
Exemplo n.º 10
0
    def __init__(self, screen, settings):
        self.brain = Brain()
        self.brain.setBrain()
        self.id = 1
        self.score = 0
        self.dead = False

        self.life = 1
        self.color = (0, 0, 0)

        self.screen = screen
        self.settings = settings

        self.movementRight = True

        self.jump = False
        self.jumpNum = 0
        self.allowJump = True
        self.timer = 0  # this if to give the jump a bit of a buffer
        self.baseJump = settings.screenHeight

        self.collideLeft = False
        self.collideRight = False
        self.collideBottom = False

        self.image = pygame.image.load("Images/player.png")
        self.rect = self.image.get_rect()
        self.x, self.y = 50, self.settings.screenHeight - self.rect.bottom - 50
        self.rect.x, self.rect.y = self.x, self.y

        self.colorRect = pygame.Rect(self.x, self.y, 13, 17)
Exemplo n.º 11
0
    def __init__(self, state_size, action_size, bee_index, brain_name, arguments):
        self.state_size = state_size
        self.action_size = action_size
        self.bee_index = bee_index
        self.learning_rate = arguments['learning_rate']
        self.gamma = 0.95
        self.brain = Brain(self.state_size, self.action_size, brain_name, arguments)
        self.memory_model = arguments['memory']

        if self.memory_model == 'UER':
            self.memory = UER(arguments['memory_capacity'])

        elif self.memory_model == 'PER':
            self.memory = PER(arguments['memory_capacity'], arguments['prioritization_scale'])

        else:
            print('Invalid memory model!')

        self.target_type = arguments['target_type']
        self.update_target_frequency = arguments['target_frequency']
        self.max_exploration_step = arguments['maximum_exploration']
        self.batch_size = arguments['batch_size']
        self.step = 0
        self.test = arguments['test']
        if self.test:
            self.epsilon = MIN_EPSILON
Exemplo n.º 12
0
    def __init__(self, size, brain=None):
        self.scale = 80
        self.pigframe = [
            pg.transform.scale(
                pg.image.load("./resource/pigframes/" + str(i) + ".png"),
                (self.scale, self.scale)) for i in range(20)
        ]

        if brain == None:
            self.brain = Brain(2, 8, 2)
        else:
            self.brain = Brain(brain=brain, flag=True)

        self.pig_state = 0
        self.isjumping_up = False
        self.isjumping_down = False

        self.x = size[0] / 10
        self.y = 286
        self.velocity = 30
        self.accleration = 2.6363
        self.max_upper_jump = 100

        self.score = 0

        self.hitbox_color = (np.random.randint(0,
                                               255), np.random.randint(0, 255),
                             np.random.randint(0, 255))
Exemplo n.º 13
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
Exemplo n.º 14
0
 def __init__(self):
     """Create all class-level attributes"""
     self.current_sockets = []
     self.message_queues = {
     }  # keys = sockets, entries = outgoing message queue for that user
     self.message_rest = {}  # keys = clientserver_sockets
     self.mind = Brain()
Exemplo n.º 15
0
def OneCnn():
    brain = Brain()
    brain = brain.getInstance('cnn', 'log/cat_vs_dog/train/')
    from info import Info
    info = Info()
    image_info = info.getOneImage('data/cat_vs_dog/test/dog.9712.jpg')
    brain.evaluateOneImage(image_info, 2, {'cat': 0, 'dog': 1})
Exemplo n.º 16
0
 def __init__(self, num_states, num_actions, Double, Dueling, PER):
     ''' 태스크의 상태 및 행동의 가짓수를 설정 '''
     self.Double = Double
     self.Dueling = Dueling
     self.PER = PER
     self.brain = Brain(num_states, num_actions, Double, Dueling,
                        PER)  # 에이전트의 행동을 결정할 두뇌 역할 객체를 생성
Exemplo n.º 17
0
class Conversation(object):

    def __init__(self, persona, speaker, profile):
        self.persona = persona
        self.speaker = speaker
        self.profile = profile
        self.notifier = Notifier(profile)
        self.brain = Brain(speaker, profile)

    def handleForever(self):

        while True:

            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self.speaker.say(notif)

            threshold, transcribed = self.speaker.passiveListen(self.persona)
            if not threshold or not transcribed:
                continue

            input = self.speaker.activeListenToAllOptions(threshold)

            if input:
                self.brain.query(self.profile, transcribed)
Exemplo n.º 18
0
    def __init__(self,
                 number,
                 env,
                 coordinator,
                 epsilon=1,
                 epsilon_min=0.01,
                 epsilon_decay_step=300,
                 gamma=0.99,
                 params_update_iter=30):
        self.name = 'agent_' + str(number)
        self.number = number
        self.env = env
        self.coordinator = coordinator
        self.n_states = env.n_states
        self.n_actions = env.n_actions
        self.a_low_bound = env.a_low_bound
        self.a_high_bound = env.a_high_bound
        self.epsilon = epsilon
        self.epsilon_min = epsilon_min
        self.epsilon_decay_step = epsilon_decay_step
        self.gamma = gamma
        self.params_update_iter = params_update_iter
        self.agent_episode = 0

        self.agent = Brain(scope=self.name, env=env)
        self.global_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,
                                               'global')
        self.local_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,
                                              self.name)
Exemplo n.º 19
0
Arquivo: A3C.py Projeto: tdelubac/A3C
def main():

    state_shape, n_actions = utils.getSpecs(ENV)
    brain = Brain(state_shape, n_actions, GAMMA)
    #brain = Brain(state_shape, n_actions, GAMMA)

    envs = [Environment(brain, ENV, EPS_START, EPS_END, EPS_STEPS) for i in range(N_THREADS)]
    opts = [Optimizer(brain)   for i in range(N_OPTIMIZERS)]

    for opt in opts:
        opt.start()
    for env in envs:
        env.start()

    time.sleep(TRAINING_TIME)

    for opt in opts:
        opt.stop()
    for opt in opts:
        opt.join()
    for env in envs:
        env.stop()
    for env in envs:
        env.join()

    print("--------------")
    print("Training done!")
    print("Saving model under:",OUTPUT_NAME)
    brain.save(OUTPUT_NAME)
    print("--------------")
    print("Testing")
    test_env    = Environment(brain, ENV, render=True)
    test_env.run()
Exemplo n.º 20
0
    def run(self, window):
        self.window = window
        frame = self.view(window, back_button=True)

        vbox = gui.Box(frame, axis=1, expand=True)
        self.question_text = tichy.Text("Question")
        self.question_text.view(vbox, expand=True, font_size=58)

        self.choices = tichy.List()
        self.choices.view(vbox, expand=True)

        frame.connect('back', self.on_quit)

        dic = codecs.open(Learn.path('characters.dic'), encoding='utf-8')

        logger.info("opening the dict")
        # dic = open(Learn.path('characters.dic'), 'r')
        dic = Dic.read(dic)
        self.full_dic = dic[:]
        brain = Brain()

        logger.info("start game")
        self.task = None
        while True:
            self.task = brain.ask(self.ask, dic)
            try:
                yield self.task
            except GeneratorExit:
                break
Exemplo n.º 21
0
 def test_saves_event_if_event_is_not_already_stored(self):
     Brain.create(self.event)
     stored_event = Brain.read("223-unique-id")
     assert stored_event.title == "Cool event"
     assert stored_event.notification_sent == False
     assert str(stored_event.date) == str(self.event.date)
     assert str(stored_event.enrollment_date) == str(self.event.enrollment_date)
Exemplo n.º 22
0
    def __init__(self,
                 look_ahead=4,
                 skip_to_page=0,
                 feats=10,
                 max_q_sz=100,
                 base_url="http://www.xvideos.com/c/{0}/anal-12"):
        # Let's set this up so gathering new videos can happen in the background.
        self.scraped_videos = {}
        gather_args = (look_ahead, skip_to_page, feats, max_q_sz)
        self.gather_process = Thread(target=self.gather,
                                     args=gather_args,
                                     daemon=True)

        self.scr = Scraper(base_url=base_url, pg_n=skip_to_page)
        self.db = Database()
        self.ai = Brain(self)
        self.win = Window(self)

        self.currently_loaded_video_data = {}
        self.feats = feats

        self.q = PriorityQueue(maxsize=max_q_sz)
        self.lock = RLock()

        if "brain.pkl" in os.listdir():
            self.train()
        self.get_next()
Exemplo n.º 23
0
 def __init__(self, persona, mic, profile, house):
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, house)
     self.notifier = Notifier(profile, house)
     self.house = house
Exemplo n.º 24
0
    def _merge(assemblies: Tuple[Assembly, ...], area: Area, *, brain: Brain = None) -> Assembly:
        """
        Creates a new assembly with all input assemblies as parents.
        Practically creates a new assembly with one-directional links from parents.
        ONLY CALL AS: Assembly.merge(...), as the function is invariant under input order.

        :param brain: the brain in which the merge occurs
        :param assemblies: the parents of the new merged assembly
        :param area: the area into which we merge
        :returns: resulting merged assembly
        """
        assert len(assemblies) != 0, "tried to merge with empty input"

        merged_assembly: Assembly = Assembly(assemblies, area,
                                             appears_in=set.intersection(*[x.appears_in for x in assemblies]))
        if brain is not None:
            # create a mapping from the areas to the neurons we want to fire
            area_neuron_mapping = {ass.area: set() for ass in assemblies}
            for ass in assemblies:
                area_neuron_mapping[ass.area].append(list(ass.identify(brain=brain))) #maybe preserve brain?


            # update winners for relevant areas in the connectome
            for a in area_neuron_mapping.keys():
                brain.connectome.winners[a] = area_neuron_mapping[a][0]


            # Replace=True for better performance
            brain.next_round(subconnectome={a: [area] for a in area_neuron_mapping}, replace=True, iterations=brain.repeat)

            merged_assembly._update_hook(brain=brain)
        merged_assembly.bind_like(*assemblies)
        return merged_assembly
Exemplo n.º 25
0
    def project(self, area: Area, *, brain: Brain = None, iterations: Optional[int] = None) -> Assembly:
        """
        Projects an assembly into an area
        :param brain: the brain in which the projection happens
        :param area: the area in which the new assembly is going to be created
        :returns: resulting projected assembly
        """
        assert isinstance(area, Area), "Project target must be an Area"
        projected_assembly: Assembly = Assembly([self], area, appears_in=self.appears_in)
        if brain is not None:
            neurons = self.read(brain=brain)

            # TODO: Eyal see my update to line after merge
            # LINE FOR AFTER MERGE WITH PERFORMANCE
            # brain.connectome.winners[self.area] = neurons

            # CURRENT TEMPORARY BOOTSTRAPPING LINE
            brain.connectome._winners[self.area] = set(neurons)

            # Replace=True for better performance
            brain.next_round({self.area: [area]}, replace=True, iterations=iterations or brain.repeat)

            projected_assembly._update_hook(brain=brain)

        projected_assembly.bind_like(self)
        return projected_assembly
Exemplo n.º 26
0
 def __init__(self,
              sprite_groups,
              function,
              tile_size,
              color,
              coords,
              size=(1, 1),
              goal=None,
              walls=None,
              fpm=Settings.FRAMES_PER_MOVE,
              move_ticks=0,
              reached_goal=False,
              vision_surface=None,
              model_name=None):
     super().__init__(sprite_groups,
                      tile_size,
                      color,
                      coords,
                      size,
                      True,
                      fpm=fpm,
                      move_ticks=move_ticks)
     self.celebration_count = 0
     self.report = function
     self.goal = goal
     self.walls = walls
     self.original_color = color
     self.brain = Brain(self, vision_surface, reached_goal, model_name)
     self.resurrect()
Exemplo n.º 27
0
def compare_iteration(model_prefix, iterations, diversities, training_text, seed_sentence=None):
    result = {}
    index = 0
    for requested_iteration in iterations:
        for file_name in [x for x in os.listdir(data_path('')) if x.startswith(model_prefix)]:
            try:
                (runid, maxlen, step, lstm_size, rest) = file_name.split('-')
                (dropout, iteration, rest) = rest.split('_')
                if str(iteration) != str(requested_iteration):
                    continue
                (maxlen, step, lstm_size, dropout) = (int(maxlen), int(step), int(lstm_size), float(dropout))
                brain = Brain(maxlen=maxlen, lstm_size=lstm_size, dropout=dropout,
                              training_text=training_text)
                seed_sentence = seed_sentence or brain.random_seed_sentence()
                print 'sentence: ' + seed_sentence
                print '---- loading model: ' + file_name
                model = brain.load_model_with_prefix(file_name)

                length = 340

                for diversity in diversities:
                    generated = brain.generate_full(
                        model=model,
                        n=length,
                        diversity=diversity,
                        seed_sentence=seed_sentence)
                    result[(index, file_name, diversity)] = generated
                    index += 1
                    print generated
            except:
                print "Unexpected error with {}: {}".format(file_name, sys.exc_info()[1])
                raise

        for (ix, name, div), generated in sorted(result.iteritems()):
            print "ix={}, model={}, div={}| {}".format(ix, name, div, generated.encode('utf-8'))
Exemplo n.º 28
0
def train_with_opponent():
    sim = Connect4()
    if train_mode == "mixt":
        opponents = [RandomPlayer("Rand")]
        for idx, model_path in enumerate(os.listdir(models_root)):
            full_path = os.path.join(models_root, model_path)
            prev_brain = Brain(sim.width,
                               sim.height,
                               sim.actions_count,
                               load_path=full_path)
            opponents.append(QLearn(sim, prev_brain, "v" + str(idx)))
    elif train_mode == "random":
        opponents = [RandomPlayer("Rand")]
    elif train_mode == "minmax":
        opponents = [MinMax(max_level=minmax_level)]
    else:
        raise ValueError, ("Invalid train_mode. Got %s expected "
                           "(mixt|random|minmax)") % train_mode

    scorer = Scorer(stats_frequency)
    for step in xrange(new_models):
        brain = Brain(sim.width, sim.height, sim.actions_count)
        player = QLearn(sim, brain, "AI")

        w = [0.1 * i for i in xrange(1, len(opponents) + 1)]
        p = [wi / sum(w) for wi in w]

        for games in xrange(1, 100000):
            if games % win_threshold_games == 0:
                # If the new model wins more than 90% of the games of the last 300
                win_statistics = scorer.get_statistics(win_threshold_games)[0]
                if win_statistics > win_threshold_percentage:
                    # Save the model to disk and load it as an inference only model
                    model_path = brain.save(models_root)
                    prev_brain = Brain(sim.width,
                                       sim.height,
                                       sim.actions_count,
                                       load_path=model_path)
                    opponents.append(
                        QLearn(sim,
                               prev_brain,
                               "V" + str(step),
                               exploration_period=0,
                               discount_factor=0.9))
                    print "-" * 70
                    print(
                        "New model wins %d%s against previous models after "
                        "%d games") % (win_statistics, "%", games)
                    print "-" * 70
                    print ''
                    break

            opponent = np.random.choice(opponents, 1, p)[0]
            players = [player, opponent]
            play_game_with_opponent(players, sim, scorer)

    human_player = HumanPlayer("Player")
    while True:
        play_game_with_opponent([opponents[-1], human_player], sim, scorer)
Exemplo n.º 29
0
class RelayToIRC(irc.IRCClient):
    """
    Wire bot brain, job queue, and config into a Twisted IRC client
    """
    timestamp = None

    def connectionMade(self):
        self.config = self.factory.config
        self.nickname = self.config["irc"]["nick"]
        self.realname = self.config["irc"]["realname"]
        self.channel = self.config["irc"]["channel"]
        if "maxlen" in self.config["irc"]:
            text.maxlen = self.config["irc"]["maxlen"]

        self.sourceURL = self.config["source_url"]

        irc.IRCClient.connectionMade(self)

        if "pass" in self.config["irc"]:
            if "ownermail" in self.config["irc"]:
                self.msg("NickServ", "REGISTER %s %s" % (self.config["irc"]["pass"], self.config["irc"]["ownermail"]))
            elif "regverify" in self.config["irc"]:
                self.msg("NickServ", "VERIFY REGISTER %s %s" % (self.config["irc"]["nick"], self.config["irc"]["regverify"]))
            self.msg("NickServ", "IDENTIFY %s" % self.config["irc"]["pass"])

    def signedOn(self):
        self.join(self.channel)

    def joined(self, channel):
        print "Joined channel %s as %s" % (channel, self.nickname)
        self.brain = Brain(self.config, sink=self)
        #XXX get outta here:
        source = JobQueue(
            definition=self.config["jobs"],
            sink=self,
            interval=self.config["poll_interval"]
        )
        source.run()

    def privmsg(self, user, channel, message):
        if message.find(self.nickname) >= 0:
            self.brain.respond(user, message)

    def write(self, data):
        if isinstance(data, list):
            for line in data:
                self.write(line)
            return
        self.say(self.channel, data.encode('ascii', 'replace'))
        self.timestamp = datetime.datetime.utcnow()


    @staticmethod
    def run(config):
        factory = ReconnectingClientFactory()
        factory.protocol = RelayToIRC
        factory.config = config
        reactor.connectTCP(config["irc"]["host"], config["irc"]["port"], factory)
        reactor.run()
Exemplo n.º 30
0
def trainFace():
    from info import Info
    info = Info()
    info.getMyFace()
    info.setOtherFace()
    brain = Brain()
    brain = brain.getInstance('face')
    brain.faceTrain()
Exemplo n.º 31
0
 def __init__(self, persona, mic, profile, active_stt_engine=None):
     self._logger = logging.getLogger(__name__)
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, active_stt_engine, echo=mic._echo)
     # self.notifier = Notifier(profile)
     self.phone = mic.phone
Exemplo n.º 32
0
 def test_create_brain(self):
     brain = Brain()
     self.assertEqual(0, brain.num_neurons)
     n1 = brain.add_neuron()
     n2 = brain.add_neuron()
     self.assertEqual(2, brain.num_neurons)
     brain.add_synapse(n1, n2, 0.0, 1)
     self.assertEqual(1, brain.num_synapses)
Exemplo n.º 33
0
def trainCnn():
    brain = Brain()
    brain = brain.getInstance('cnn', 'log/cat_vs_dog/train/')
    train_dir = 'data/cat_vs_dog/train/'
    from info import Info
    info = Info()
    train_batch, train_label_batch = info.getImages(train_dir, {'cat' : 0, 'dog' : 1})
    brain.trainCnnNetwork(train_batch, train_label_batch)
Exemplo n.º 34
0
 def __init__(self, input_shape, action_count, steps=0, model_path=None, learning_rate=None):
     if learning_rate is not None:
         SET_LEARNING_RATE(learning_rate)
     self.steps = steps
     self.epsilon = MAX_EPSILON if steps == 0 else self.__calc_epsilon(steps)
     self.brain = Brain(action_count, input_shape=input_shape, model_path=model_path)
     self.memory = Memory(MEMORY_CAPACITY)
     self.input_shape = input_shape
     self.action_count = action_count
Exemplo n.º 35
0
    def __init__(self):

        self.pos = np.array([width/2,7*height/8])
        self.acc = np.array([0,0])
        self.dead = False
        self.reachedGoal = False
        self.fitness = 0
        self.brain = Brain(400)
        self.brain.randomise()
Exemplo n.º 36
0
 def __init__(self, num_states, num_actions, eps_min=0.05, eps_max=1, lam=1e-3):
     self.num_states = num_states
     self.num_actions = num_actions
     self.eps_min = eps_min
     self.eps_max = eps_max
     self.lam = lam
     self.brain = Brain(num_states, num_actions)
     self.memory = Memory(MEMORY_CAPACITY)
     self.step = 0
Exemplo n.º 37
0
 def setUp(self):
     Brain.connection = sqlite3.connect(":memory:")
     Brain.setup()
     self.event = MagicMock(
         id="223-unique-id",
         title="Cool event",
         enrollment_date=datetime.now(),
         date=datetime.now(),
         notification_sent=False,
     )
Exemplo n.º 38
0
def train_single_player():
  sim = DummyGame() # Breakout()
  brain = Brain(sim.width, sim.height, sim.actions_count)
  player = QLearn(sim, brain, "AI")
  scorer = Scorer(stats_frequency)

  for games in xrange(train_games):
    play_single_player_game(player, sim, scorer, display_board=True)
  # Save the model to disk and load it as an inference only model
  model_path = brain.save(models_root)
  print 'Saved trained model to', model_path
Exemplo n.º 39
0
class Conversation(object):

    def __init__(self, persona, mic, profile, isPassiveEnabled):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.isPassiveEnabled = isPassiveEnabled

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed, passivePhrases = \
                self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue

            self._logger.info("Keyword '%s' has been said!", self.persona)

            if self.isPassiveEnabled is True and len(passivePhrases) != 0:

                input = passivePhrases
                self._logger.debug("Checking for passive phrase '%s' with " +
                                   "threshold: %r", input, threshold)

            else:

                self._logger.debug("Started to listen actively with " +
                                   "threshold: %r", threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with " +
                                   "threshold: %r", threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Exemplo n.º 40
0
def train_with_opponent():
  sim = Connect4()
  if train_mode == "mixt":
    opponents = [RandomPlayer("Rand")]
    for idx, model_path in enumerate(os.listdir(models_root)):
      full_path = os.path.join(models_root, model_path)
      prev_brain = Brain(sim.width,
                         sim.height,
                         sim.actions_count,
                         load_path=full_path)
      opponents.append(QLearn(sim, prev_brain, "v" + str(idx)))
  elif train_mode == "random":
    opponents = [RandomPlayer("Rand")]
  elif train_mode == "minmax":
    opponents = [MinMax(max_level=minmax_level)]
  else:
    raise ValueError, ("Invalid train_mode. Got %s expected "
      "(mixt|random|minmax)") % train_mode

  scorer = Scorer(stats_frequency)
  for step in xrange(new_models):
    brain = Brain(sim.width, sim.height, sim.actions_count)
    player = QLearn(sim, brain, "AI")

    w = [0.1 * i for i in xrange(1, len(opponents) + 1)]
    p = [wi / sum(w) for wi in w]

    for games in xrange(1, 100000):
      if games % win_threshold_games == 0:
        # If the new model wins more than 90% of the games of the last 300
        win_statistics = scorer.get_statistics(win_threshold_games)[0]
        if win_statistics > win_threshold_percentage:
          # Save the model to disk and load it as an inference only model
          model_path = brain.save(models_root)
          prev_brain = Brain(sim.width,
                             sim.height,
                             sim.actions_count,
                             load_path=model_path)
          opponents.append(QLearn(sim, prev_brain, "V" + str(step),
                                  exploration_period=0, discount_factor=0.9))
          print "-" * 70
          print("New model wins %d%s against previous models after "
                "%d games") % (win_statistics, "%", games)
          print "-" * 70
          print ''
          break

      opponent = np.random.choice(opponents, 1, p)[0]
      players = [player, opponent]
      play_game_with_opponent(players, sim, scorer)

  human_player = HumanPlayer("Player")
  while True:
    play_game_with_opponent([opponents[-1], human_player], sim, scorer)
class Conversation(object):

    def __init__(self, persona, mic, profile, house):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, house)
        self.notifier = Notifier(profile, house)
        self.house = house

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.mic.say(
                    "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                return

            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif
                self.mic.say(notif)
            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
Exemplo n.º 42
0
def input():
	actionflg=True
	inputs=config.get('if').keys()
	for input in inputs:
		logger.debug(input)
		brain=Brain(config)
		brain.action(input)
		if not brain.outflag:
			actionflg=False
			break
	if actionflg:
		action()
Exemplo n.º 43
0
def train(maxlens, steps, dropouts, dataset):
    for code, text_file in dataset:
        for maxlen in maxlens:
            for step in steps:
                for dropout in dropouts:
                    print '=========== TRAINING on: maxlen={}, step={}, lstm_size=128, dropout={}, text={}'.format(
                        maxlen,
                        step,
                        dropout,
                        text_file)
                    brain = Brain(maxlen=maxlen, lstm_size=128, dropout=dropout,
                                  training_text=text_file)
                    brain.train(runid='11,{},tweets'.format(code), iterations=7, step=step)
Exemplo n.º 44
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            # Word we listen for to self terminate
            TERMINATE = 'GOODBYE'

            self._logger.debug("Started listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)
            threshold, transcribed = self.mic.passiveListen(self.persona, TERMINATE)
            self._logger.debug("Stopped listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            # Terminate on goodbye
            if transcribed == TERMINATE:
                friendly.goodbye(self.mic, self.profile)
                sys.exit(0)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Exemplo n.º 45
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while on == True:

            nu()
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                messages = ["what?",
                            "what did you say",
                            "Say that again?", "speak the f**k up", "i cant f*****g hear you", "blah blah blah", "did you say something?"]

                message = random.choice(messages)
                zip2()
                self.mic.say(message)
Exemplo n.º 46
0
class Conversation(object):
  def __init__(self, persona, mic, server, profile):
    self._logger = logging.getLogger(__name__)
    self.persona = persona
    self.mic = mic
    self.profile = profile
    self.brain = Brain(mic, profile)
    self.notifier = Notifier(profile)
    self.server = server

  def handleForever(self):
    """
    Delegates user input to the handling function when activated.
    """
    self._logger.info("Starting to handle conversation with keyword '%s'.",
                      self.persona)
    while True:
      # Print notifications until empty
      notifications = self.notifier.getAllNotifications()
      for notif in notifications:
        self._logger.info("Received notification: '%s'", str(notif))

      if 'jasper.server.enabled' in self.profile and self.profile['jasper.server.enabled']:
        inputDevice = self.server
        self._logger.debug("Listening to tcp socket with Jasper server")
      else:
        inputDevice = self.mic
        self._logger.debug("Listening to attached microphone")

      self._logger.debug("Started listening for keyword '%s'",
                         self.persona)
      threshold, transcribed = inputDevice.passiveListen(self.persona)
      self._logger.debug("Stopped listening for keyword '%s'",
                         self.persona)

      if not transcribed or not threshold:
        self._logger.info("Nothing has been said or transcribed.")
        continue
      self._logger.info("Keyword '%s' has been said!", self.persona)

      self._logger.debug("Started to listen actively with threshold: %r",
                         threshold)
      input = inputDevice.activeListenToAllOptions(threshold)
      self._logger.debug("Stopped to listen actively with threshold: %r",
                         threshold)

      if input:
        self.brain.query(input)
      else:
        inputDevice.say("Pardon?")
Exemplo n.º 47
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            try:
                notifications = self.notifier.getAllNotifications()
                for notif in notifications:
                    self._logger.info("Received notification: '%s'", str(notif))

                self._logger.debug("Started listening for keyword '%s'",
                                   self.persona)
                threshold, transcribed = self.mic.passiveListen(self.persona)
                self._logger.debug("Stopped listening for keyword '%s'",
                                   self.persona)

                if not transcribed or not threshold:
                    self._logger.info("Nothing has been said or transcribed.")
                    continue
                self._logger.info("Keyword '%s' has been said!", self.persona)

                self._logger.debug("Started to listen actively with threshold: %r",
                                   threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with threshold: %r",
                                   threshold)

                if input:
                    self.brain.query(input)
                else:
                    self.mic.say("Pardon?")
            except KeyboardInterrupt:
                print "Keyboard Interrupt!"
                try:
                    sys.exit(0)
                except SystemExit:
                    os._exit(0)
Exemplo n.º 48
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            #notifications = self.notifier.getAllNotifications()
            #for notif in notifications:
            #    self._logger.info("Received notification: '%s'", str(notif))

            #self._logger.debug("Started listening for keyword '%s'",self.persona)
            #threshold, transcribed = self.mic.passiveListen(self.persona)
            #self._logger.debug("Stopped listening for keyword '%s'",
                              # self.persona)

            #if not transcribed or not threshold:
                #self._logger.info("Nothing has been said or transcribed.")
                #continue
            #self._logger.info("Keyword '%s' has been said!", self.persona)

            #self._logger.debug("Started to listen actively with threshold: %r",
                              # threshold)
	    input = []
	    print "entering input"
            input = client.grab_input().strip().split()
            #input = self.mic.activeListenToAllOptions(threshold)
            #self._logger.debug("Stopped to listen actively with threshold: %r",
                              # threshold)
	    print input

            if input:
		print "if entered"
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
		print "else entered"
Exemplo n.º 49
0
Arquivo: grid.py Projeto: pravj/orbis
	def __init__(self):
		# global configurations
		self.cfg = Config()

		# 2D-array having all blocks in grid
		self.Blocks = []

		# array of colors in pallete
		self.colors = self.cfg.colors		

		# create a window and table
		Gtk.Window.__init__(self, title=self.cfg.name)
		self.table = Gtk.Table(self.cfg.size, self.cfg.size, True)
		
		# pallete element to be added
		self.pallete = Pallete()
		
		# add generated table to window
		self.add(self.table)
		self.generate_table()
		self.add_pallete()

		# brain instance
		self.brain = Brain(self.Blocks)

		# activate stylesheet
		self.add_style()
Exemplo n.º 50
0
    def __init__(self, settings, debug, announce):
        self.settings = settings
        self.twitter_keys = settings.twitter
        self.debug = debug
        self.announce = announce

        # Set up the twitter API
        self.auth = tweepy.OAuthHandler(
            self.twitter_keys['consumer_key'],
            self.twitter_keys['consumer_secret'])
        self.auth.set_access_token(
            self.twitter_keys['access_key'],
            self.twitter_keys['access_secret'])
        self.twitter_api = tweepy.API(self.auth)

        # Set up MongoDB connection
        self.client = MongoClient()
        self.db = self.client.wilbur 
        self.reports = self.db.reports
        self.tweets = self.db.tweets

        self.tweet_queue = Queue.Queue()
        logging.basicConfig()
        self.scheduler = BackgroundScheduler()
        self.brain = Brain(self)
Exemplo n.º 51
0
def compile(sentences, dictionary, languagemodel):
    """
        Gets the words and creates the dictionary
    """

    modules = Brain.get_modules()

    words = []
    for module in modules:
        words.extend(module.WORDS)

    # for spotify module
    words.extend(["MUSIC", "SPOTIFY"])
    words = list(set(words))

    # create the dictionary
    pronounced = g2p.translateWords(words)
    zipped = zip(words, pronounced)
    lines = ["%s %s" % (x, y) for x, y in zipped]

    with open(dictionary, "w") as f:
        f.write("\n".join(lines) + "\n")

    # create the language model
    with open(sentences, "w") as f:
        f.write("\n".join(words) + "\n")
        f.write("<s> \n </s> \n")
        f.close()

    # make language model
    text2lm(sentences, languagemodel)
Exemplo n.º 52
0
 def __init__(self):
     self.brain = Brain()
     self.movement = Movement(self, max_speed=800)
     self.max_velocity = 800
     self.move_target = None
     self.attack_target = None
     self.brain.push_state(self.ai_idle)
Exemplo n.º 53
0
 def __init__(self, persona, mic, profile):
     self._logger = logging.getLogger(__name__)
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile)
     self.notifier = Notifier(profile)
Exemplo n.º 54
0
	def __init__( self ):
		self.radius 	 = config.member_radius
		self.color  	 = Helper.random_color()

		self.brain       = Brain()

		self.x 			 = None
		self.y 			 = None

		self.energy      = self.max_energy
		self.distance    = 0.0
		self.relation    = 0.0
		self.rotation    = 0.0
		self.speed       = 0.0

		self.left_track  = None
		self.right_track = None

		self.close_to    = None
		self.alive 		 = True
		self.food 		 = 0
		self.score       = 0
		self.norm_score  = 0.0
		self.mutations   = 0

		self.error_count = 0

		self.born 		 = pygame.time.get_ticks()
		self.died		 = None
		self.lifespan    = 0

		self.generation  = 0
		self.member_num  = 0
Exemplo n.º 55
0
 def __init__(self, mic, profile, logger):
     self.persona = profile['persona']
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, logger)
     self.notifier = Notifier(profile, logger)
     self.logger = logger
Exemplo n.º 56
0
    def __init__(self, DNA=None, saveState=None):
        self.x = self.y = 0.0
        self.facing = 0.0 #In radians, 0 is facing east
        self.velocity = 0.0
        self.angularVelocity = 0.0 #positive is turning anticlockwise
        self.mouthPos = (0,0)
        self.energy = self.MAX_ENERGY

        self.pulser = Pulser()
        
        self.fAntenna = Antenna(self,0,10)
        self.lAntenna = Antenna(self,-5,7)
        self.rAntenna = Antenna(self,5,7)
        self.antennae = []
        
        self.lEye = Eye(self,10,8,500)
        self.rEye = Eye(self,-10,8,500)
        self.eyes = [self.lEye, self.rEye]

        self.fBooster = Booster(self)
        self.lTurn = AngularBooster(self, 0.05)
        self.rTurn = AngularBooster(self, -0.05)

        self.brain = Brain([self.pulser]+self.antennae+self.eyes,
                           5,
                           [self.lTurn, self.fBooster, self.rTurn])

        if saveState!=None:
            self.loadFromString(saveState)
        elif DNA!=None:
            self.loadFromDNA(DNA)
Exemplo n.º 57
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        
        try_num =0
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            #msg = xbee.Receive()   #this is where we get our serial data during downtime
            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Exemplo n.º 58
0
class Conversation(object):
    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        # self.notifier = Notifier(profile)

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module

        # if any(x in text.upper() for x in ["SPOTIFY","MUSIC"]):
        #     self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
        #     music_mode = MusicMode(self.persona, self.mic)
        #     music_mode.handleForever()
        #     return
        if any(x in text.upper() for x in ["EXIT", "QUIT"]):
            exit()

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            # notifications = self.notifier.getAllNotifications()
            # for notif in notifications:
            #     print notif

            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                    if any(x in input.upper() for x in ["EXIT", "QUIT"]):
                        break
                else:
                    self.mic.say("Pardon?")
        exit()
Exemplo n.º 59
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.shutdown = False

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while not self.shutdown:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            self.mic.say(random.choice(["your wish is my command", "what is thy bidding, my master", "I live to serve"]))
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")