Exemple #1
0
def mem_walker(brains_found):
    flag1, flag2 = False, False

    if not brains_found:
        block = MemBlock()
        block.question = "Is it 4 legged?"
        block.guess = "Dog"

        write_memory(block)
        mem_walker(True)
    else:
        block = read_memory()
        current_block = block

        while True:
            print("[Jeeves] %s" % current_block.question)
            say(current_block.question)
            reply = user_input("reply: ").lower()

            if reply in ["yes", "y"]:
                print("[Jeeves] %s" % current_block.guess)
                say("So, Is it a %s?" % current_block.guess)
                reply = user_input("reply: ").lower()

                if reply in ["yes", "y"]:
                    say("Awesome!! I'm getting good at this!")
                    break
                else:
                    if not current_block.no2:
                        flag2 = True
                        break
                    else:
                        current_block = current_block.no2
            else:
                if not current_block.no1:
                    flag1 = True
                    break
                else:
                    current_block = current_block.no1

        if flag1 or flag2:
            temp = MemBlock()

            say("Okay, I give up!")
            say("I want to learn from you now...")
            say("Type a question related to the animal you thought.")
            say("For example: Does it have stripes? Or does it run fast?")
            temp.question = user_input("reply: ")

            say("Okay, tell me the creature you thought of")
            temp.guess = user_input("reply: ")

            say("Awesome. Assuming what you taught me is correct, I'll definitely remember it!")

            if flag1:
                current_block.no1 = temp
            else:
                current_block.no2 = temp

            write_memory(block)
Exemple #2
0
def check():
    say("Think of an animal and when you're ready say ok.")
    user_input('reply:')

    if not os.path.exists("brains"):
        say("I guess we are playing this game for the first time, so pardon my ignorance.")
        mem_walker(False)
    else:
        mem_walker(True)
    def get_top_tracks(self):
        tracks = self.sp.artist_top_tracks(self.artist["uri"])['tracks']
        if len(tracks) > 0:
            say("Here's what I think are their best works.")
            count = 0

            playlist = {}

            for track in tracks:
                print("[%d] Song: %s Album: %s" % (count + 1, track['name'], track['album']['name']))
                say("%s from the album %s" % (track['name'], track['album']['name']))
                count += 1

                playlist[str(count)] = (self.artist['name'], track['name'], track['album']['name'], track['uri'])

            say("Please type the index of the song you would like to hear")
            choice = user_input("reply: ")

            say("Playing %s from the album %s." % (playlist[choice][1], playlist[choice][2]))

            subprocess.call([
                'osascript',
                '-e',
                'tell app "Spotify" to play track "%s"' % playlist[choice][3]
            ])
        else:
            say("Sorry, Although I know %s but I can't find any songs. Weird" % (self.artist['name']))
Exemple #4
0
    def get_top_tracks(self):
        tracks = self.sp.artist_top_tracks(self.artist["uri"])['tracks']
        if len(tracks) > 0:
            say("Here's what I think are the top 3 songs of %s." %
                self.artist["name"])

            playlist = {}

            for track in tracks[:3]:
                print("Song: %s Album: %s" %
                      (track['name'], track['album']['name']))
                say("%s from the album %s" %
                    (track['name'], track['album']['name']))

                playlist[track['name'].lower()] = track['uri']

            say("Tell me the name of the song you would like to hear")
            choice = user_input()

            for song in playlist.keys():
                if choice in song:
                    say("Playing %s" % choice)
                    subprocess.call([
                        'osascript', '-e',
                        'tell app "Spotify" to play track "%s"' %
                        playlist[song]
                    ])
                    break
        else:
            say("Sorry, Although I know %s but I can't find any songs. Weird" %
                (self.artist['name']))
Exemple #5
0
    def get_top_tracks(self):
        tracks = self.sp.artist_top_tracks(self.artist["uri"])['tracks']
        if len(tracks) > 0:
            say("Here's what I think are the top 3 songs of %s." % self.artist["name"])

            playlist = {}

            for track in tracks[:3]:
                print("Song: %s Album: %s" % (track['name'], track['album']['name']))
                say("%s from the album %s" % (track['name'], track['album']['name']))

                playlist[track['name'].lower()] = track['uri']

            say("Tell me the name of the song you would like to hear")
            choice = user_input()

            for song in playlist.keys():
                if choice in song:
                    say("Playing %s" % choice)
                    subprocess.call([
                        'osascript',
                        '-e',
                        'tell app "Spotify" to play track "%s"' % playlist[song]
                    ])
                    break
        else:
            say("Sorry, Although I know %s but I can't find any songs. Weird" % (self.artist['name']))
Exemple #6
0
    def read_mails(self):
        user_id = 'me'
        label = 'UNREAD'
        credentials = self.get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('gmail', 'v1', http=http)
        response = service.users().messages().list(userId=user_id, labelIds=label).execute()
        messages = []

        if 'messages' in response:
            messages.extend(response['messages'])

        say('you have %d unread emails; and how many would you like me to read?' % response['resultSizeEstimate'])
        limit = int(user_input("reply: "))

        count = 0
        for message in messages[:limit]:
            count += 1
            message_content = service.users().messages().get(userId=user_id, id=message['id'],
                                                             format='metadata',
                                                             metadataHeaders=['From', 'Subject']).execute()
            say('message %d' % count)
            metadata_list = message_content['payload']['headers']

            for metadata in metadata_list:
                say(metadata['name'])
                say(metadata['value'])
