sashdev commited on
Commit
88968f8
·
verified ·
1 Parent(s): 0d70e51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py CHANGED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import nltk
3
+ from nltk.corpus import wordnet
4
+ from nltk.tokenize import word_tokenize
5
+
6
+ # Download necessary resources
7
+ nltk.download('punkt')
8
+ nltk.download('averaged_perceptron_tagger')
9
+ nltk.download('wordnet')
10
+
11
+ # Function to get the WordNet POS tag from the NLTK POS tag
12
+ def get_wordnet_pos(tag):
13
+ if tag.startswith('J'):
14
+ return wordnet.ADJ
15
+ elif tag.startswith('V'):
16
+ return wordnet.VERB
17
+ elif tag.startswith('N'):
18
+ return wordnet.NOUN
19
+ elif tag.startswith('R'):
20
+ return wordnet.ADV
21
+ else:
22
+ return None
23
+
24
+ # Function to find a synonym for a word
25
+ def get_synonym(word, pos):
26
+ synonyms = wordnet.synsets(word, pos=pos)
27
+ if synonyms:
28
+ return synonyms[0].lemmas()[0].name() # Get the first synonym
29
+ return word # Return the original word if no synonym is found
30
+
31
+ # Main function to replace words with synonyms
32
+ def replace_with_synonyms(sentence):
33
+ words = word_tokenize(sentence)
34
+ pos_tags = nltk.pos_tag(words) # Get the part of speech tags
35
+ new_sentence = []
36
+
37
+ for word, tag in pos_tags:
38
+ wordnet_pos = get_wordnet_pos(tag)
39
+ if wordnet_pos: # Only replace if a valid POS tag is found
40
+ synonym = get_synonym(word, wordnet_pos)
41
+ new_sentence.append(synonym)
42
+ else:
43
+ new_sentence.append(word) # Keep the original word if no POS tag
44
+
45
+ return ' '.join(new_sentence)
46
+
47
+ # Gradio interface
48
+ def synonymize(sentence):
49
+ return replace_with_synonyms(sentence)
50
+
51
+ iface = gr.Interface(fn=synonymize, inputs="text", outputs="text", title="Synonym Replacer", description="Enter a sentence, and the app will replace words with synonyms.")
52
+
53
+ iface.launch()