File size: 8,315 Bytes
d7e7b74 77111fb d7e7b74 |
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 |
"""
Panini Tokenizer - Interactive Demo
HuggingFace Space for comparing Panini Tokenizer against SOTA models.
ArthaLabs 2025
"""
import gradio as gr
from transformers import AutoTokenizer
import sys
import os
# Get the base directory (where app.py is located)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = os.path.join(BASE_DIR, "src")
# Add src to path for Panini Tokenizer
sys.path.insert(0, SRC_DIR)
# Set the STEMS_FILE path BEFORE importing analyzer
# This patches the module-level variable
import json
STEMS_PATH = os.path.join(BASE_DIR, "stems.json")
# Try to import Panini Tokenizer components
PANINI_AVAILABLE = False
PANINI_SPLITTER = None
try:
# Patch the analyzer module's STEMS_FILE path
import analyzer
analyzer.STEMS_FILE = STEMS_PATH
analyzer._STEM_CACHE_LOADED = False # Force reload with correct path
from splitter import SamasaSplitter
PANINI_SPLITTER = SamasaSplitter()
PANINI_AVAILABLE = True
print(f"✅ Panini Tokenizer loaded successfully")
except Exception as e:
print(f"❌ Panini Tokenizer not available: {e}")
import traceback
traceback.print_exc()
# Load comparison tokenizers
TOKENIZERS = {}
def load_tokenizers():
"""Load all tokenizers for comparison."""
global TOKENIZERS
# Sanskrit-BERT (Buddhist Sanskrit)
try:
TOKENIZERS["Sanskrit-BERT"] = AutoTokenizer.from_pretrained(
"Matej/bert-base-buddhist-sanskrit", trust_remote_code=True
)
print("✅ Sanskrit-BERT loaded")
except Exception as e:
print(f"Sanskrit-BERT failed: {e}")
# MuRIL (Google)
try:
TOKENIZERS["MuRIL (Google)"] = AutoTokenizer.from_pretrained(
"google/muril-base-cased", trust_remote_code=True
)
print("✅ MuRIL loaded")
except Exception as e:
print(f"MuRIL failed: {e}")
# Ansh-256k (22 Indic Languages)
try:
TOKENIZERS["Ansh-256k (Indic)"] = AutoTokenizer.from_pretrained(
"LingoIITGN/Ansh-256k", trust_remote_code=True
)
print("✅ Ansh-256k loaded")
except Exception as e:
print(f"Ansh-256k failed: {e}")
# Sanskrit-Qwen2 Tokenizer
try:
TOKENIZERS["Sanskrit-Qwen2"] = AutoTokenizer.from_pretrained(
"diabolic6045/Sanskrit-English-qwen2-tokenizer", trust_remote_code=True
)
print("✅ Sanskrit-Qwen2 loaded")
except Exception as e:
print(f"Sanskrit-Qwen2 failed: {e}")
# Initialize tokenizers
load_tokenizers()
def tokenize_with_panini(text: str) -> list:
"""Tokenize using Panini Tokenizer."""
if not PANINI_AVAILABLE or PANINI_SPLITTER is None:
return ["[Panini not available]"]
try:
tokens = []
words = text.split()
for i, word in enumerate(words):
prefix = "▁" if i == 0 else ""
split_result = PANINI_SPLITTER.split_v4(word) # V1.5: Uses sandhi expansion
if split_result.is_compound and len(split_result.components) > 1:
for j, comp in enumerate(split_result.components):
if j == 0:
tokens.append(prefix + comp)
else:
tokens.append(comp)
else:
tokens.append(prefix + word)
return tokens
except Exception as e:
return [f"[Error: {e}]"]
def tokenize_text(text: str):
"""Tokenize text with all tokenizers and return comparison."""
if not text.strip():
return "Please enter some Sanskrit text (SLP1 transliteration)"
results = []
# Panini Tokenizer
panini_tokens = tokenize_with_panini(text)
results.append({
"name": "🏆 Panini (Ours)",
"count": len(panini_tokens),
"tokens": panini_tokens,
"is_panini": True
})
# Other tokenizers
for name, tok in TOKENIZERS.items():
try:
tokens = tok.tokenize(text)
results.append({
"name": name,
"count": len(tokens),
"tokens": tokens,
"is_panini": False
})
except Exception as e:
results.append({
"name": name,
"count": "Error",
"tokens": [str(e)[:30]],
"is_panini": False
})
# Build card-style output (handles overflow better)
md = "## 📊 Tokenization Results\n\n"
# Summary bar
panini_count = results[0]['count'] if isinstance(results[0]['count'], int) else 0
other_counts = [r['count'] for r in results[1:] if isinstance(r['count'], int)]
if other_counts and panini_count > 0:
avg_other = sum(other_counts) / len(other_counts)
compression = avg_other / panini_count
md += f"**Compression:** Panini uses **{compression:.1f}x fewer tokens** than average\n\n"
md += "---\n\n"
# Each tokenizer as a card
for r in results:
if r['is_panini']:
md += f"### {r['name']} — **{r['count']} tokens**\n"
else:
md += f"### {r['name']} — {r['count']} tokens\n"
# Truncate tokens display to ~60 chars
tokens_str = " | ".join(r['tokens'][:10])
if len(tokens_str) > 80:
tokens_str = tokens_str[:80] + "..."
elif len(r['tokens']) > 10:
tokens_str += " ..."
md += f"```\n{tokens_str}\n```\n\n"
return md
def get_examples():
"""Return example inputs."""
return [
["nirapekzajYAnasAkzAtkArasAmarthyam"],
["tadekaniScitArthavyavasthApanam"],
["svaprakASatvaparaprakASavyavacCedaH"],
["rAmo gacCati"],
["dharme kzetre kurukzetre"],
["parasparApekzApratiyogitvanirUpaNam"],
]
# Build Gradio Interface
with gr.Blocks(
title="Panini Tokenizer - ArthaLabs",
theme=gr.themes.Soft(),
css="""
.container { max-width: 900px; margin: auto; }
.title { text-align: center; }
"""
) as demo:
gr.Markdown(
"""
# 🔤 Panini Tokenizer
### Grammar-First Sanskrit Tokenization by ArthaLabs
Compare our morphology-based tokenizer against state-of-the-art multilingual models.
**Input Format:** SLP1 transliteration (e.g., `rAmo gacCati` not `रामो गच्छति`)
"""
)
with gr.Row():
with gr.Column(scale=3):
text_input = gr.Textbox(
label="Sanskrit Text (SLP1)",
placeholder="Enter Sanskrit text in SLP1 transliteration...",
lines=2,
value="nirapekzajYAnasAkzAtkArasAmarthyam"
)
with gr.Column(scale=1):
submit_btn = gr.Button("🔍 Tokenize", variant="primary", size="lg")
output = gr.Markdown(label="Results")
gr.Examples(
examples=get_examples(),
inputs=text_input,
label="Example Inputs (click to try)"
)
submit_btn.click(
fn=tokenize_text,
inputs=text_input,
outputs=output
)
text_input.submit(
fn=tokenize_text,
inputs=text_input,
outputs=output
)
gr.Markdown(
"""
---
### About
**Panini Tokenizer** uses recursive morphological analysis based on Pāṇinian grammar rules,
not statistical BPE. This results in:
- ✅ **2-4x fewer tokens** for complex compounds
- ✅ **Semantically meaningful** token boundaries
- ✅ **No arbitrary byte-level splits** like `##k`, `##z`, `##ab`
[📖 Model Card](https://huggingface.co/ArthaLabs/panini-tokenizer) |
[📊 Full Benchmarks](https://huggingface.co/ArthaLabs/panini-tokenizer/blob/main/BENCHMARKS.md)
---
*© 2025 ArthaLabs - Apache 2.0 License*
"""
)
if __name__ == "__main__":
demo.launch()
|