File size: 15,404 Bytes
60d4f9d
 
 
 
 
 
 
 
 
 
09cf57c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60d4f9d
1bbf96e
60d4f9d
1bbf96e
 
 
 
 
60d4f9d
1bbf96e
 
 
 
 
60d4f9d
 
 
 
 
 
 
 
 
1bbf96e
 
 
 
 
 
09edd55
aeb8c22
 
09edd55
aeb8c22
 
 
 
 
 
09edd55
 
 
aeb8c22
1e2f6c5
 
 
09cf57c
 
 
aeb8c22
 
09cf57c
 
 
1e2f6c5
 
 
 
09edd55
1e2f6c5
 
 
aeb8c22
1e2f6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60d4f9d
 
aeb8c22
e653dcc
 
 
 
09cf57c
e653dcc
 
09cf57c
e653dcc
09cf57c
e653dcc
 
 
09cf57c
 
 
 
 
 
 
 
e653dcc
 
 
 
 
 
 
 
 
09cf57c
 
 
 
 
 
e653dcc
09cf57c
 
 
 
 
 
 
e653dcc
09cf57c
e653dcc
 
1bbf96e
e653dcc
 
aeb8c22
e653dcc
 
aeb8c22
 
dc47e43
e653dcc
 
 
 
 
dc47e43
e653dcc
 
aeb8c22
218a0d7
aeb8c22
dc47e43
218a0d7
1e2f6c5
 
e653dcc
 
 
09cf57c
 
e653dcc
 
 
 
 
 
 
 
 
 
 
 
60d4f9d
 
09cf57c
60d4f9d
 
09cf57c
60d4f9d
09cf57c
60d4f9d
09cf57c
 
 
 
 
 
 
 
 
 
60d4f9d
09cf57c
60d4f9d
 
 
09cf57c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aeb8c22
 
 
09cf57c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60d4f9d
 
 
09cf57c
 
 
 
 
 
 
60d4f9d
218a0d7
09cf57c
218a0d7
 
09cf57c
218a0d7
60d4f9d
09cf57c
 
 
 
 
 
60d4f9d
09cf57c
60d4f9d
09cf57c
60d4f9d
 
09cf57c
 
 
 
60d4f9d
 
 
09cf57c
 
 
 
 
60d4f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b3552c
 
60d4f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09cf57c
60d4f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4355c29
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import gradio as gr
import pandas as pd
from transformers import AutoTokenizer
import nltk
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
import re

# Try to import tiktoken
try:
    import tiktoken
    TIKTOKEN_AVAILABLE = True
    tiktoken_encoder = tiktoken.get_encoding("cl100k_base")
except ImportError:
    TIKTOKEN_AVAILABLE = False
    print("tiktoken not available - install with: pip install tiktoken")

# Try to import spaCy
try:
    import spacy
    nlp = spacy.load("en_core_web_sm")
    SPACY_AVAILABLE = True
except (ImportError, OSError):
    SPACY_AVAILABLE = False
    print("spaCy not available - install with: pip install spacy && python -m spacy download en_core_web_sm")

# Download required NLTK data
import ssl
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

print("Downloading NLTK data...")
nltk.download('punkt', quiet=False)
nltk.download('wordnet', quiet=False)
nltk.download('averaged_perceptron_tagger', quiet=False)
print("NLTK data downloaded successfully!")

# Initialize tools
stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()

# Load tokenizers
bert_tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
gpt2_tokenizer = AutoTokenizer.from_pretrained('gpt2')

def safe_word_tokenize(text):
    """Safe word tokenization with fallback"""
    try:
        return word_tokenize(text.lower())
    except:
        return re.findall(r'\b\w+\b', text.lower())

def get_wordnet_pos(word):
    """Map POS tag to WordNet POS"""
    try:
        tag = nltk.pos_tag([word])[0][1][0].upper()
        tag_dict = {"J": wordnet.ADJ,
                    "N": wordnet.NOUN,
                    "V": wordnet.VERB,
                    "R": wordnet.ADV}
        return tag_dict.get(tag, wordnet.NOUN)
    except:
        return wordnet.NOUN

