File size: 13,833 Bytes
f32f063
f32d4c7
 
 
f32f063
f32d4c7
f32f063
 
61a3b2f
f32f063
f32d4c7
 
 
 
 
532fc72
f32d4c7
f32f063
3567a04
f32f063
 
 
 
f32d4c7
 
 
 
 
 
 
 
 
 
 
 
f32f063
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f32d4c7
59baef6
 
 
7b9de45
d57f9ad
59baef6
7b9de45
532fc72
 
 
7b9de45
59baef6
 
7b9de45
59baef6
 
7b9de45
532fc72
 
 
 
 
 
59baef6
 
d57f9ad
 
 
 
 
532fc72
d57f9ad
 
 
 
 
 
59baef6
 
 
f32f063
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f32d4c7
 
 
 
 
 
 
 
 
 
 
f32f063
 
 
 
 
 
 
 
 
0c3f890
 
 
 
 
d57f9ad
0c3f890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d57f9ad
0c3f890
 
 
 
 
 
 
 
 
 
d57f9ad
0c3f890
 
 
 
 
 
 
 
f32f063
f32d4c7
7b9de45
f32d4c7
 
 
7b9de45
532fc72
7b9de45
532fc72
d57f9ad
7b9de45
 
 
f32f063
6f9d03f
f32d4c7
f32f063
 
 
fcbfd45
f32f063
 
f32d4c7
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
"""
Arabic Tokenizer Arena Pro - Main Application
==============================================
Advanced research & production platform for Arabic tokenization analysis

Run with: python app.py
"""

import gradio as gr

# Import modules
from config import SAMPLE_TEXTS, LEADERBOARD_DATASETS
from styles import CUSTOM_CSS
from tokenizer_manager import tokenizer_manager
from analysis import analyze_single_tokenizer, compare_tokenizers
from leaderboard import run_leaderboard_evaluation, evaluate_submitted_tokenizer, get_cached_leaderboard
from ui_components import generate_about_html


