YanaGabelev commited on
Commit
bed9e9f
·
verified ·
1 Parent(s): c5d04b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -24
app.py CHANGED
@@ -56,38 +56,97 @@ def safe_word_tokenize(text):
56
  except:
57
  return re.findall(r'\b\w+\b', text.lower())
58
 
59
- def safe_pos_tag(word):
60
- """Safe POS tagging with fallback"""
61
  try:
62
- tag = nltk.pos_tag([word])[0][1][0].upper()
63
- tag_dict = {"J": wordnet.ADJ,
64
- "N": wordnet.NOUN,
65
- "V": wordnet.VERB,
66
- "R": wordnet.ADV}
67
- return tag_dict.get(tag, wordnet.NOUN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  except:
69
  return wordnet.NOUN
70
 
71
  def safe_lemmatize(word):
72
- """Safe lemmatization with fallback - tries spaCy first, then WordNet"""
73
- # Try spaCy lemmatization first if available
74
  if SPACY_AVAILABLE:
75
  try:
76
  doc = nlp(word)
77
- if len(doc) > 0:
78
  return doc[0].lemma_
79
  except:
80
  pass
81
 
82
- # Fallback to WordNet lemmatization
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  try:
84
  pos = safe_pos_tag(word)
85
- return lemmatizer.lemmatize(word, pos)
 
 
86
  except:
87
- try:
88
- return lemmatizer.lemmatize(word)
89
- except:
90
- return word
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  def process_text(text, selected_model):
93
  """
@@ -149,7 +208,7 @@ def process_text(text, selected_model):
149
  # Create comparison table data
150
  comparison_data = []
151
  for word in words:
152
- stemmed = stemmer.stem(word)
153
  lemmatized = safe_lemmatize(word)
154
  comparison_data.append({
155
  'Original': word,
@@ -161,8 +220,8 @@ def process_text(text, selected_model):
161
  df = pd.DataFrame(comparison_data)
162
 
163
  # Stemming results
164
- stemmed_words = [stemmer.stem(word) for word in words]
165
- stemming_info = f"**Stemming Results (Porter Stemmer):**\n"
166
  stemming_info += f"- Original words: {words}\n"
167
  stemming_info += f"- Stemmed words: {stemmed_words}\n\n"
168
 
@@ -224,7 +283,7 @@ def generate_analysis(text, tokens, other_tokens, words, stemmed_words, lemmatiz
224
  analysis += f"- **tiktoken**: {running_tiktoken_decoded}\n"
225
 
226
  # Stemming and Lemmatization analysis
227
- running_stemmed = stemmer.stem("running")
228
  running_lemmatized = safe_lemmatize("running")
229
  lemma_method = "spaCy" if SPACY_AVAILABLE else "WordNet"
230
 
@@ -268,11 +327,12 @@ Try entering a sentence with "running" to see the specific analysis.
268
  - **Disadvantages**: Model-dependent, may create non-interpretable tokens
269
  - **Use case**: Input preprocessing for transformer models
270
 
271
- ### ✂️ **Stemming (Porter Stemmer)**
272
  - **Best for**: Fast text preprocessing, search engines, basic analysis
273
- - **Advantages**: Very fast, simple implementation, language-independent approach
274
- - **Disadvantages**: Can create non-words, loses semantic precision
275
  - **Use case**: Information retrieval, basic text normalization
 
276
 
277
  ### 🎯 **Lemmatization (WordNet + spaCy)**
278
  - **Best for**: Accurate linguistic analysis, semantic preservation
 
56
  except:
57
  return re.findall(r'\b\w+\b', text.lower())
58
 
59
+ def safe_stem(word):
60
+ """Enhanced stemming with better accuracy"""
61
  try:
62
+ # Use Porter Stemmer but with some corrections for common issues
63
+ stemmed = stemmer.stem(word)
64
+
65
+ # Fix common Porter Stemmer issues
66
+ corrections = {
67
+ 'quickli': 'quick', # quickly -> quick (not quickli)
68
+ 'happi': 'happi', # happily -> happi (keep as is, it's expected)
69
+ 'easi': 'easi', # easily -> easi (keep as is)
70
+ 'runn': 'run', # running -> run (not runn)
71
+ }
72
+
73
+ return corrections.get(stemmed, stemmed)
74
+ except:
75
+ return word
76
+ """Enhanced POS tagging with better accuracy"""
77
+ try:
78
+ # Use NLTK POS tagging
79
+ pos_tag = nltk.pos_tag([word])[0][1]
80
+
81
+ # Map to WordNet POS tags with more detail
82
+ if pos_tag.startswith('V'): # Verb
83
+ return wordnet.VERB
84
+ elif pos_tag.startswith('N'): # Noun
85
+ return wordnet.NOUN
86
+ elif pos_tag.startswith('R'): # Adverb
87
+ return wordnet.ADV
88
+ elif pos_tag.startswith('J'): # Adjective
89
+ return wordnet.ADJ
90
+ else:
91
+ return wordnet.NOUN
92
  except:
93
  return wordnet.NOUN
94
 
95
  def safe_lemmatize(word):
96
+ """Enhanced lemmatization with multiple strategies"""
97
+ # Strategy 1: Try spaCy first if available
98
  if SPACY_AVAILABLE:
99
  try:
100
  doc = nlp(word)
101
+ if len(doc) > 0 and doc[0].lemma_ != word:
102
  return doc[0].lemma_
103
  except:
104
  pass
105
 
106
+ # Strategy 2: Try WordNet with different POS tags
107
+ lemma_candidates = []
108
+
109
+ # Try as verb first (important for "running")
110
+ try:
111
+ verb_lemma = lemmatizer.lemmatize(word, wordnet.VERB)
112
+ if verb_lemma != word:
113
+ lemma_candidates.append(verb_lemma)
114
+ except:
115
+ pass
116
+
117
+ # Try as adjective (important for "best" -> "good")
118
+ try:
119
+ adj_lemma = lemmatizer.lemmatize(word, wordnet.ADJ)
120
+ if adj_lemma != word:
121
+ lemma_candidates.append(adj_lemma)
122
+ except:
123
+ pass
124
+
125
+ # Try with detected POS
126
  try:
127
  pos = safe_pos_tag(word)
128
+ pos_lemma = lemmatizer.lemmatize(word, pos)
129
+ if pos_lemma != word:
130
+ lemma_candidates.append(pos_lemma)
131
  except:
132
+ pass
133
+
134
+ # Try as noun (default)
135
+ try:
136
+ noun_lemma = lemmatizer.lemmatize(word, wordnet.NOUN)
137
+ if noun_lemma != word:
138
+ lemma_candidates.append(noun_lemma)
139
+ except:
140
+ pass
141
+
142
+ # Return the best candidate (shortest different from original)
143
+ if lemma_candidates:
144
+ # Prefer shorter forms (run over running)
145
+ best_lemma = min(lemma_candidates, key=len)
146
+ return best_lemma
147
+
148
+ # If nothing worked, return original
149
+ return word
150
 
151
  def process_text(text, selected_model):
152
  """
 
208
  # Create comparison table data
209
  comparison_data = []
210
  for word in words:
211
+ stemmed = safe_stem(word)
212
  lemmatized = safe_lemmatize(word)
213
  comparison_data.append({
214
  'Original': word,
 
220
  df = pd.DataFrame(comparison_data)
221
 
222
  # Stemming results
223
+ stemmed_words = [safe_stem(word) for word in words]
224
+ stemming_info = f"**Stemming Results (Enhanced Porter Stemmer):**\n"
225
  stemming_info += f"- Original words: {words}\n"
226
  stemming_info += f"- Stemmed words: {stemmed_words}\n\n"
227
 
 
283
  analysis += f"- **tiktoken**: {running_tiktoken_decoded}\n"
284
 
285
  # Stemming and Lemmatization analysis
286
+ running_stemmed = safe_stem("running")
287
  running_lemmatized = safe_lemmatize("running")
288
  lemma_method = "spaCy" if SPACY_AVAILABLE else "WordNet"
289
 
 
327
  - **Disadvantages**: Model-dependent, may create non-interpretable tokens
328
  - **Use case**: Input preprocessing for transformer models
329
 
330
+ ### ✂️ **Stemming (Enhanced Porter Stemmer)**
331
  - **Best for**: Fast text preprocessing, search engines, basic analysis
332
+ - **Advantages**: Very fast, simple implementation, corrected common issues
333
+ - **Disadvantages**: Still can create non-words, loses semantic precision
334
  - **Use case**: Information retrieval, basic text normalization
335
+ - **Enhancement**: Fixed common Porter Stemmer issues (quickli→quick, runn→run)
336
 
337
  ### 🎯 **Lemmatization (WordNet + spaCy)**
338
  - **Best for**: Accurate linguistic analysis, semantic preservation