def lemmatize_word(word):
    """Simple but effective lemmatization"""
    
    # Try spaCy first if available (most reliable)
    if SPACY_AVAILABLE:
        try:
            doc = nlp(word)
            if len(doc) > 0 and doc[0].lemma_ != '-PRON-':
                return doc[0].lemma_
        except:
            pass
    
    # Try WordNet with all possible POS tags
    candidates = []
    
    # Try as verb (most important for ran, running)
    try:
        verb_lemma = lemmatizer.lemmatize(word, wordnet.VERB)
        if verb_lemma != word:
            candidates.append(verb_lemma)
    except:
        pass
    
    # Try as adjective (important for better)
    try:
        adj_lemma = lemmatizer.lemmatize(word, wordnet.ADJ)
        if adj_lemma != word:
            candidates.append(adj_lemma)
    except:
        pass
    
    # Try as noun
    try:
        noun_lemma = lemmatizer.lemmatize(word, wordnet.NOUN)
        if noun_lemma != word:
            candidates.append(noun_lemma)
    except:
        pass
    
    # Try as adverb
    try:
        adv_lemma = lemmatizer.lemmatize(word, wordnet.ADV)
        if adv_lemma != word:
            candidates.append(adv_lemma)
    except:
        pass
    
    # Return best candidate (shortest one)
    if candidates:
        return min(candidates, key=len)
    
    # If nothing worked, return original
    return word

def process_text(text, selected_model):
    """Main function to process text with tokenization, stemming, and lemmatization"""
    try:
        if not text.strip():
            return "Please enter text for analysis", "", "", pd.DataFrame(), ""
        
        # Tokenization with selected model
        if selected_model == "BERT":
            tokens = bert_tokenizer.tokenize(text)
            token_ids = bert_tokenizer.encode(text, add_special_tokens=True)
            decoded_tokens = bert_tokenizer.convert_ids_to_tokens(token_ids)
            tokenizer_info = f"**BERT (bert-base-uncased) Tokenizer Results:**\n"
            tokenizer_info += f"- Number of tokens: {len(tokens)}\n"
            tokenizer_info += f"- Tokens: {tokens}\n"
            tokenizer_info += f"- Token IDs: {token_ids}\n"
            tokenizer_info += f"- Decoded tokens (with special tokens): {decoded_tokens}\n\n"
            
            # Compare with GPT-2
            gpt2_tokens = gpt2_tokenizer.tokenize(text)
            tokenizer_info += f"**GPT-2 Comparison:**\n"
            tokenizer_info += f"- GPT-2 tokens ({len(gpt2_tokens)}): {gpt2_tokens}\n\n"
            other_tokens = gpt2_tokens
            
        else:  # GPT-2
            tokens = gpt2_tokenizer.tokenize(text)
            token_ids = gpt2_tokenizer.encode(text)
            decoded_tokens = gpt2_tokenizer.convert_ids_to_tokens(token_ids)
            tokenizer_info = f"**GPT-2 Tokenizer Results:**\n"
            tokenizer_info += f"- Number of tokens: {len(tokens)}\n"
            tokenizer_info += f"- Tokens: {tokens}\n"
            tokenizer_info += f"- Token IDs: {token_ids}\n"
            tokenizer_info += f"- Decoded tokens: {decoded_tokens}\n\n"
            
            # Compare with BERT
            bert_tokens = bert_tokenizer.tokenize(text)
            tokenizer_info += f"**BERT Comparison:**\n"
            tokenizer_info += f"- BERT tokens ({len(bert_tokens)}): {bert_tokens}\n\n"
            other_tokens = bert_tokens
        
        # Add tiktoken comparison if available
        if TIKTOKEN_AVAILABLE:
            tiktoken_tokens = tiktoken_encoder.encode(text)
            tiktoken_decoded = [tiktoken_encoder.decode_single_token_bytes(token).decode('utf-8', errors='replace') for token in tiktoken_tokens]
            tokenizer_info += f"**tiktoken (cl100k_base) Comparison:**\n"
            tokenizer_info += f"- tiktoken tokens ({len(tiktoken_tokens)}): {tiktoken_decoded}\n"
            tokenizer_info += f"- Token IDs: {tiktoken_tokens}\n"
        else:
            tokenizer_info += f"**tiktoken not available** - install with: pip install tiktoken\n"
        
        # Word processing for stemming and lemmatization
        words = safe_word_tokenize(text)
        words = [word for word in words if word.isalpha()]
        
        # Create comparison table data - NO HARDCODING
        comparison_data = []
        for word in words:
            stemmed = stemmer.stem(word)  # Pure Porter Stemmer
            lemmatized = lemmatize_word(word)  # Pure lemmatization
            
            comparison_data.append({
                'Original': word,
                'Stemmed': stemmed,
                'Lemmatized': lemmatized
            })
            
        df = pd.DataFrame(comparison_data)
        
        # Results info - NO HARDCODING
        stemmed_words = [stemmer.stem(word) for word in words]
        lemmatized_words = [lemmatize_word(word) for word in words]
        
        stemming_info = f"**Stemming Results (Porter Stemmer):**\n"
        stemming_info += f"- Direct test: 'running' -> '{stemmer.stem('running')}' (should be 'runn')\n"
        stemming_info += f"- Direct test: 'quickly' -> '{stemmer.stem('quickly')}' (should be 'quickli')\n"
        stemming_info += f"- Original words: {words}\n"
        stemming_info += f"- Stemmed words: {stemmed_words}\n\n"
        
        lemmatization_method = "spaCy + WordNet" if SPACY_AVAILABLE else "WordNet only"
        lemmatization_info = f"**Lemmatization Results ({lemmatization_method}):**\n"
        lemmatization_info += f"- Original words: {words}\n"
        lemmatization_info += f"- Lemmatized words: {lemmatized_words}\n\n"
        
        # Analysis and conclusions
        analysis = generate_analysis(text, tokens, other_tokens, words, stemmed_words, lemmatized_words, selected_model)
        
        return tokenizer_info, stemming_info, lemmatization_info, df, analysis
        
    except Exception as e:
        error_msg = f"Error processing text: {str(e)}"
        empty_df = pd.DataFrame()
        return error_msg, error_msg, error_msg, empty_df, error_msg

