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)