Spaces:
Configuration error
Configuration error
from smolagents.tools import Tool | |
import json | |
import string | |
import pronouncing | |
import difflib | |
class ParodyWordSuggestionTool(Tool): | |
name = "parody_word_suggester" | |
description = """Suggests rhyming funny words using CMU dictionary pronunciations. | |
Returns similar-sounding words that rhyme, especially focusing on common vowel sounds.""" | |
inputs = {'target': {'type': 'string', 'description': 'The word you want to find rhyming alternatives for'}, 'word_list_str': {'type': 'string', 'description': 'JSON string of word list (e.g. \'["word1", "word2"]\')'}, 'min_similarity': {'type': 'string', 'description': 'Minimum similarity threshold (0.0-1.0)', 'nullable': True}} | |
output_type = "string" | |
def _has_vowel(self, phone: str) -> bool: | |
"""Check if a phone contains a vowel.""" | |
VOWELS = ['A', 'E', 'I', 'O', 'U'] | |
for vowel in VOWELS: | |
if vowel in phone: | |
return True | |
return False | |
def _get_rhyme_part(self, phones: list) -> list: | |
"""Get the rhyming part of a word (last vowel onwards).""" | |
for i, phone in enumerate(reversed(phones)): | |
if self._has_vowel(phone): | |
return phones[-(i+1):] | |
return phones | |
def forward(self, target: str, word_list_str: str, min_similarity: str = "0.5") -> str: | |
"""Get rhyming word suggestions.""" | |
import pronouncing | |
import string | |
import json | |
from difflib import SequenceMatcher | |
target = target.lower().strip(string.punctuation) | |
min_similarity = float(min_similarity) | |
suggestions = [] | |
# Parse JSON string to list | |
try: | |
words = json.loads(word_list_str) | |
except json.JSONDecodeError: | |
return json.dumps({ | |
"error": "Invalid JSON string for word_list_str", | |
"suggestions": [] | |
}, indent=2) | |
# Get target pronunciation | |
target_phones = pronouncing.phones_for_word(target) | |
if not target_phones: | |
return json.dumps({ | |
"error": f"'{target}' not found in CMU dictionary", | |
"suggestions": [] | |
}, indent=2) | |
target_phones = target_phones[0] | |
target_phone_list = target_phones.split() | |
target_rhyme_part = self._get_rhyme_part(target_phone_list) | |
# Check each word | |
for word in words: | |
word = word.lower().strip(string.punctuation) | |
phones = pronouncing.phones_for_word(word) | |
if phones: | |
word_phones = phones[0] | |
word_phone_list = word_phones.split() | |
word_rhyme_part = self._get_rhyme_part(word_phone_list) | |
# 1. Rhyme score (most important - 60%) | |
# Perfect rhyme if the rhyming parts match exactly | |
rhyme_score = 1.0 if word_rhyme_part == target_rhyme_part else 0.0 | |
# 2. Syllable match (25%) | |
target_syl = pronouncing.syllable_count(target_phones) | |
word_syl = pronouncing.syllable_count(word_phones) | |
syllable_score = 1.0 if target_syl == word_syl else 0.0 | |
# 3. Overall similarity (15%) | |
string_similarity = SequenceMatcher(None, target, word).ratio() | |
# Combined score | |
similarity = (rhyme_score * 0.6) + (syllable_score * 0.25) + (string_similarity * 0.15) | |
if similarity >= min_similarity: | |
suggestions.append({ | |
"word": word, | |
"similarity": round(similarity, 3), | |
"rhyme_match": rhyme_score > 0, | |
"rhyme_score": round(rhyme_score, 3), | |
"syllable_match": syllable_score == 1.0, | |
"string_similarity": round(string_similarity, 3), | |
"syllables": word_syl, | |
"phones": word_phones, | |
"rhyme_part": " ".join(word_rhyme_part) | |
}) | |
# Sort by similarity score descending | |
suggestions.sort(key=lambda x: x["similarity"], reverse=True) | |
result = { | |
"target": target, | |
"target_syllables": pronouncing.syllable_count(target_phones), | |
"target_phones": target_phones, | |
"target_rhyme_part": " ".join(target_rhyme_part), | |
"suggestions": suggestions | |
} | |
return json.dumps(result, indent=2) | |
def __init__(self, *args, **kwargs): | |
self.is_initialized = False | |