def generate_analysis(text, tokens, other_tokens, words, stemmed_words, lemmatized_words, selected_model):
    """Generate detailed analysis and conclusions focusing on the assignment requirements"""
    
    analysis = f"""
# Assignment Analysis and Conclusions

## Tokenizer Model Comparison:

### Tokenization Results for: "{text}"
- **{selected_model}**: {len(tokens)} tokens
- **{'GPT-2' if selected_model == 'BERT' else 'BERT'}**: {len(other_tokens)} tokens
"""
    
    if TIKTOKEN_AVAILABLE:
        tiktoken_tokens = tiktoken_encoder.encode(text)
        analysis += f"- **tiktoken (cl100k_base)**: {len(tiktoken_tokens)} tokens\n"
    
    analysis += f"""

### Analysis: How different models treat the word "running"

"""
    
    # Specific analysis for "running"
    if "running" in text.lower():
        # Tokenization analysis
        running_in_bert = [token for token in bert_tokenizer.tokenize("running")]
        running_in_gpt2 = [token for token in gpt2_tokenizer.tokenize("running")]
        
        analysis += f"""
#### Tokenization of the word "running":
- **BERT**: {running_in_bert}
- **GPT-2**: {running_in_gpt2}
"""
        
        if TIKTOKEN_AVAILABLE:
            running_tiktoken = tiktoken_encoder.encode("running")
            running_tiktoken_decoded = [tiktoken_encoder.decode_single_token_bytes(token).decode('utf-8', errors='replace') for token in running_tiktoken]
            analysis += f"- **tiktoken**: {running_tiktoken_decoded}\n"
        
        # Stemming and Lemmatization analysis - NO HARDCODING
        running_stemmed = stemmer.stem("running")  # Pure Porter Stemmer
        running_lemmatized = lemmatize_word("running")  # Pure lemmatization
        lemma_method = "spaCy" if SPACY_AVAILABLE else "WordNet"
        
        analysis += f"""

#### Processing of the word "running":
- **Original**: running
- **Stemmed (Porter)**: {running_stemmed}  
- **Lemmatized ({lemma_method})**: {running_lemmatized}

#### Conclusion: Do all models treat the word "running" the same way?
**No!** Each model handles the word "running" differently:

1. **Tokenization Differences**: 
   - BERT splits into smaller sub-word units using WordPiece
   - GPT-2 may handle it as one unit or split differently using BPE
   - tiktoken (if available) may split completely differently

2. **Stemming vs Lemmatization**:
   - Stemming: "running" β†’ "{running_stemmed}" (mechanical suffix removal)
   - Lemmatization: "running" β†’ "{running_lemmatized}" (contextual base form)

3. **Why the differences?**:
   - **Different training data**: Each model was trained on different datasets
   - **Different algorithms**: WordPiece vs BPE vs tiktoken encoding
   - **Different vocabulary sizes**: Affects how words are split
"""
    else:
        analysis += """
#### Note: The word "running" was not found in the input text.
Try entering a sentence with "running" to see the specific analysis.
"""
    
    analysis += f"""

## When to Use Each Method:

### πŸ”€ **Tokenization**
- **Best for**: Preparing text for specific AI models (BERT, GPT, etc.)
- **Advantages**: Model-optimized, handles unknown words, preserves semantic units
- **Disadvantages**: Model-dependent, may create non-interpretable tokens
- **Use case**: Input preprocessing for transformer models

### βœ‚οΈ **Stemming (Porter Stemmer)**
- **Best for**: Fast text preprocessing, search engines, basic analysis
- **Advantages**: Very fast, simple implementation, language-independent approach
- **Disadvantages**: Can create non-words (like "runn", "quickli"), loses semantic precision
- **Use case**: Information retrieval, basic text normalization
- **Note**: Results like "quickli" and "runn" demonstrate stemming limitations

### 🎯 **Lemmatization (WordNet + spaCy)**
- **Best for**: Accurate linguistic analysis, semantic preservation
- **Advantages**: Returns valid words, considers part-of-speech, linguistically accurate
- **Disadvantages**: Slower processing, requires linguistic resources
- **Use case**: Advanced NLP tasks, semantic analysis, research
- **Note**: This app uses spaCy when available, with WordNet as fallback

## Summary of Results:

### Examples from current text:
"""
    
    # Add specific examples from the processed text
    for i, word in enumerate(words[:5]):  # Show first 5 words
        if i < len(stemmed_words) and i < len(lemmatized_words):
            analysis += f"- **{word}** β†’ Stemmed: *{stemmed_words[i]}* | Lemmatized: *{lemmatized_words[i]}*\n"
    
    analysis += f"""

### Key Takeaways:
1. **No universal approach**: Different models serve different purposes
2. **Context matters**: Lemmatization considers grammar, stemming doesn't
3. **Speed vs accuracy**: Stemming is fast, lemmatization is precise
4. **Model choice**: Use tokenizer that matches your target model
"""
    
    return analysis

