YanaGabelev commited on
Commit
aeb8c22
·
verified ·
1 Parent(s): dc47e43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -113
app.py CHANGED
@@ -56,124 +56,44 @@ def safe_word_tokenize(text):
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
- """Improved lemmatization focusing on accuracy"""
97
-
98
- # Strategy 1: Try spaCy first if available (most accurate)
99
  if SPACY_AVAILABLE:
100
  try:
101
  doc = nlp(word)
102
- if len(doc) > 0:
103
- lemma = doc[0].lemma_
104
- # spaCy sometimes returns -PRON-, fix this
105
- if lemma != '-PRON-' and lemma.strip():
106
- return lemma
107
  except:
108
  pass
109
 
110
- # Strategy 2: Manual mappings for common problematic words
111
- manual_lemmas = {
112
- 'are': 'be',
113
- 'is': 'be',
114
- 'was': 'be',
115
- 'were': 'be',
116
- 'been': 'be',
117
- 'being': 'be',
118
- 'better': 'good',
119
- 'best': 'good',
120
- 'worse': 'bad',
121
- 'worst': 'bad',
122
- 'children': 'child',
123
- 'mice': 'mouse',
124
- 'feet': 'foot',
125
- 'teeth': 'tooth',
126
- 'people': 'person',
127
- }
128
-
129
- if word.lower() in manual_lemmas:
130
- return manual_lemmas[word.lower()]
131
-
132
- # Strategy 3: Try WordNet with proper POS detection
133
  try:
134
- # Get POS tag for the word in context
135
- pos_tag = nltk.pos_tag([word])[0][1]
136
-
137
- # Map to WordNet POS
138
- if pos_tag.startswith('V'): # Verb
139
- pos = wordnet.VERB
140
- elif pos_tag.startswith('N'): # Noun
141
- pos = wordnet.NOUN
142
- elif pos_tag.startswith('J'): # Adjective
143
- pos = wordnet.ADJ
144
- elif pos_tag.startswith('R'): # Adverb
145
- pos = wordnet.ADV
146
- else:
147
- pos = wordnet.NOUN
148
-
149
- lemma = lemmatizer.lemmatize(word, pos)
150
- if lemma != word:
151
- return lemma
152
-
153
  except:
154
  pass
155
 
156
- # Strategy 4: Try all POS types and pick the best
157
- candidates = []
158
- for pos in [wordnet.VERB, wordnet.NOUN, wordnet.ADJ, wordnet.ADV]:
159
- try:
160
- candidate = lemmatizer.lemmatize(word, pos)
161
- if candidate != word and candidate not in candidates:
162
- candidates.append(candidate)
163
- except:
164
- continue
165
-
166
- # Return shortest valid candidate
167
- if candidates:
168
- return min(candidates, key=len)
169
-
170
- # Fallback: return original word
171
- return word
172
 
173
  def process_text(text, selected_model):
174
- """
175
- Main function to process text with tokenization, stemming, and lemmatization
176
- """
177
  try:
178
  if not text.strip():
179
  return "Please enter text for analysis", "", "", pd.DataFrame(), ""
@@ -193,7 +113,6 @@ def process_text(text, selected_model):
193
  gpt2_tokens = gpt2_tokenizer.tokenize(text)
194
  tokenizer_info += f"**GPT-2 Comparison:**\n"
195
  tokenizer_info += f"- GPT-2 tokens ({len(gpt2_tokens)}): {gpt2_tokens}\n\n"
196
-
197
  other_tokens = gpt2_tokens
198
 
199
  else: # GPT-2
@@ -210,7 +129,6 @@ def process_text(text, selected_model):
210
  bert_tokens = bert_tokenizer.tokenize(text)
211
  tokenizer_info += f"**BERT Comparison:**\n"
212
  tokenizer_info += f"- BERT tokens ({len(bert_tokens)}): {bert_tokens}\n\n"
213
-
214
  other_tokens = bert_tokens
215
 
216
  # Add tiktoken comparison if available
@@ -227,11 +145,11 @@ def process_text(text, selected_model):
227
  words = safe_word_tokenize(text)
228
  words = [word for word in words if word.isalpha()]
229
 
230
- # Create comparison table data
231
  comparison_data = []
232
  for word in words:
233
- stemmed = stemmer.stem(word)
234
- lemmatized = safe_lemmatize(word)
235
 
236
  comparison_data.append({
237
  'Original': word,
@@ -239,12 +157,11 @@ def process_text(text, selected_model):
239
  'Lemmatized': lemmatized
240
  })
241
 
