|
import gradio as gr |
|
import nltk |
|
from nltk.corpus import wordnet |
|
from nltk.tokenize import word_tokenize |
|
|
|
|
|
nltk.download('punkt') |
|
nltk.download('averaged_perceptron_tagger') |
|
nltk.download('wordnet') |
|
|
|
|
|
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 |
|
|
|
|
|
def get_synonym(word, pos): |
|
synonyms = wordnet.synsets(word, pos=pos) |
|
if synonyms: |
|
return synonyms[0].lemmas()[0].name() |
|
return word |
|
|
|
|
|
def replace_with_synonyms(sentence): |
|
words = word_tokenize(sentence) |
|
pos_tags = nltk.pos_tag(words) |
|
new_sentence = [] |
|
|
|
for word, tag in pos_tags: |
|
wordnet_pos = get_wordnet_pos(tag) |
|
if wordnet_pos: |
|
synonym = get_synonym(word, wordnet_pos) |
|
new_sentence.append(synonym) |
|
else: |
|
new_sentence.append(word) |
|
|
|
return ' '.join(new_sentence) |
|
|
|
|
|
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() |
|
|
|
|