import matplotlib.pyplot as plt
import pandas as pd
import nltk
import re
from collections import Counter
from nltk.tokenize import word_tokenize, sent_tokenize
import spacy
from utils.model_loader import load_spacy, download_nltk_resources
from utils.helpers import fig_to_html, df_to_html_table
def tokenization_handler(text_input):
"""Show tokenization capabilities."""
output_html = []
# Add result area container
output_html.append('
')
output_html.append('')
output_html.append("""
Tokenization is the process of breaking text into smaller units called tokens, which can be words, characters, or subwords.
""")
# Model info
output_html.append("""
Tools Used:
- NLTK - Natural Language Toolkit for basic word and sentence tokenization
- spaCy - Advanced tokenization with linguistic features
- WordPiece - Subword tokenization used by BERT and other transformers
""")
try:
# Ensure NLTK resources are downloaded
download_nltk_resources()
# Original Text
output_html.append('')
output_html.append(f'
')
# Word Tokenization
output_html.append('')
output_html.append('
Breaking text into individual words and punctuation marks.
')
# NLTK Word Tokenization
nltk_tokens = word_tokenize(text_input)
# Format tokens
token_html = ""
for token in nltk_tokens:
token_html += f'
{token}'
output_html.append(f"""
""")
# Token statistics
token_count = len(nltk_tokens)
unique_tokens = len(set([t.lower() for t in nltk_tokens]))
alpha_only = sum(1 for t in nltk_tokens if t.isalpha())
numeric = sum(1 for t in nltk_tokens if t.isnumeric())
punct = sum(1 for t in nltk_tokens if all(c in '.,;:!?-"\'()[]{}' for c in t))
output_html.append(f"""
{token_count}
Total Tokens
{unique_tokens}
Unique Tokens
""")
# Sentence Tokenization
output_html.append('')
output_html.append('
Dividing text into individual sentences.
')
# NLTK Sentence Tokenization
nltk_sentences = sent_tokenize(text_input)
# Format sentences
sentence_html = ""
for i, sentence in enumerate(nltk_sentences):
sentence_html += f'
{i+1} {sentence}
'
output_html.append(f"""
""")
output_html.append(f'
Text contains {len(nltk_sentences)} sentences with an average of {token_count / len(nltk_sentences):.1f} tokens per sentence.
')
# Advanced Tokenization with spaCy
output_html.append('')
output_html.append('
spaCy provides more linguistically-aware tokenization with additional token properties.
')
# Load spaCy model
nlp = load_spacy()
doc = nlp(text_input)
# Create token table
token_data = []
for token in doc:
token_data.append({
'Text': token.text,
'Lemma': token.lemma_,
'POS': token.pos_,
'Tag': token.tag_,
'Dep': token.dep_,
'Shape': token.shape_,
'Alpha': token.is_alpha,
'Stop': token.is_stop
})
token_df = pd.DataFrame(token_data)
# Display interactive table with expandable rows
output_html.append("""
| Token |
Lemma |
POS |
Tag |
Dependency |
Properties |
""")
for token in doc:
# Determine row color based on token type
row_class = ""
if token.is_stop:
row_class = "table-danger" # Light red for stopwords
elif token.pos_ == "VERB":
row_class = "table-success" # Light green for verbs
elif token.pos_ == "NOUN" or token.pos_ == "PROPN":
row_class = "table-primary" # Light blue for nouns
elif token.pos_ == "ADJ":
row_class = "table-warning" # Light yellow for adjectives
output_html.append(f"""
| {token.text} |
{token.lemma_} |
{token.pos_} |
{token.tag_} |
{token.dep_} |
{'Alpha' if token.is_alpha else 'Non-alpha'}
{'Stopword' if token.is_stop else 'Content'}
Shape: {token.shape_}
|
""")
output_html.append("""
""")
# Create visualization for POS distribution
pos_counts = Counter([token.pos_ for token in doc])
# Create bar chart for POS distribution
fig = plt.figure(figsize=(10, 6))
plt.bar(pos_counts.keys(), pos_counts.values(), color='#1976D2')
plt.xlabel('Part of Speech')
plt.ylabel('Count')
plt.title('Part-of-Speech Distribution')
plt.xticks(rotation=45)
plt.tight_layout()
output_html.append('
Token Distribution by Part of Speech
')
output_html.append(fig_to_html(fig))
# Subword Tokenization
output_html.append('')
output_html.append("""
Subword tokenization breaks words into smaller units to handle rare words and morphologically rich languages.
This technique is widely used in modern transformer models like BERT, GPT, etc.
""")
try:
from transformers import BertTokenizer, GPT2Tokenizer
# Load tokenizers
bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
gpt2_tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
# Tokenize with BERT
bert_tokens = bert_tokenizer.tokenize(text_input)
# Tokenize with GPT-2
# GPT-2 doesn't have a special tokenize method like BERT, so we encode and decode
gpt2_encoding = gpt2_tokenizer.encode(text_input)
gpt2_tokens = [gpt2_tokenizer.decode([token]).strip() for token in gpt2_encoding]
# BERT WordPiece Section
output_html.append('
BERT WordPiece
')
output_html.append('
BERT uses WordPiece tokenization which marks subword units with ##.
')
# Create token display
output_html.append('
')
output_html.append('
')
for token in bert_tokens:
if token.startswith("##"):
output_html.append(f'{token}')
else:
output_html.append(f'{token}')
output_html.append('
')
output_html.append(f'
Total BERT tokens: {len(bert_tokens)}
')
# GPT-2 BPE Section
output_html.append('
GPT-2 BPE
')
output_html.append('
GPT-2 uses Byte-Pair Encoding (BPE) tokenization where Ġ represents a space before the token.
')
output_html.append('
')
output_html.append('
')
for token in gpt2_tokens:
if token.startswith("Ġ"):
output_html.append(f'{token}')
else:
output_html.append(f'{token}')
output_html.append('
')
output_html.append(f'
Total GPT-2 tokens: {len(gpt2_tokens)}
')
# Compare token counts
output_html.append('
Token Count Comparison
')
token_count_data = {
'Tokenizer': ['Words (spaces)', 'NLTK', 'spaCy', 'BERT WordPiece', 'GPT-2 BPE'],
'Token Count': [
len(text_input.split()),
len(nltk_tokens),
len(doc),
len(bert_tokens),
len(gpt2_tokens)
]
}
token_count_df = pd.DataFrame(token_count_data)
# Create comparison chart
fig = plt.figure(figsize=(10, 6))
bars = plt.bar(token_count_df['Tokenizer'], token_count_df['Token Count'], color=['#BBDEFB', '#90CAF9', '#64B5F6', '#42A5F5', '#2196F3'])
# Add value labels on top of bars
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.5,
f'{height}',
ha='center', va='bottom')
plt.ylabel('Token Count')
plt.title('Tokenization Comparison by Method')
plt.ylim(0, max(token_count_df['Token Count']) * 1.1) # Add some headroom for labels
plt.tight_layout()
output_html.append(fig_to_html(fig))
# Add token length distribution analysis
output_html.append('
Token Length Distribution
')
token_lengths = [len(token) for token in nltk_tokens]
fig = plt.figure(figsize=(10, 6))
plt.hist(token_lengths, bins=range(1, max(token_lengths) + 2), color='#4CAF50', alpha=0.7)
plt.xlabel('Token Length')
plt.ylabel('Frequency')
plt.title('Token Length Distribution')
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
output_html.append(fig_to_html(fig))
# Add tokenization statistics summary
avg_token_length = sum(token_lengths) / len(token_lengths) if token_lengths else 0
output_html.append(f"""
Tokenization Statistics
{token_count}
Total Tokens
{avg_token_length:.2f}
Average Token Length
{token_count / len(nltk_sentences):.2f}
Tokens per Sentence
""")
except Exception as e:
output_html.append(f"""
Subword Tokenization Error
Failed to load transformer tokenizers: {str(e)}
The transformers library may not be installed or there might be network issues when downloading models.
""")
except Exception as e:
output_html.append(f"""
Error
Failed to process tokenization: {str(e)}
""")
# About Tokenization section
output_html.append("""
What is Tokenization?
Tokenization is the process of breaking down text into smaller units called tokens.
These tokens can be words, subwords, characters, or symbols, depending on the approach.
It's typically the first step in most NLP pipelines.
Types of Tokenization:
- Word Tokenization - Splits text on whitespace and punctuation (with various rules)
- Sentence Tokenization - Divides text into sentences using punctuation and other rules
- Subword Tokenization - Splits words into meaningful subunits (WordPiece, BPE, SentencePiece)
- Character Tokenization - Treats each character as a separate token
Why Subword Tokenization?
Modern NLP models use subword tokenization because:
- It handles out-of-vocabulary words better
- It represents rare words by decomposing them
- It works well for morphologically rich languages
- It balances vocabulary size and token length
""")
output_html.append('
') # Close result-area div
return '\n'.join(output_html)