def create_interface():
    """Create the Gradio interface"""
    
    available_tokenizers = tokenizer_manager.get_tokenizer_choices()
    tokenizers_by_type = tokenizer_manager.get_tokenizers_by_type()
    
    with gr.Blocks(
        css=CUSTOM_CSS, 
        title="Arabic Tokenizer Arena Pro", 
        theme=gr.themes.Base(
            primary_hue="green",
            secondary_hue="blue",
            neutral_hue="slate",
            font=["IBM Plex Sans Arabic", "system-ui", "sans-serif"]
        )
    ) as demo:
        
        # Header
        gr.HTML("""
        <div class="header-section">
            <h1>๐ŸŸ๏ธ Arabic Tokenizer Arena Pro</h1>
            <p>Advanced research & production platform for Arabic tokenization analysis</p>
        </div>
        """)
        
        with gr.Tabs():
            # ===== TAB 1: Single Tokenizer Analysis =====
            with gr.TabItem("๐Ÿ”ฌ Single Analysis", id="single"):
                with gr.Row():
                    with gr.Column(scale=1):
                        tokenizer_dropdown = gr.Dropdown(
                            choices=available_tokenizers,
                            value=available_tokenizers[0] if available_tokenizers else None,
                            label="Select Tokenizer",
                            info="Choose a tokenizer to analyze"
                        )
                        
                        sample_dropdown = gr.Dropdown(
                            choices=list(SAMPLE_TEXTS.keys()),
                            label="Sample Texts",
                            info="Select a sample or enter custom text"
                        )
                        
                        input_text = gr.Textbox(
                            lines=4,
                            placeholder="ุงูƒุชุจ ุงู„ู†ุต ุงู„ุนุฑุจูŠ ู‡ู†ุง...\nEnter Arabic text here...",
                            label="Input Text",
                            rtl=True
                        )
                        
                        analyze_btn = gr.Button("๐Ÿ” Analyze", variant="primary", size="lg")
                    
                    with gr.Column(scale=2):
                        info_output = gr.HTML(label="Tokenizer Information")
                
                metrics_output = gr.HTML(label="Evaluation Metrics")
                tokens_output = gr.HTML(label="Token Visualization")
                decoded_output = gr.HTML(label="Decoded Output")
                
                sample_dropdown.change(
                    lambda x: SAMPLE_TEXTS.get(x, ""),
                    inputs=[sample_dropdown],
                    outputs=[input_text]
                )
                
                analyze_btn.click(
                    analyze_single_tokenizer,
                    inputs=[tokenizer_dropdown, input_text],
                    outputs=[info_output, metrics_output, tokens_output, decoded_output]
                )
            
            # ===== TAB 2: Comparison Mode =====
            with gr.TabItem("โš–๏ธ Compare Tokenizers", id="compare"):
                with gr.Row():
                    with gr.Column(scale=1):
                        compare_tokenizers_select = gr.CheckboxGroup(
                            choices=available_tokenizers,
                            value=available_tokenizers[:5] if len(available_tokenizers) >= 5 else available_tokenizers,
                            label="Select Tokenizers to Compare",
                            info="Choose 2 or more tokenizers"
                        )
                        
                        compare_sample = gr.Dropdown(
                            choices=list(SAMPLE_TEXTS.keys()),
                            label="Sample Texts"
                        )
                        
                        compare_text = gr.Textbox(
                            lines=4,
                            placeholder="ุงูƒุชุจ ุงู„ู†ุต ุงู„ุนุฑุจูŠ ู‡ู†ุง...",
                            label="Input Text",
                            rtl=True
                        )
                        
                        compare_btn = gr.Button("โš–๏ธ Compare", variant="primary", size="lg")
                    
                    with gr.Column(scale=2):
                        comparison_output = gr.HTML(label="Comparison Results")
                
                compare_sample.change(
                    lambda x: SAMPLE_TEXTS.get(x, ""),
                    inputs=[compare_sample],
                    outputs=[compare_text]
                )
                
                compare_btn.click(
                    compare_tokenizers,
                    inputs=[compare_tokenizers_select, compare_text],
                    outputs=[comparison_output]
                )
            
            # ===== TAB 3: LEADERBOARD =====
            with gr.TabItem("๐Ÿ† Leaderboard", id="leaderboard"):
                gr.Markdown("""
                ## ๐Ÿ† Arabic Tokenizer Leaderboard

                All tokenizers evaluated on **all 8 Arabic datasets** from HuggingFace (~36,000+ samples total).
                """)

                with gr.Row():
                    status_output = gr.Markdown("โณ Loading cached results...")
                    re_evaluate_btn = gr.Button("๐Ÿ”„ Re-evaluate All", variant="secondary", size="sm")

                gr.Markdown("### ๐Ÿ“Š Leaderboard Results")
                leaderboard_output = gr.HTML()

                gr.Markdown("### ๐Ÿ“ˆ Per-Dataset Breakdown")
                per_dataset_output = gr.HTML()

                re_evaluate_btn.click(
                    fn=run_leaderboard_evaluation,
                    inputs=[],
                    outputs=[leaderboard_output, per_dataset_output, status_output]
                )

                gr.Markdown("""
                ---
                ### ๐Ÿ“– Evaluation Datasets

                | Dataset | Category | Samples |
                |---------|----------|---------|
                | ArabicMMLU | MSA Benchmark | 5,000 |
                | ASTD | Egyptian Dialect | 5,000 |
                | ATHAR | Classical Arabic | 5,000 |
                | ARCD | QA Dataset | 1,395 |
                | Ashaar | Poetry | 5,000 |
                | Hadith | Religious | 5,000 |
                | Arabic Sentiment | Social Media | 5,000 |
                | SANAD | News | 5,000 |
                """)
            
            # ===== TAB 4: Metrics Reference =====
            with gr.TabItem("๐Ÿ“– Metrics Guide", id="guide"):
                gr.Markdown("""
                ## Tokenization Evaluation Metrics Guide
                
                ### Efficiency Metrics
                
                | Metric | Description | Ideal Value | Why It Matters |
                |--------|-------------|-------------|----------------|
                | **Fertility** | Tokens per word | 1.0 | Lower fertility = fewer tokens = faster inference & lower cost |
                | **Compression Ratio** | Bytes per token | Higher is better | Better compression = more efficient encoding |
                | **Chars/Token** | Characters per token | Higher is better | More characters per token = better vocabulary utilization |
                
                ### Coverage Metrics
                
                | Metric | Description | Ideal Value | Why It Matters |
                |--------|-------------|-------------|----------------|
                | **OOV Rate** | Out-of-vocabulary percentage | 0% | Lower OOV = better vocabulary coverage |
                | **STRR** | Single Token Retention Rate | Higher is better | More words preserved as single tokens = better semantic boundaries |
                | **Continued Words Ratio** | Words split into multiple tokens | Lower is better | Fewer splits = better word boundary preservation |
                
                ### Arabic-Specific Metrics
                
                | Metric | Description | Why It Matters |
                |--------|-------------|----------------|
                | **Arabic Fertility** | Tokens per Arabic word | Arabic-specific efficiency measure |
                | **Diacritic Preservation** | Whether tashkeel is preserved | Important for religious & educational texts |
                
                ### Scoring Formula (Leaderboard)
                
                ```
                Score = (Fertility Score ร— 0.45) + (Compression Score ร— 0.35) + (UNK Score ร— 0.20) ร— 100
                ```
                
                Where:
                - **Fertility Score** = 2.0 / fertility (capped 0-1, inverted - lower fertility = higher score)
                - **Compression Score** = compression / 6 (capped 0-1)
                - **UNK Score** = 1 - (unk_ratio ร— 20) (capped 0-1, inverted)
                
                ### Research Background
                
                These metrics are based on recent research including:
                - *"A Comprehensive Analysis of Various Tokenizers for Arabic LLMs"* (2024)
                - *"Evaluating Various Tokenizers for Arabic Text Classification"* (Alyafeai et al.)
                - *"Beyond Fertility: STRR as a Metric for Multilingual Tokenization"* (2025)
                - *"Arabic Stable LM: Adapting Stable LM to Arabic"* (2024)
                """)
            
            # ===== TAB 5: Submit Tokenizer =====
            with gr.TabItem("๐Ÿš€ Submit", id="submit"):
                gr.Markdown("""
                ## ๐Ÿš€ Submit Your Tokenizer

                Evaluate any HuggingFace tokenizer on **all 8 Arabic datasets** and see how it compares.
                """)

                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### Model Information")

                        submit_model_id = gr.Textbox(
                            label="HuggingFace Model ID *",
                            placeholder="e.g., google/gemma-2-9b",
                            info="The model ID from HuggingFace Hub"
                        )

                        submit_model_name = gr.Textbox(
                            label="Display Name (optional)",
                            placeholder="e.g., My Custom Tokenizer",
                            info="Leave empty to use model name"
                        )

                        submit_organization = gr.Textbox(
                            label="Organization (optional)",
                            placeholder="e.g., My Organization",
                            info="Leave empty to auto-detect"
                        )

                        submit_model_type = gr.Dropdown(
                            choices=[
                                "Arabic LLM",
                                "Arabic BERT",
                                "Arabic Tokenizer",
                                "Multilingual LLM",
                                "Custom"
                            ],
                            value="Custom",
                            label="Model Type"
                        )

                        submit_btn = gr.Button("๐Ÿš€ Evaluate Tokenizer", variant="primary", size="lg")

                        submit_status = gr.Markdown("")

                    with gr.Column(scale=2):
                        gr.Markdown("### Evaluation Results")
                        submit_results = gr.HTML()

                submit_btn.click(
                    fn=evaluate_submitted_tokenizer,
                    inputs=[submit_model_id, submit_model_name, submit_organization, submit_model_type],
                    outputs=[submit_results, submit_status]
                )

                gr.Markdown("""
                ---
                ### ๐Ÿ“‹ Submission Guidelines

                - **Model ID**: Must be a valid HuggingFace model ID (e.g., `organization/model-name`)
                - **Tokenizer**: The model must have a tokenizer that can be loaded with `AutoTokenizer`
                - **Public Models**: Only public models on HuggingFace Hub are supported
                - **Evaluation**: Your tokenizer will be evaluated on all 8 Arabic datasets (~36,000+ samples)

                ### ๐Ÿ’ก Tips

                - Lower fertility scores indicate better Arabic tokenization efficiency
                - Compare your results with the leaderboard to see how your tokenizer ranks
                """)

            # ===== TAB 6: About =====
            with gr.TabItem("โ„น๏ธ About", id="about"):
                about_html = generate_about_html(
                    tokenizers_by_type,
                    len(available_tokenizers)
                )
                gr.HTML(about_html)

        # Load cached leaderboard results on page load (fast)
        demo.load(
            fn=get_cached_leaderboard,
            inputs=[],
            outputs=[leaderboard_output, per_dataset_output, status_output]
        )

        return demo


# ============================================================================
# MAIN
# ============================================================================

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