Example #1
0
 def syllable_counter(word):
     count = 0
     if word == '' or word == '\n':
         count = 0
     elif ipa.syllable_count(word) == 0:
         count = len(word) % 3
         if count == 0:
             count = 1
     else:
         count += ipa.syllable_count(word)
     return count
Example #2
0
def phonetic_difficulty(word):
    word = clean(word)
    word_ipa = ipa.convert(word)
    word_ipa = clean(word_ipa)

    vowels = 'iɪeɛæɑouʊʌə'
    dorsals = 'kŋgxw'
    fri_aff_liq = 'rfvszxhθðʃʒlʧʤ'
    rhotic = 'r'

    phon = 0
    i = 0
    for i in range(len(word_ipa)):
        if word_ipa[i] in dorsals:
            phon += 1
        if word_ipa[i] in fri_aff_liq:
            phon += 1
        if word_ipa[i] in rhotic:
            phon += 1
    if word_ipa[len(word_ipa) - 1] not in vowels:
        phon += 1
    if ipa.syllable_count(word) >= 3:
        phon += 1
    if check_clusters(word_ipa) == True:
        phon += 1
    if homorganic(word_ipa) == False:
        phon += 1
    return phon
Example #3
0
                         reverse=False):
             print('{0:<30}{1:<30}'.format(x, freq_dic[x]))
 if x == '3':
     print('-----------------------------------------------------------')
     y = input('Check definition for word: ')
     definitions = get_definition(y)
     for definition in definitions:
         print(definition)
 if x == '4':
     print('-----------------------------------------------------------')
     syllable_count = 0
     word_count = 0  #nie uzywamy len(words) bo nie chcemy liczyć kropek
     for word in words:
         if word.isalpha():
             word_count += 1
             syllable = ipa.syllable_count(word)
             syllable_count = syllable_count + syllable
     sentences_count = len(sentences)
     scores = readability_score(word_count, sentences_count, syllable_count)
     for score in scores:
         print(score)
 if x == '5':
     print('-----------------------------------------------------------')
     y = input('Check phonetic difficulty for word: ')
     difficulty = phonetic_difficulty(y)
     voicing = regressive(y)
     print('Your word difficulty: ', difficulty)
     if difficulty >= 8:
         print('This word is difficult to pronunce.')
     elif difficulty >= 4:
         print('This word is of average difficulty to pronunce.')
