Ejemplo n.º 1
0
    def key_released(self, button):
        '''
        Decides which method to call after a button is released/pressed.
        '''

        track_name = LabTextInput.active_textinput
        if button.text == '123':
            self.parent.parent.current = 'numeric_keyboard'
            self.parent.parent.transition.direction = 'left'
        elif button.text == 'shift':
            if self.shift_pressed:
                self.shift_pressed = False
                self.shift_buttons()
            else:
                self.shift_pressed = True
                self.shift_buttons()
        if track_name != None:
            if button.text == 'space':
                track_name.text += ' '
            elif button.text in ['123', 'abc', 'shift']:
                pass
            elif button.text == '⌫':
                track_name.text = track_name.text[:-1]
                try:
                    print(autocomplete.predict(track_name.text, ' '))
                except:
                    pass
            else:
                track_name.text += button.text
                try:
                    print(autocomplete.predict(track_name.text, button.text))
                except:
                    pass
Ejemplo n.º 2
0
def get_suggestion(prev_word='my', next_semi_word='na'):
    global full_sentence
    separated = full_sentence.strip().split(' ')

    print(separated)

    list_or = [
        "Crisis Services Canada", "Hope for Wellness", "Kids Help Phone",
        "Canadian Mental Health Association"
    ]

    if len(separated) == 0:
        return ['i', 'me', 'the', 'my', 'there']
    elif len(separated) == 1:
        suggestions = autocomplete.predict(full_sentence, '')[:5]
    elif len(separated) >= 2:
        first = ''
        second = ''

        first = separated[-2]
        second = separated[-1]

        suggestions = autocomplete.predict(first, second)[:5]

    return [word for word in list_or]
Ejemplo n.º 3
0
 def lastwords(self):
     autocomplete.load()
     if len(self._label.cget("text").split("_")) > 1:
         a = self._label.cget("text").split("_")[-2:]
         print(autocomplete.predict(a[0], a[1]))
         return autocomplete.predict(a[0], a[1])
     else:
         return [("", 1), ("", 1), ("", 1)]
def makePrediction(character):
    global lastWord
    global currentWord
    #update lastWord, currentWord, lastString
    if(lastWord == '' and character != ' '):
        currentWord += character
        return DEFAULTPREDICTION
    elif character == ' ' and currentWord != '':
        lastWord = currentWord
        currentWord = ''
        return pasturizeList(autocomplete.predict(lastWord, currentWord))
    else:
        currentWord += character
        return  pasturizeList(autocomplete.predict(lastWord, currentWord))
Ejemplo n.º 5
0
    def predict(self, word1, word2=None, n=20):
        predictions = []

        if word2 is not None and len(word2) is not 0:
            predictions = [i[0] for i in autocomplete.predict(first_word=word1, second_word=word2, top_n=n)]
            return  predictions

        for letter in string.ascii_lowercase:
            for p in autocomplete.predict(first_word=word1, second_word=letter, top_n=n):
                predictions.append(p)

        predictions = list(set(predictions))

        predictions = [i[0] for i in sorted(predictions, key=lambda t: t[1], reverse=True)[:n]]
        return predictions
Ejemplo n.º 6
0
def autocomplete_predictor_wrapper(memory, seq):
    last_word = memory[-1]
    predictions_raw = ac.predict(last_word, seq, NUM_PREDICTIONS)
    predictions_clear = []
    for i in range(len(predictions_raw)):
        predictions_clear.append(predictions_raw[i][0])
    return predictions_clear
Ejemplo n.º 7
0
def test_fnc(seed_word = 'the',roughly_number_words=100 ):
    import autocomplete
    reload(autocomplete)
    from random import randint
    import string
    import random

    autocomplete.load()

    #the seed for the poem
    prior_word = seed_word

    #the prose you generate
    poem = prior_word

    for i in range(0,roughly_number_words):
        random_seed = random.choice(string.letters)
        x = randint(0,9)
        if x <= 1:
            poem = poem + '\n'
        else:
            new_prediction=autocomplete.predict(prior_word, random_seed)
            if len(new_prediction)>=1:
                y = randint(0,len(new_prediction)-1)
                new_word = new_prediction[y][0]
                poem = poem + ' ' + new_word

    print "\n\n****Words of inspiration:****\n\n"
    print poem