Exemple #7
0
    def get_strategy_for(self, stemmed_mental_state, action_type):
        try:
            strategies = self.strategies[stemmed_mental_state][action_type]

            if len(strategies) > 1:
                say("Okay, what would you like to do?")
                count = 0
                plans = {}

                for strategy in strategies:
                    if strategy.describe():
                        say(strategy.describe())

                    plans[str(count)] = strategy

                reply = user_input("reply:")
                if not reply:
                    return

                action = reply.split(' ')
                strategy = self.strategies[action[0]][action[1]][0]
            else:
                strategy = strategies[0]

            strategy.react()
            strategy.perform()
        except KeyError:
            print("I don't know what do. Yet, hum nahi phate na!")
def main():
    # Get user input on hyperparameters
    hyper_params = user_input()

    # Edit parameters here
    model_num = hyper_params["model_number"]
    epochs = hyper_params["epochs"]
    train_batch_size = hyper_params["train_batch_size"]
    test_batch_size = hyper_params["test_batch_size"]
    learning_rate = hyper_params["learning_rate"]
    gamma = hyper_params["gamma"]
    log_interval = hyper_params["log_interval"]

    # Print hyperparameters for user to see
    print_user_input(hyper_params)

    # Set manual seed
    torch.manual_seed(1)

    # Check whether you can use Cuda
    use_cuda = torch.cuda.is_available()
    # Use Cuda if you can
    device = torch.device("cuda" if use_cuda else "cpu")
    print("Device: ", device)

    # Train based on hyperparameters
    train_cnn(model_num, epochs, train_batch_size, test_batch_size,
              learning_rate, gamma, log_interval, device)
Exemple #9
0
    def get_referrer(self):
        for tag in self.pos_tags:
            if str(tag[1]) == "VBZ":
                self.speak("Who is %s" % self.pos_tags[self.parse_index - 1][0])
                return user_input("reply: ")
            elif str(tag[1]) == "VBP":
                return "self"

            self.parse_index += 1
Exemple #10
0
    def get_referrer(self):
        for tag in self.pos_tags:
            if str(tag[1]) == 'VBZ':
                self.speak("Who is %s" %
                           self.pos_tags[self.parse_index - 1][0])
                return user_input("reply: ")
            elif str(tag[1]) == 'VBP':
                return "self"

            self.parse_index += 1
Exemple #11
0
    def perform(self):
        reply = "yes"

        while reply in ["yes", "y"]:
            check()

            say("Shall we play again?")
            reply = user_input("reply: ").lower()

        say("It was nice playing with you!")
Exemple #12
0
    def perform(self):
        self.start_spotify()
        say("Please type the artist you want to hear: ")
        name = user_input("reply: ")

        if not self.find_artist(name):
            say("That's weird. All this knowledge and still I couldn't find anything. I'll try to learn more.")
            say("My sincere apologies for that.")
            return

        self.get_top_tracks()
Exemple #13
0
    def perform(self):
        self.start_spotify()
        say("Please tell me the artist or band you want to hear: ")
        name = user_input()

        if not self.find_artist(name):
            say("That's weird. All this knowledge and still I couldn't find anything. I'll try to learn more."
                )
            say("My sincere apologies for that.")
            return

        self.get_top_tracks()
Exemple #14
0
    def read_news(self):
        sources = data_sources['news_urls']

        say("I can read news from...")
        for source in sources.keys():
            say(source)
        say("please tell me where would you like to hear it from?")
        feed = feedparser.parse(sources[user_input()])

        say("So, the top 3 stories are...")
        for entry in feed.entries[:count]:
            news_to_read = entry["description"]
            say(re.sub('<[^<]+?>', '', news_to_read.split('.')[0]))
    def read_news(self):
        indexed_source = []

        sources = data_sources['news_urls']

        say("I can read news from...")
        for source in sources.keys():
            say(source)
            indexed_source.append(sources[source])

        say("And, very soon i will be able to hear you. For now please type the choice from 1 to %d" % len(sources))
        choice = int(user_input("choice[1-%d]: " % len(sources)))
        say("And, how many headlines would you like to hear?")
        count = int(user_input("how many: "))

        feed = feedparser.parse(indexed_source[choice - 1])

        say("So, the top stories are...")
        for entry in feed.entries:
            news_to_read = entry["description"]
            say(re.sub('<[^<]+?>', '', news_to_read.split('.')[0]))
            count -= 1
            if count == 0:
                break
Exemple #16
0
    "--input", help="specify the input source mic/stdin, default is stdin")
parser.add_argument("--host",
                    help="specify julius' host, default is localhost")
parser.add_argument("--port",
                    help="specify julius' port, default is 10500",
                    type=int)
args = parser.parse_args()

if not os.path.exists(".CHAT_SERVER_PID"):
    process = subprocess.Popen([sys.executable, "chat_ui/chat_ui_server.py"])

    with open(".CHAT_SERVER_PID", "w") as pid:
        pid.write(str(process.pid))
else:
    with open(".CHAT_SERVER_PID") as pid:
        subprocess.call(['kill', pid.readlines()[0].strip()])

    os.remove(".CHAT_SERVER_PID")

src = "mic" if (args.input and args.input == "mic") else "stdin"

say("Hello. I'm at your service.")
while True:
    if src == "stdin":
        sentence = raw_input("Type something: ")
    else:
        sentence = user_input("Say something: ")

    segregator = Segregator(sentence)
    segregator.segregate_and_react()