|
import pronouncing |
|
import string |
|
import copy |
|
import gradio as gr |
|
|
|
CONSONANTS = set(string.ascii_uppercase) - set('AEIOU') |
|
|
|
def get_phones(word): |
|
phones_for_word = pronouncing.phones_for_word(word) |
|
if not phones_for_word: |
|
return None |
|
phones = phones_for_word[0].split() |
|
return phones |
|
|
|
def _get_vowel_index(phones): |
|
for index, phone in enumerate(phones): |
|
if phone[0] in 'AEIOU': |
|
return index |
|
|
|
def _get_consonant_indices(phones): |
|
indices = [] |
|
for index, phone in enumerate(phones): |
|
if phone[0] in CONSONANTS and index < len(phones) - 1: |
|
indices.append(index) |
|
return indices |
|
|
|
def _get_rhyming_tail(phones): |
|
index = _get_vowel_index(phones) |
|
return phones[index:] |
|
|
|
def _slant_rhyme_consonants(phones): |
|
consonant_indices = _get_consonant_indices(phones) |
|
new_phones = copy.copy(phones) |
|
for index in consonant_indices: |
|
new_phones[index] = '.' |
|
return new_phones |
|
|
|
def get_perfect_rhymes(phones): |
|
rhyming_tail = " ".join(_get_rhyming_tail(phones)) |
|
return pronouncing.search(rhyming_tail + "$") |
|
|
|
def get_internal_rhymes(phones): |
|
rhyming_tail = " ".join(_get_rhyming_tail(phones)) |
|
return pronouncing.search(rhyming_tail) |
|
|
|
def get_slant_rhymes(phones): |
|
tail = _get_rhyming_tail(phones) |
|
search = ' '.join(_slant_rhyme_consonants(tail)) |
|
return pronouncing.search(search) |
|
|
|
def find_rhymes(word): |
|
phones = get_phones(word) |
|
if phones is None: |
|
return 'That word is not recognized. Please check the spelling and avoid proper nouns.' |
|
|
|
perfect_rhymes = get_perfect_rhymes(phones) |
|
internal_rhymes = get_internal_rhymes(phones) |
|
slant_rhymes = get_slant_rhymes(phones) |
|
|
|
perfects_without_word = set(perfect_rhymes) - {word} |
|
internals_without_perfects = set(internal_rhymes) - set(perfect_rhymes) - {word} |
|
imperfect_slants = set(slant_rhymes) - set(internal_rhymes) - {word} |
|
|
|
result = "" |
|
if perfects_without_word: |
|
result += 'Perfect rhymes: ' + ", ".join(sorted(perfects_without_word)) + '\n\n' |
|
else: |
|
result += 'No perfect rhymes.\n\n' |
|
|
|
if internals_without_perfects: |
|
result += 'Internal rhymes: ' + ", ".join(sorted(internals_without_perfects)) + '\n\n' |
|
else: |
|
result += 'No internal rhymes.\n\n' |
|
|
|
if imperfect_slants: |
|
result += 'Slant rhymes: ' + ", ".join(sorted(imperfect_slants)) |
|
else: |
|
result += 'No slant rhymes.' |
|
|
|
return result |
|
|
|
|
|
iface = gr.Interface(fn=find_rhymes, inputs="text", outputs="text", description="Enter a word to find rhymes.") |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|