Ejemplo n.º 8
0
    def __preprocess_search_query(self, query):
        # create tokens
        consumed = AnalyzeContent(text_weights=[(query, 1)])
        search_tokens = consumed.content_token_list()

        for i, token in enumerate(search_tokens):
            # attempt to spellcheck invalid tokens
            if len(token) >= 3:
                if self._spellcheck.unknown([token]):
                    search_tokens[i] = self._spellcheck.correction(token)
                    # print('corrected ' + token + ' to ' + search_tokens[i])
                    token = search_tokens[i]

            if i > 0 and autocomplete.predict_currword(search_tokens[i - 1]):
                prev = search_tokens[i - 1]
                pred = autocomplete.predict(prev, token)
            else:
                pred = autocomplete.predict_currword(token)

            if len(pred) > 0:
                best_pred = pred[0][0]
            else:
                best_pred = token

            search_tokens[i] = self._lemmatizer.lemmatize(best_pred)

        # remove stopwords if we have non-stopword terms. otherwise search purely by stopwords as a last case.
        non_stopwords = [x for x in search_tokens if x not in self._stopwords]
        if non_stopwords:
            search_tokens = non_stopwords

        return search_tokens
Ejemplo n.º 9
0
def get_ac_list(str, count):
    ac_list = []

    words = str.split()

    # Note that the auto-complete library only supports up to two full words
    if len(words) > 2:
        return ac_list

    if len(words) > 1:
        try:
            l = autocomplete.predict(words[0], words[1], count)
            for name,num in l:
                ac_list.append(words[0]+' '+name)
        except:
            # Due to a bug in the auto-complete library,
            # words that contain number (e.g. abcde10) doesn't get
            # handled properly
            return []
    elif len(words) == 1:
        l = autocomplete.predict_currword(words[0], count)
        for name,num in l:
            ac_list.append(name)

    return ac_list
Ejemplo n.º 10
0
    def on_text(self, instance, value):
        try:
            if self.get_labhelper().ids.substance_name.text == "":
                pass
            else:
                print("csdvjbchknohuicgyvjg hkbhbj")
                self.get_labhelper().ids.suggestions_list.remove_widget(
                    self.get_labhelper().ids.suggestions_list.character_list)
                suggestion_list = []
                predicted_values = autocomplete.predict(value, ' ')
                print(predicted_values)
                for sv in predicted_values:
                    print(sv[0])
                    print("-_-")
                    suggestion_list.append(sv[0])

                print(suggestion_list)
                character_list = CharacterList(suggestion_list)
                self.get_labhelper().ids.suggestions_list.add_widget(
                    character_list)
                print("didne")
        except:
            pass

        if instance == LabTextInput.instances[0]:
            pass
        elif self.get_labhelper().ids.substance_name.text == "":
            pass
        else:
            self.switch_to_suggestions()
    def prediction(self, text):

        # remove non ascii chars
        text = ''.join([i if ord(i) < 128 else ' ' for i in text])

        splited_text = text.split()
        pred = []

        if (len(splited_text) > 1):
            last_word = splited_text[-1]
            second_last_word = splited_text[-2]

            try:
                pred += predict(second_last_word, last_word)
            except Exception as e:
                print("ERROR Markov Chain")
                pass

            text = ' '.join(word.capitalize() for word in text.split()[:-1])
            pred = [text + ' ' + word.capitalize() for word, points in pred]

        try:
            list_prediction = self.Trie.search(text)
            pred += [lp[0] for lp in list_prediction]
            pred = [word.capitalize() for word in pred]

        except Exception as e:
            print("ERROR TRIE")
            pass

        return pred