242
- # Create DataFrame
243
  df = pd.DataFrame(comparison_data)
244
 
245
- # Prepare results info
246
  stemmed_words = [stemmer.stem(word) for word in words]
247
- lemmatized_words = [safe_lemmatize(word) for word in words]
248
 
249
  stemming_info = f"**Stemming Results (Porter Stemmer):**\n"
250
  stemming_info += f"- Original words: {words}\n"
@@ -305,9 +222,9 @@ def generate_analysis(text, tokens, other_tokens, words, stemmed_words, lemmatiz
305
  running_tiktoken_decoded = [tiktoken_encoder.decode_single_token_bytes(token).decode('utf-8', errors='replace') for token in running_tiktoken]
306
  analysis += f"- **tiktoken**: {running_tiktoken_decoded}\n"
307
 
308
- # Stemming and Lemmatization analysis
309
- running_stemmed = stemmer.stem("running")
310
- running_lemmatized = safe_lemmatize("running")
311
  lemma_method = "spaCy" if SPACY_AVAILABLE else "WordNet"
312
 
313
  analysis += f"""
 
56
  except:
57
  return re.findall(r'\b\w+\b', text.lower())
58
 
59
+ def get_wordnet_pos(word):
60
+ """Map POS tag to WordNet POS"""
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 lemmatize_word(word):
72
+ """Pure lemmatization without any hardcoded fixes"""
73
+ # Try spaCy first if available
 
74
  if SPACY_AVAILABLE:
75
  try:
76
  doc = nlp(word)
77
+ if len(doc) > 0 and doc[0].lemma_ != '-PRON-':
78
+ return doc[0].lemma_
 
 
 
79
  except:
80
  pass
81
 
82
+ # Try WordNet with POS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  try:
84
+ pos = get_wordnet_pos(word)
85
+ return lemmatizer.lemmatize(word, pos)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  except:
87
  pass
88
 
89
+ # Basic WordNet fallback
90
+ try:
91
+ return lemmatizer.lemmatize(word)
92
+ except:
93
+ return word
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  def process_text(text, selected_model):
96
+ """Main function to process text with tokenization, stemming, and lemmatization"""
 
 
97
  try:
98
  if not text.strip():
99
  return "Please enter text for analysis", "", "", pd.DataFrame(), ""
 
113
  gpt2_tokens = gpt2_tokenizer.tokenize(text)
114
  tokenizer_info += f"**GPT-2 Comparison:**\n"
115
  tokenizer_info += f"- GPT-2 tokens ({len(gpt2_tokens)}): {gpt2_tokens}\n\n"
 
116
  other_tokens = gpt2_tokens
117
 
118
  else: # GPT-2
 
129
  bert_tokens = bert_tokenizer.tokenize(text)
130
  tokenizer_info += f"**BERT Comparison:**\n"
131
  tokenizer_info += f"- BERT tokens ({len(bert_tokens)}): {bert_tokens}\n\n"
 
132
  other_tokens = bert_tokens
133
 
134
  # Add tiktoken comparison if available
 
145
  words = safe_word_tokenize(text)
146
  words = [word for word in words if word.isalpha()]
147
 
148
+ # Create comparison table data - NO HARDCODING
149
  comparison_data = []
150
  for word in words:
151
+ stemmed = stemmer.stem(word) # Pure Porter Stemmer
152
+ lemmatized = lemmatize_word(word) # Pure lemmatization
153
 
154
  comparison_data.append({
155
  'Original': word,
 
157
  'Lemmatized': lemmatized
158
  })
159
 
 
160
  df = pd.DataFrame(comparison_data)
161
 
162
+ # Results info - NO HARDCODING
163
  stemmed_words = [stemmer.stem(word) for word in words]
164
+ lemmatized_words = [lemmatize_word(word) for word in words]
165
 
166
  stemming_info = f"**Stemming Results (Porter Stemmer):**\n"
167
  stemming_info += f"- Original words: {words}\n"
 
222
  running_tiktoken_decoded = [tiktoken_encoder.decode_single_token_bytes(token).decode('utf-8', errors='replace') for token in running_tiktoken]
223
  analysis += f"- **tiktoken**: {running_tiktoken_decoded}\n"
224
 
225
+ # Stemming and Lemmatization analysis - NO HARDCODING
226
+ running_stemmed = stemmer.stem("running") # Pure Porter Stemmer
227
+ running_lemmatized = lemmatize_word("running") # Pure lemmatization
228
  lemma_method = "spaCy" if SPACY_AVAILABLE else "WordNet"
229
 
230
  analysis += f"""