godsofheaven commited on
Commit
338aa93
·
verified ·
1 Parent(s): 765bef9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ import html
4
+
5
+ import gradio as gr
6
+ from transformers import PreTrainedTokenizerFast
7
+
8
+
9
+ def load_tokenizer():
10
+ tok_path = Path("kn_bpe/kn_bpe_8000.json")
11
+ if not tok_path.exists():
12
+ return None, f"Tokenizer not found at {tok_path}. Run build_kn_bpe.py first."
13
+ tok = PreTrainedTokenizerFast(
14
+ tokenizer_file=str(tok_path),
15
+ unk_token="[UNK]",
16
+ pad_token="[PAD]",
17
+ bos_token="[BOS]",
18
+ eos_token="[EOS]",
19
+ sep_token="[SEP]",
20
+ mask_token="[MASK]",
21
+ )
22
+ return tok, None
23
+
24
+
25
+ tokenizer, load_err = load_tokenizer()
26
+
27
+
28
+ def _colored_tokens_html(tokens):
29
+ if not tokens:
30
+ return ""
31
+ palette = [
32
+ "#e57373", "#64b5f6", "#81c784", "#ffd54f", "#ba68c8",
33
+ "#4db6ac", "#ff8a65", "#9575cd", "#4fc3f7", "#aed581",
34
+ ]
35
+ spans = []
36
+ for i, t in enumerate(tokens):
37
+ color = palette[i % len(palette)]
38
+ safe = html.escape(t)
39
+ spans.append(
40
+ f'<span style="background:{color};padding:2px 4px;border-radius:4px;margin-right:2px;display:inline-block">{safe}</span>'
41
+ )
42
+ return "".join(spans)
43
+
44
+
45
+ def tokenize_single(text: str):
46
+ if load_err:
47
+ return "", "", "", "", "", load_err
48
+ if not text:
49
+ return [], [], "", {"chars": 0, "tokens": 0, "chars_per_token": 0.0}, "", ""
50
+ enc = tokenizer(text)
51
+ tokens = enc.tokens()
52
+ ids = enc["input_ids"]
53
+ decoded = tokenizer.decode(ids, skip_special_tokens=True)
54
+ chars = len(text)
55
+ tok_count = len(ids)
56
+ cpt = round(chars / max(tok_count, 1), 3)
57
+ stats = {"chars": chars, "tokens": tok_count, "chars_per_token": cpt}
58
+ colored_html = _colored_tokens_html(tokens)
59
+ return tokens, ids, decoded, stats, colored_html, ""
60
+
61
+
62
+ def tokenize_batch(multiline_text: str):
63
+ if load_err:
64
+ return "", load_err
65
+ lines = [ln for ln in multiline_text.splitlines() if ln.strip()]
66
+ if not lines:
67
+ return {"input_ids": [], "attention_mask": []}, ""
68
+ batch = tokenizer(lines, padding=True, truncation=True, max_length=256)
69
+ # Return compact preview
70
+ preview = {
71
+ "num_examples": len(lines),
72
+ "seq_len": len(batch["input_ids"][0]) if batch["input_ids"] else 0,
73
+ "sample_input_ids": batch["input_ids"][0][:32] if batch["input_ids"] else [],
74
+ "sample_attention_mask": batch["attention_mask"][0][:32] if batch["attention_mask"] else [],
75
+ }
76
+ return preview, ""
77
+
78
+
79
+ def _colored_ids_html(ids):
80
+ if not ids:
81
+ return ""
82
+ palette = [
83
+ "#e57373", "#64b5f6", "#81c784", "#ffd54f", "#ba68c8",
84
+ "#4db6ac", "#ff8a65", "#9575cd", "#4fc3f7", "#aed581",
85
+ ]
86
+ spans = []
87
+ for i, idv in enumerate(ids):
88
+ color = palette[i % len(palette)]
89
+ safe = html.escape(str(idv))
90
+ spans.append(
91
+ f'<span style="background:{color};padding:2px 6px;border-radius:4px;margin-right:2px;display:inline-block">{safe}</span>'
92
+ )
93
+ return "".join(spans)
94
+
95
+
96
+ def playground_render(text: str, view: str):
97
+ if load_err:
98
+ return "0", "0", "0.0", "<em>Tokenizer not loaded</em>"
99
+ text = text or ""
100
+ enc = tokenizer(text)
101
+ tokens = enc.tokens()
102
+ ids = enc["input_ids"]
103
+ chars = len(text)
104
+ toks = len(ids)
105
+ ratio = round(chars / max(toks, 1), 3)
106
+ if view == "Text":
107
+ body = _colored_tokens_html(tokens)
108
+ elif view == "Token IDs":
109
+ body = _colored_ids_html(ids)
110
+ else:
111
+ body = ""
112
+ return str(toks), str(chars), str(ratio), body
113
+
114
+
115
+ with gr.Blocks(title="The Tokenizer Playground") as app:
116
+ gr.Markdown("# The Tokenizer Playground")
117
+ gr.Markdown("Experiment with different tokenizers (running locally in your browser).")
118
+ if load_err:
119
+ gr.Markdown(f"**Error:** {load_err}")
120
+
121
+ inp = gr.Textbox(lines=10, placeholder="Enter Kannada text here…", show_label=False)
122
+
123
+ # Stats row
124
+ with gr.Row():
125
+ tokens_count = gr.HTML("<div style='text-align:center'><div>TOKENS</div><div style='font-size:36px;font-weight:700'>0</div></div>")
126
+ chars_count = gr.HTML("<div style='text-align:center'><div>CHARACTERS</div><div style='font-size:36px;font-weight:700'>0</div></div>")
127
+ ratio_count = gr.HTML("<div style='text-align:center'><div>COMPRESSION</div><div style='font-size:36px;font-weight:700'>0.0</div></div>")
128
+
129
+ view = gr.Radio(["Text", "Token IDs", "Hide"], value="Text", label=None)
130
+ viz = gr.HTML("")
131
+
132
+ def _update(text, mode):
133
+ tks, chs, ratio, body = playground_render(text, mode)
134
+ tokens_html = f"<div style='text-align:center'><div>TOKENS</div><div style='font-size:36px;font-weight:700'>{tks}</div></div>"
135
+ chars_html = f"<div style='text-align:center'><div>CHARACTERS</div><div style='font-size:36px;font-weight:700'>{chs}</div></div>"
136
+ ratio_html = f"<div style='text-align:center'><div>COMPRESSION</div><div style='font-size:36px;font-weight:700'>{ratio}</div></div>"
137
+ return tokens_html, chars_html, ratio_html, body
138
+
139
+ inp.change(_update, inputs=[inp, view], outputs=[tokens_count, chars_count, ratio_count, viz])
140
+ view.change(_update, inputs=[inp, view], outputs=[tokens_count, chars_count, ratio_count, viz])
141
+
142
+ # Examples
143
+ examples = [
144
+ ["೧೯೫೦ರಲ್ಲಿ ಸ್ವಾಮಿ ಭಾರತಕ್ಕೆ ಹಿಂದಿರುಗಿದರು.", "Text"],
145
+ ["‘ಸ್ವಾಮಿಯಾನ’ ಪುಸ್ತಕದಲ್ಲಿ ಹಲವಾರು ಕ್ಷೇತ್ರದ ಗಣ್ಯರು ಸ್ವಾಮಿಯವರ ಬಗ್ಗೆ ಬರೆದ ಲೇಖನಗಳಿವೆ.", "Text"],
146
+ ["ವೇದ, ವೇದಾಂತ, ಮೀಮಾಂಸೆ, ಶಾಸ್ತ್ರ, ಆಗಮಶಾಸ್ತ್ರ, ಜ್ಯೋತಿಷ್ಯಶಾಸ್ತ್ರ, ಶಿಲ್ಪಶಾಸ್ತ್ರ, ಸಂಗೀತ ಶಾಸ್ತ್ರ, ಹಾಗೂ ಆಯುರ್ವೇದ ಶಾಸ್ತ್ರ ಮುಂತಾದ ಶಾಸ್ತ್ರಗಳನ್ನು ಆಳವಾಗಿ ಅಭ್ಯಸಿಸಿ ಅವುಗಳಲ್ಲಿ ಮೇರು-ಪಾಂಡಿತ್ಯವನ್ನು ಸಂಪಾದಿಸಿದ್ದರು.", "Text"],
147
+ ]
148
+ gr.Examples(
149
+ examples=examples,
150
+ inputs=[inp, view],
151
+ outputs=[tokens_count, chars_count, ratio_count, viz],
152
+ fn=_update,
153
+ cache_examples=False,
154
+ )
155
+
156
+ if __name__ == "__main__":
157
+ try:
158
+ app.launch(server_name="127.0.0.1", server_port=7860)
159
+ except Exception:
160
+ # Fallback: default launch
161
+ app.launch()
162
+
163
+