Ejemplo n.º 12
0
def suggest(alp):
    autocomplete.load()
    l = autocomplete.predict('the', alp)
    i = 0
    while (i < 5 and i < len(l)):
        print(l[i][0])
        i = i + 1
Ejemplo n.º 13
0
def get_suggestion(prev_word='my', next_semi_word='na'):
    global full_sentence
    separated = full_sentence.strip().split(' ')

    print(separated)

    if len(separated) == 0:
        return ['i', 'me', 'the', 'my', 'there']
    elif len(separated) == 1:
        suggestions = autocomplete.predict(full_sentence, '')[:5]
    elif len(separated) >= 2:
        first = ''
        second = ''

        first = separated[-2]
        second = separated[-1]

        suggestions = autocomplete.predict(first, second)[:5]

    return [word[0] for word in suggestions]
Ejemplo n.º 14
0
def suggest_word(previous, current):
    """Given the previous word and the current partially typed
    word, suggest some possibilities for the word being typed.
    Returns a list of tuples containing the suggested word and
    the number of times it showed up as a followup in the training
    corpus.
    """
    if not suggest_word.is_loaded:  #Don't train more than once
        autocomplete.load()
        suggest_word.is_loaded = True
    return autocomplete.predict(previous, current)
Ejemplo n.º 15
0
def predict():
    global data1, data2, olddata1, olddata2
    if (len(text.get(0.0, END).split()) > 1):
        data1, data2 = text.get(0.0, END).split()[-2:]
    if (not (data1 == olddata1 and data2 == olddata2)):
        olddata1 = data1
        olddata2 = data2
        try:
            print(autocomplete.predict(data1, data2))
        except:
            print("[]")
    root.after(20, predict)
Ejemplo n.º 16
0
 def predict_corrected_word(self, word="") -> []:
     preds = autocomplete.predict(first_word=word, second_word="", top_n=3)
     result = []
     # if preds list is not empty
     if len(preds) != 0:
         for prediction in preds:
             result.append(prediction[0])
         return result
     else:  # if preds list is empty, recheck all characters
         for i in range(1, len(word) + 1):
             char = word[-i]
             checking_char_list = self.get_checking_char_list(char)
             for checking_char in checking_char_list:
                 word_l = list(word)
                 word_l[-i] = checking_char
                 temp_preds = autocomplete.predict(
                     first_word="".join(word_l), second_word="", top_n=3)
                 if len(temp_preds) > 0:
                     for prediction in temp_preds:
                         result.append(prediction[0])
                     return result
     return []
Ejemplo n.º 17
0
    def index(text):
        if not text:
            return ''

        print('GET: ', text)

        try:
            splitted = text.split()
            if len(splitted) < 2:
                return ''
            else:
                splitted = splitted[-2:]
                p = predict(splitted[0], splitted[1])
        except:
            return ''

        print('PREDICTED: ', p)
        return '\n'.join([w for w, _ in p])
Ejemplo n.º 18
0
def api_articles():

    response = []

    query = request.args.get('query').split(' ')

    subQuery = query[len(query) - 1]

    result = autocomplete.predict(subQuery, '')

    if len(result) >= 3:

        response = [result[0][0], result[1][0], result[2][0]]

    elif len(result) == 2:

        response = [result[0][0], result[1][0]]

    elif len(result) == 1:

        response = [result[0][0]]

    return str(response)
Ejemplo n.º 19
0
def next_word(word):
    global temp
    temp = []
    for i in range(ord('a'), ord('z') + 1):
        temp = temp + autocomplete.predict(word, chr(i))

    Sort(temp)
    rem = temp
    temp = []
    temp = [i for i in rem if i[0] != "r"]
    temp_store = temp[0:4]

    k = 1
    for keys in temp_store:
        string = str(k)
        print("word {} : {}".format(k, keys[0]))
        level3Buttons[k] = keys[0]
        Main_Window._buttons4[string].config(text=keys[0])
        k = k + 1
    if (k != 5):
        for i in range(k, 5):
            string = str(i)
            level3Buttons[i] = "empty"
            Main_Window._buttons4[string].config(text="")
