synonyms / app.py
sashdev's picture
Update app.py
aa08666 verified
import gradio as gr
import nltk
from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize
# Download necessary resources
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
# Function to get the WordNet POS tag from the NLTK POS tag
def get_wordnet_pos(tag):
if tag.startswith('J'):
return wordnet.ADJ
elif tag.startswith('V'):
return wordnet.VERB
elif tag.startswith('N'):
return wordnet.NOUN
elif tag.startswith('R'):
return wordnet.ADV
else:
return None
# Function to find a synonym for a word
def get_synonym(word, pos):
synonyms = wordnet.synsets(word, pos=pos)
if synonyms:
return synonyms[0].lemmas()[0].name() # Get the first synonym
return word # Return the original word if no synonym is found
# Main function to replace words with synonyms
def replace_with_synonyms(sentence):
words = word_tokenize(sentence)
pos_tags = nltk.pos_tag(words) # Get the part of speech tags
new_sentence = []
for word, tag in pos_tags:
wordnet_pos = get_wordnet_pos(tag)
if wordnet_pos: # Only replace if a valid POS tag is found
synonym = get_synonym(word, wordnet_pos)
new_sentence.append(synonym)
else:
new_sentence.append(word) # Keep the original word if no POS tag
return ' '.join(new_sentence)
# Gradio interface
def synonymize(sentence):
return replace_with_synonyms(sentence)
iface = gr.Interface(fn=synonymize, inputs="text", outputs="text", title="Synonym Replacer", description="Enter a sentence, and the app will replace words with synonyms.")
iface.launch()