File size: 1,695 Bytes
88968f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa08666
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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()