Ejemplo n.º 20
0
def word_prediction(keyword1, keyword2):  #word prediction
    global is_word
    global is_char
    global is_first_char
    global sentence
    global word
    global char
    global take_new_input
    global store
    global idx
    global space

    store = autocomplete.predict(keyword1, keyword2)
    if (idx == 0):
        store = store[0:3]
    elif (idx > 0):
        store = store[idx * 3:(idx + 1) * 3]

    if (len(store) == 0):
        print("word 1:" + keyword1)
    else:
        print("word 1 : " + keyword1 + keyword2)
        k = 2
        for keys in store:
            print("word {} : {}".format(k, keys[0]))
            k = k + 1
    print("select word")
    if (len(store) >= 3):
        print("select 5 for more words")

    select = int(input())
    #    word_prediction_part_two(select)

    #def word_prediction_part_two(select):
    if (select == 1):
        word = keyword1
        is_char = 1
        is_word = 0
        idx = 0
    elif (select == 2):
        word = store[0][0]
        keyword1 = word
        is_char = 0
        is_word = 1
        idx = 0
    elif (select == 3):
        word = store[1][0]
        keyword1 = word
        is_char = 0
        is_word = 1
        idx = 0
    elif (select == 4):
        word = store[2][0]
        keyword1 = word
        is_char = 0
        is_word = 1
        idx = 0
    elif (select == 5):
        idx = idx + 1
        word_prediction(keyword1, keyword2)
    if (is_char == 0):
        flg = 0
        temp = len(sentence)
        for i in range(len(sentence) - 1, 0, -1):
            if (sentence[i] == ' '):
                temp = i
                flg = 1
                break
        if (flg == 1):
            sentence = sentence[:temp + 1]
        sentence = sentence + word
    if (is_char == 1):
        sentence = sentence + take_new_input

    print(sentence)

    print("Enter new word/character")
    take_new_input = raw_input()
    if (take_new_input == ' '):
        sentence = sentence + ' '
        space = space + 1
        main()
    if (is_char):
        keyword1 = keyword1 + take_new_input
        word_prediction(keyword1, '')
    elif (sentence[len(sentence) - 1] != ' ' and is_word == 1):
        word_prediction(keyword1 + take_new_input, '')
    elif (sentence[len(sentence) - 1] == ' ' and is_word == 1):
        word_prediction(keyword1, take_new_input)
Ejemplo n.º 21
0
def test_autocomplete(beginning, letters):
    autocomplete.load()
    print(autocomplete.predict(beginning, letters))
Ejemplo n.º 22
0
def getPredictions(current_buffer, i):
    options = autocomplete.predict(current_buffer, '')[:4]
    finalOptions = [i[0] for i in options]
    print(' {}: \n'.format(current_buffer))
    return finalOptions
Ejemplo n.º 23
0
import autocomplete

# load pickled python Counter objects representing our predictive models
# I use Peter Norvigs big.txt (http://norvig.com/big.txt) to create the predictive models
autocomplete.load()
autocomplete.run_server()
# imagine writing "the b"
autocomplete.predict('the', 'b')

arr = [('blood', 204), ('battle', 185), ('bone', 175), ('best', 149),
       ('body', 149)]

# now you type an "o"

autocomplete.predict('the', 'bo')

[('bone', 175), ('body', 149), ('bones', 122), ('boy', 46), ('bottom', 32),
 ('box', 24), ...]
# pip install autocomplete
import autocomplete

text = input('Type: ')
spaces = len(text.split(' ')) - 2
words = [text.split(' ')[spaces], text.split(' ')[spaces + 1]]
autocomplete.load()
print(autocomplete.predict(words[0], words[1]))
Ejemplo n.º 25
0
def getpred(s1, s2):
    return autocomplete.predict(s1, s2)