Example #4
0
def getvalue(model=model):
    epoch = request.form['epochs']
    word = request.form['words']
    temperature = request.form['temperature']

    num = epoch  # Enter Number of Epochs from 1 to 20
    if num.isdigit() and int(num) <= 20 and int(num) > 0:
        num_epochs = int(num)
        print("Setting Epochs = ", num_epochs)

    else:
        num_epochs = DEFAULT_EPOCHS
        print("Incorrect Input, Setting Epochs = ", num_epochs)

    num = word  # Enter Number of Words from 200 to 1200 after each epoch
    if num.isdigit() and int(num) <= 1600 and int(num) >= 200:
        num_words = int(num)
        print("Setting # of words = ", num_words)

    else:
        num_words = DEFAULT_WORDS
        print("Incorrect Input, Setting Words = ", num_words)

    flt = temperature  # Enter randomizer factor from 0.2 to 1.5
    try:
        temperature = float(flt)
        if temperature >= 0.2 and temperature <= 1.5:
            print("Setting Randomizer Factor = ", temperature)
        else:
            temperature = DEFAULT_TEMP
            print("Incorrect Input, Setting Randomizer Factor = ", temperature)
    except ValueError:
        temperature = DEFAULT_TEMP
        print("Incorrect Input, Setting Randomizer Factor = ", temperature)

    def sample(preds, temperature=1.0):
        preds = np.asarray(preds).astype('float64')
        preds = np.log(preds) / temperature
        exp_preds = np.exp(preds)
        preds = exp_preds / np.sum(exp_preds)
        probas = np.random.multinomial(1, preds, 1)
        return np.argmax(probas)

    def rhyming_words(word):
        if word != '':
            for key in phonem:
                len_key = len(phonem[key])
                for i in range(len(phonem[word])):
                    for j in range(len_key):
                        if word == key or len_key == 0:
                            continue
                        elif len(phonem[word]) == 1:
                            if phonem[word][i][-1] == phonem[key][j][-1]:
                                rhymers.append(key)
                        elif len(phonem[key]) == 2:
                            if phonem[word][i][-2:] == phonem[key][j][-2:]:
                                rhymers.append(key)
                        else:
                            if phonem[word][i][-3:] == phonem[key][j][-3:]:
                                rhymers.append(key)

    #     print(len(rhymers))

    def syllable_counter(word):
        count = 0
        if word == '' or word == '\n':
            count = 0
        elif ipa.syllable_count(word) == 0:
            count = len(word) % 3
            if count == 0:
                count = 1
        else:
            count += ipa.syllable_count(word)
        return count

    import random
    import sys
    import time

    t = time.localtime()
    timestamp = time.strftime('%b-%d-%Y_%H%M', t)
    FILE_NAME = ("poem_output_" + timestamp + ".txt")
    file = open(FILE_NAME, 'a')

    RHYME_CHECK = 5

    model_loss = {}
    model_loss['loss'] = []

    line_count = 0
    quatrain_count = 0
    quatrain = False
    new_line = False
    app_word = ''
    end_of_line = False

    generated_text = ''
    count = 0

    for epoch in range(1, num_epochs + 1):
        generated_text = ''
        generated_list = []
        print('\nepoch', epoch)
        hist = model.fit(x, y, batch_size=128, epochs=1)
        model_loss['loss'].append(hist.history['loss'][0])
        start_index = random.randint(0, len(word_list) - maxlen - 1)
        generated_list = word_list[start_index:start_index + maxlen]

        for word in generated_list:
            generated_text += word + ' '
        generated_text = generated_text.strip()
        print('--- Generating with seed: "' + generated_text + '"')
        file.write('--- Generating with seed: "' + generated_text + '"\n')
        for num in ipa.syllable_count(generated_text):
            count += num
    #    for temperature in [0.5, 1.0, 1.2]:
        print('------ temperature:', temperature)
        file.write('------ temperature: ' + str(temperature) + '\n')
        sys.stdout.write(generated_text)
        file.write(generated_text)

        for i in range(num_words):
            sampled = np.zeros((1, maxlen, len(words)))
            for t, word in enumerate(generated_list):
                sampled[0, t, word_indices[word]] = 1.

            if count >= 10:
                end_of_line = True
                count = 0

            if line_count == 2 and count >= RHYME_CHECK:
                preds = model.predict(sampled, verbose=0)[0] * z1
                next_index = sample(preds, temperature)
                next_word = words[next_index]
                if count + syllable_counter(next_word) >= 10:
                    #                     sys.stdout.write(' THIRD LINE')
                    #                     print(' WORD:', next_word, end='')
                    line_count += 1
                    #                     print(f' LC {line_count} QC {quatrain_count} COUNT {count}', end='')
                    if quatrain_count == 3:
                        line_count += 1
                        quatrain_count = 0
                else:
                    preds = model.predict(sampled, verbose=0)[0]
                    next_index = sample(preds, temperature)
                    next_word = words[next_index]
                    while (count + syllable_counter(next_word)) >= 10:
                        next_index = sample(preds, temperature)
                        next_word = words[next_index]

            elif line_count == 3 and count >= RHYME_CHECK:
                preds = model.predict(sampled, verbose=0)[0] * z2
                next_index = sample(preds, temperature)
                next_word = words[next_index]
                if (count + syllable_counter(next_word) >= 10):
                    #                     sys.stdout.write('     FOURTH LINE')
                    line_count += 1
                    quatrain_count += 1
                else:
                    preds = model.predict(sampled, verbose=0)[0]
                    next_index = sample(preds, temperature)
                    next_word = words[next_index]
                    while (count + syllable_counter(next_word)) >= 10:
                        next_index = sample(preds, temperature)
                        next_word = words[next_index]

            else:
                preds = model.predict(sampled, verbose=0)[0]
                next_index = sample(preds, temperature)
                next_word = words[next_index]

            if count < 10 and next_word == 'eol':
                next_word = ''
                app_word = generated_list[maxlen - 1]
            elif end_of_line:
                app_word = next_word = 'eol'
                end_of_line = False
                count = 0
            else:
                app_word = next_word

            generated_list.append(app_word)
            generated_list = generated_list[1:]

            if new_line and next_word == 'eol':
                next_word = ''
            elif new_line:
                next_word = next_word.capitalize()
                new_line = False
            elif next_word == 'i':
                next_word = next_word.upper()
            elif next_word == 'eol':
                next_word = '\n'
                new_line = True
            if next_word != '':
                sys.stdout.write(' ' + next_word)
                file.write(' ' + next_word)
                #                 engine.say(next_word)
                #                 engine.runAndWait()
                #                 engine.stop()
                syl_num = syllable_counter(next_word)
                count += syl_num

            if count >= 10:
                if line_count == 0:
                    #                     sys.stdout.write('     FIRST LINE')
                    rhymers = []
                    z1 = np.zeros(len(words)) + 0.0001
                    #                     print("\nNext Word:", next_word)
                    r_word = next_word[:].lower()
                    r_word = r_word.strip(",.?!:;-'\"_")
                    #                     print(r_word)
                    rhyming_words(r_word)
                    #                     print(rhymers)
                    for rhyme in rhymers:
                        if rhyme in word_indices:
                            z1[word_indices[rhyme]] = 10000.
                    line_count += 1
                    if quatrain_count == 3:
                        line_count += 1

                elif line_count == 1:
                    #                     sys.stdout.write('  SECOND LINE')
                    rhymers = []
                    z2 = np.zeros(len(words)) + 0.0001
                    #                     print("\nNext Word:", next_word)
                    r_word = next_word[:].lower()
                    r_word = r_word.strip(",.?!:;-'\"_")
                    #                     print(r_word)
                    rhyming_words(r_word)
                    #                     print(rhymers)
                    for rhyme in rhymers:
                        if rhyme in word_indices:
                            z2[word_indices[rhyme]] = 10000.
                    line_count += 1
    #                     print('     LINE COUNT:', line_count, end = '')

                elif line_count == 4:
                    print()
                    file.write('\n')
                    line_count = 0
    file.close()

    return render_template('poemout.html',
                           epoch=num_epochs,
                           word=num_words,
                           t=temperature)
Example #5
0
for epoch in range(1, num_epochs + 1):
    generated_text = ''
    generated_list = []
    print('\nepoch', epoch)
    hist = model.fit(x, y, batch_size=128, epochs=1)
    model_loss['loss'].append(hist.history['loss'][0])
    start_index = random.randint(0, len(word_list) - maxlen - 1)         
    generated_list = word_list[start_index: start_index + maxlen]

    for word in generated_list:
        generated_text += word + ' '
    generated_text =  generated_text.strip()
    print('--- Generating with seed: "' + generated_text + '"')
    file.write('--- Generating with seed: "' + generated_text + '"\n')
    for num in ipa.syllable_count(generated_text):
        count += num
#    for temperature in [0.5, 1.0, 1.2]:                        
    print('------ temperature:', temperature)
    file.write('------ temperature: ' + str(temperature) + '\n')
    sys.stdout.write(generated_text)
    file.write(generated_text)

    for i in range(num_words):                                        
        sampled = np.zeros((1, maxlen, len(words)))             
        for t, word in enumerate(generated_list):               
            sampled[0, t, word_indices[word]] = 1. 
            
        if count >= 10:
            end_of_line = True
            count = 0