Rhyme / app.py
JaeSwift's picture
Update app.py
b054a29 verified
raw
history blame
2.78 kB
import pronouncing
import string
import itertools
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_rhyming_tail(phones, syllable_count=1):
vowels = [phone for phone in phones if phone[0] in 'AEIOU']
if len(vowels) < syllable_count:
return None # Not enough syllables for the rhyme
return phones[-syllable_count * 2:]
def get_soft_rhymes(phones, syllable_count=1):
"""
Find words that have a similar ending sound but don't match exactly.
"""
rhyming_tail = _get_rhyming_tail(phones, syllable_count)
if not rhyming_tail:
return []
# Generate a "soft rhyme" by allowing slight variations in the ending sounds
search_pattern = " ".join(phone[:-1] + "." for phone in rhyming_tail) # Replace last digit in each phoneme with "."
return pronouncing.search(search_pattern)
def find_rhymes_for_phrase(phrase, syllable_count=1):
# Split phrase into individual words
words = phrase.split()
rhyming_options = []
# Get rhymes for each word in the phrase
for word in words:
phones = get_phones(word)
if phones is None:
rhyming_options.append([f"{word} (Not recognized)"])
continue
# Get perfect and soft rhymes
perfect_rhymes = get_multisyllabic_rhymes(phones, syllable_count)
soft_rhymes = get_soft_rhymes(phones, syllable_count)
# Combine both types of rhymes
all_rhymes = set(perfect_rhymes + soft_rhymes)
if not all_rhymes:
rhyming_options.append([f"{word} (No rhymes found)"])
else:
rhyming_options.append(list(all_rhymes))
# Generate all possible combinations of rhyming words
combined_results = list(itertools.product(*rhyming_options))
# Format combined results as a string
if combined_results:
result_str = f"Rhyming combinations for '{phrase}':\n"
result_str += "\n".join(" ".join(combination) for combination in combined_results)
return result_str
else:
return f"No rhyming combinations found for '{phrase}'"
# Gradio interface
iface = gr.Interface(
fn=lambda phrase, syllables: find_rhymes_for_phrase(phrase, syllables),
inputs=[
gr.Textbox(label="Enter phrase (space-separated words)"),
gr.Slider(1, 3, step=1, label="Number of Syllables")
],
outputs="text",
description="Enter a phrase with any number of words to find multisyllabic rhyming combinations and similar sounds."
)
if __name__ == "__main__":
iface.launch()