Ejemplo n.º 26
0
def word_prediction(keyword1, keyword2):
    global is_word
    global is_char
    global is_first_char
    global sentence
    global word
    global char
    global take_new_input
    global store, st
    global idx
    global space
    global tempkeyword1
    global tempkeyword2
    global flag

    print("word prediction")
    store = autocomplete.predict(keyword1, keyword2)
    st = store

    if (idx == 0):
        store = store[0:3]
    elif (idx > 0):
        store = store[idx * 3:(idx + 1) * 3]

    if (len(store) == 0):
        if (keyword2 == ''):
            print("word 1:" + keyword1)
            level3Buttons[1] = keyword1
            Main_Window._buttons4["1"].config(text=keyword1)
            for i in range(2, 5):
                string = str(i)
                level3Buttons[i] = "empty"
                Main_Window._buttons4[string].config(text="")
        else:
            print("word 1:" + keyword2)
            level3Buttons[1] = keyword2
            Main_Window._buttons4["1"].config(text=keyword2)
            for i in range(2, 5):
                string = str(i)
                level3Buttons[i] = "empty"
                Main_Window._buttons4[string].config(text="")
    else:
        if (keyword2 == ''):
            print("word 1 : " + keyword1)
            level3Buttons[1] = keyword1
            Main_Window._buttons4["1"].config(text=keyword1)
            k = 2
            for keys in store:
                string = str(k)
                print("word {} : {}".format(k, keys[0]))
                level3Buttons[k] = keys[0]
                Main_Window._buttons4[string].config(text=keys[0])
                k = k + 1
            if (k != 5):
                for i in range(k, 5):
                    string = str(i)
                    level3Buttons[i] = "empty"
                    Main_Window._buttons4[string].config(text="")
        else:
            print("word 1 : " + keyword2)
            level3Buttons[1] = keyword2
            Main_Window._buttons4["1"].config(text=keyword2)
            k = 2
            for keys in store:
                string = ""
                string = str(k)
                print("word {} : {}".format(k, keys[0]))
                level3Buttons[k] = keys[0]
                Main_Window._buttons4[string].config(text=keys[0])
                k = k + 1
            if (k != 5):
                for i in range(k, 5):
                    string = ""
                    string = str(i)
                    level3Buttons[i] = "empty"
                    Main_Window._buttons4[string].config(text="")

    tempkeyword1 = keyword1
    tempkeyword2 = keyword2
Ejemplo n.º 27
0
import re
import autocomplete

ser = serial.Serial('COM18', 9600, timeout=1)  # open serial port, set time out equals 1s
print(ser.is_open)
print(ser.name)
autocomplete.load()
engine = pyttsx3.init() 
engine.setProperty('rate', 130)
string=''
string_check= re.compile('[@_!#$%^&*()<>?/\,|}{~:]')
while True:
	data=ser.read().decode('ascii')
	if(data):
		if(data.isalpha() or data.isnumeric() or string_check.search(data) or data==' ' or data=='\n'):
			string+=data
			print(string)
			engine.say(string) 
			engine.runAndWait()
			suggestions = autocomplete.predict('the',string)
			try:
				print(suggestions[0][0])
				engine.say(suggestions[0][0])
				print(suggestions[1][0])
				engine.say(suggestions[1][0])
			except:
				print("No Suggestions")
			engine.runAndWait()
				
			
Ejemplo n.º 28
0
def hello_ml(first_word, last_word):
     return dict(predict(first_word,last_word))
Ejemplo n.º 29
0
 def post(self, sentence):
     words = ["the"] + ["the"] + sentence.split(" ")
     predictions = autocomplete.predict(words[-2], words[-1])
     return list(map(lambda x: x[0], predictions))[:5]
Ejemplo n.º 30
0
 def predict_word(self, first_word="", second_word="") -> []:
     preds = autocomplete.predict(first_word, second_word, top_n=3)
     result = []
     for prediction in preds:
         result.append(prediction[0])
     return result
Ejemplo n.º 31
0
 def index(wordA, wordB):
     return dict(autocomplete.predict(wordA, wordB))