# Create Gradio interface
def create_interface():
    with gr.Blocks(title="Interactive Text Processing", theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # 🧠 Interactive Text Processing with Gradio
        
        Application to explore text processing methods: **Tokenization**, **Stemming**, and **Lemmatization**
        
        ---
        """)
        
        with gr.Row():
            with gr.Column(scale=2):
                text_input = gr.Textbox(
                    label="Enter sentence for analysis:",
                    placeholder="The children ran quickly because they were running to their better homes.",
                    value="The children ran quickly because they were running to their better homes.",
                    lines=3
                )
                
                model_choice = gr.Dropdown(
                    choices=["BERT", "GPT-2"],
                    value="BERT",
                    label="Choose Tokenizer Model:"
                )
                
                analyze_btn = gr.Button("πŸ” Analyze", variant="primary", size="lg")
        
        gr.Markdown("---")
        
        with gr.Row():
            with gr.Column():
                tokenization_output = gr.Markdown(label="Tokenization Results")
            
        with gr.Row():
            with gr.Column():
                stemming_output = gr.Markdown(label="Stemming Results")
            with gr.Column():
                lemmatization_output = gr.Markdown(label="Lemmatization Results")
        
        comparison_table = gr.DataFrame(
            label="Comparison Table: Original | Stemmed | Lemmatized",
            headers=["Original", "Stemmed", "Lemmatized"],
            interactive=False
        )
        
        analysis_output = gr.Markdown(label="Analysis and Explanations")
        
        # Event handlers
        analyze_btn.click(
            fn=process_text,
            inputs=[text_input, model_choice],
            outputs=[tokenization_output, stemming_output, lemmatization_output, comparison_table, analysis_output]
        )
        
        # Auto-analyze on text change
        text_input.change(
            fn=process_text,
            inputs=[text_input, model_choice],
            outputs=[tokenization_output, stemming_output, lemmatization_output, comparison_table, analysis_output]
        )
        
        return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch(share=True)