nitinvig commited on
Commit
4634d4e
·
verified ·
1 Parent(s): e055374

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +13 -274
README.md CHANGED
@@ -1,274 +1,13 @@
1
- # Hindi BPE Encoder - Hugging Face Space
2
-
3
- A Byte Pair Encoding (BPE) tokenizer for Hindi text, deployed as a Hugging Face Space application. Built with a modular architecture for maintainability and extensibility.
4
-
5
- ## Features
6
-
7
- - **Encode**: Convert Hindi text into token IDs and subword tokens
8
- - **Decode**: Convert token IDs back to Hindi text
9
- - **Train**: Train the tokenizer on your custom Hindi text corpus
10
- - **Interactive UI**: User-friendly Gradio interface with tabbed navigation
11
- - **Modular Design**: Clean separation of concerns for easy maintenance and extension
12
-
13
- ## Usage
14
-
15
- ### Running Locally
16
-
17
- 1. Install dependencies:
18
- ```bash
19
- pip install -r requirements.txt
20
- ```
21
-
22
- 2. Run the app:
23
- ```bash
24
- python app.py
25
- ```
26
-
27
- 3. Open your browser to `http://localhost:7860`
28
-
29
- ### Deploying to Hugging Face Spaces
30
-
31
- 1. Create a new Space on [Hugging Face Spaces](https://huggingface.co/spaces)
32
- 2. Select "Gradio" as the SDK
33
- 3. Upload all files from this repository
34
- 4. The app will automatically deploy
35
-
36
- ## Project Structure
37
-
38
- The project follows a modular architecture with clear separation of concerns:
39
-
40
- ```
41
- ERAv4S11/
42
- ├── app.py # Main entry point - orchestrates all components
43
- ├── hindi_bpe_encoder.py # Core tokenizer class (BPE implementation)
44
- ├── hindi_preprocessor.py # Regex-based Hindi text preprocessing
45
- ├── gradio_handlers.py # Event handlers connecting UI to tokenizer
46
- ├── gradio_ui.py # Gradio UI components and layout
47
- ├── constants.py # Configuration constants and sample data
48
- ├── train_tokenizer.py # Script to train tokenizer from corpus
49
- ├── collect_hindi_data.py # Script to download Hindi Wikipedia dataset
50
- ├── requirements.txt # Python dependencies
51
- ├── README.md # This file
52
- ├── hindi_bpe_tokenizer.json # Saved tokenizer (created after training)
53
- └── hindi_training_corpus.txt # Training corpus (created by collect_hindi_data.py)
54
- ```
55
-
56
- ### Module Descriptions
57
-
58
- - **`app.py`**: Main application entry point that initializes the encoder, creates handlers, builds the UI, and launches the Gradio app.
59
-
60
- - **`hindi_bpe_encoder.py`**: Core tokenizer module containing the `HindiBPEEncoder` class. Handles:
61
- - Tokenizer initialization with byte-level BPE and Unicode normalization
62
- - Training on Hindi text corpus with streaming support
63
- - Encoding text to token IDs
64
- - Decoding token IDs back to text
65
-
66
- - **`hindi_preprocessor.py`**: Hindi text preprocessing module with regex-based functions:
67
- - Text normalization (whitespace, punctuation, quotes)
68
- - Hindi-specific character handling
69
- - Streaming support for large files
70
- - Filtering functions for Hindi content
71
-
72
- - **`gradio_handlers.py`**: Contains factory functions that create event handlers bound to the encoder instance. These functions format inputs/outputs for the Gradio interface.
73
-
74
- - **`gradio_ui.py`**: Defines all Gradio UI components:
75
- - Tab creation functions (Encode, Decode, Train)
76
- - Complete app interface builder
77
- - UI layout and styling
78
-
79
- - **`constants.py`**: Centralized configuration:
80
- - Sample Hindi text for training
81
- - Example sentences for the Encode tab
82
- - Vocabulary size limits and defaults
83
- - App configuration constants
84
-
85
- ## How It Works
86
-
87
- The BPE (Byte Pair Encoding) tokenizer:
88
- - Splits Hindi text into subword units
89
- - Handles out-of-vocabulary words by breaking them into known subwords
90
- - Uses whitespace pre-tokenization suitable for Hindi
91
- - Supports special tokens: `<unk>`, `<s>`, `</s>`, `<pad>`, `<mask>`
92
-
93
- ### Technical Implementation Details
94
-
95
- #### Byte-Level BPE with UTF-8 Encoding
96
- - **256 Base Tokens**: The tokenizer starts with exactly 256 base tokens (one for each byte value 0-255)
97
- - **UTF-8 Byte Encoding**: Text is first encoded as UTF-8 bytes, then BPE learns merges on these bytes
98
- - **Universal Coverage**: With `byte_fallback=True`, any Unicode character can be handled, even if not seen during training
99
- - **Why This Matters**: Ensures BPE always learns merges regardless of vocabulary size, and can handle any Hindi character or rare Unicode symbol
100
-
101
- #### Unicode Normalization (NFD)
102
- - **Normalization Form Decomposed (NFD)**: All text is normalized to NFD before tokenization
103
- - **Consistent Representation**: Prevents issues where the same character in different Unicode forms (composed vs decomposed) is treated as different tokens
104
- - **Real-World Impact**: Fixes tokenization issues with words like "छोड़कर" that might otherwise be split incorrectly
105
- - **Example**: "छोड़कर" will always be normalized consistently, preventing `<unk>` tokens in the middle of valid Hindi words
106
-
107
- #### Vocabulary Size
108
- - **Recommended Size**: 10,000 tokens for Hindi (default: 5,000, can be increased)
109
- - **Breakdown**:
110
- - 256 base tokens (bytes 0-255)
111
- - 5 special tokens (`<unk>`, `<s>`, `</s>`, `<pad>`, `<mask>`)
112
- - ~9,739 merged tokens (learned subword units)
113
- - **Coverage**: Larger vocab sizes (10,000+) provide better coverage of Hindi character combinations
114
- - **Trade-offs**:
115
- - Larger vocab = better coverage, fewer `<unk>` tokens, but slower encoding
116
- - Smaller vocab = faster, but may miss rare patterns
117
- - **Min Frequency**: Set to 2 (can be lowered to 1 for better coverage of rare patterns)
118
-
119
- #### Text Preprocessing
120
- The `clean_hindi_text()` function performs regex-based preprocessing:
121
- - **Whitespace Normalization**: Multiple spaces/tabs/newlines → single space
122
- - **Punctuation Handling**: Proper spacing around Hindi punctuation (।, ॥) and standard punctuation
123
- - **Quote Normalization**: Standardizes different quote types (curly quotes → straight quotes)
124
- - **Dash Normalization**: Normalizes different dash types (em dash, en dash → hyphen)
125
- - **Invisible Character Removal**: Removes zero-width spaces and other invisible Unicode characters
126
- - **Purpose**: Ensures consistent text representation for better tokenization quality
127
-
128
- ### Architecture Flow
129
-
130
- ```
131
- User Input (Gradio UI)
132
-
133
- gradio_handlers.py (Format & Validate)
134
-
135
- hindi_bpe_encoder.py (Process)
136
-
137
- gradio_handlers.py (Format Output)
138
-
139
- Gradio UI (Display Results)
140
- ```
141
-
142
- ## Example
143
-
144
- **Input (Hindi):**
145
- ```
146
- हिंदी भारत की राष्ट्रभाषा है।
147
- ```
148
-
149
- **Output:**
150
- - Token IDs: `[1, 2, 3, 4, 5, 6]`
151
- - Tokens: `['हिंदी', 'भारत', 'की', 'राष्ट्रभाषा', 'है', '।']`
152
-
153
- ## Dataset
154
-
155
- ### Training Data Source
156
- - **Dataset**: Hindi Wikipedia from Hugging Face (`wikimedia/wikipedia`, version `20231101.hi`)
157
- - **Collection Script**: `collect_hindi_data.py` - Downloads and processes the dataset
158
- - **Size**: Full dataset contains ~320,000+ articles (~300-500 MB)
159
- - **Processing**:
160
- - Extracts article text
161
- - Cleans using `clean_hindi_text()` for normalization
162
- - Filters very short articles (< 50 characters)
163
- - Saves to `hindi_training_corpus.txt`
164
-
165
- ### Using the Dataset Collector
166
-
167
- ```bash
168
- # Download full Hindi Wikipedia dataset
169
- python3 collect_hindi_data.py
170
-
171
- # Download sample dataset (10,000 articles, faster)
172
- python3 collect_hindi_data.py --sample
173
-
174
- # Specify output file
175
- python3 collect_hindi_data.py --output my_corpus.txt
176
- ```
177
-
178
- The collected corpus can then be used to train the tokenizer:
179
-
180
- ```bash
181
- python3 train_tokenizer.py --corpus hindi_training_corpus.txt --vocab-size 10000
182
- ```
183
-
184
- ## Key Learnings & Best Practices
185
-
186
- ### 1. Vocabulary Size Selection
187
- - **For Hindi**: 10,000 tokens provides good coverage
188
- - **Base Tokens**: Always 256 (one per byte) - these are guaranteed
189
- - **Merged Tokens**: The remaining tokens are learned BPE merges
190
- - **Rule of Thumb**: `vocab_size` should be > 256 to ensure merges are learned
191
- - **Too Small**: If vocab_size < unique characters, BPE just collects characters without learning merges
192
- - **Too Large**: Diminishing returns, slower encoding, but better rare pattern coverage
193
-
194
- ### 2. UTF-8 and Byte-Level BPE
195
- - **Why Byte-Level**: Handles any Unicode character, even rare ones not in training data
196
- - **How It Works**:
197
- 1. Text → UTF-8 bytes
198
- 2. BPE learns merges on byte sequences
199
- 3. Unknown characters automatically encoded as bytes
200
- - **Advantage**: No `<unk>` tokens for valid Unicode characters (with proper normalization)
201
- - **Trade-off**: Slightly larger vocabulary needed, but universal coverage
202
-
203
- ### 3. Unicode Normalization is Critical
204
- - **Problem**: Same character can exist in multiple Unicode forms (composed vs decomposed)
205
- - **Example**: "छोड़कर" might be stored as:
206
- - Composed: `छ` + `ो` + `ड़` + `क` + `र` (single code points)
207
- - Decomposed: `छ` + `ो` + `ड` + `़` + `क` + `र` (base + combining marks)
208
- - **Solution**: NFD normalization ensures consistent representation
209
- - **Impact**: Without normalization, same word might tokenize differently → `<unk>` tokens
210
- - **Best Practice**: Always normalize before training and encoding
211
-
212
- ### 4. Preprocessing Matters
213
- - **Consistency**: Same preprocessing must be used during training and encoding
214
- - **Normalization**: Regex-based cleaning ensures consistent whitespace, punctuation, quotes
215
- - **Filtering**: Can optionally filter non-Hindi content, but be careful not to be too aggressive
216
- - **Performance**: Pre-compiled regex patterns (Python 3.11 optimization) for faster processing
217
-
218
- ### 5. Training Best Practices
219
- - **Large Corpora**: Use streaming mode for files > 100MB to avoid memory issues
220
- - **Min Frequency**: Start with 2, lower to 1 if you need more rare patterns
221
- - **Validation**: Always check that merges were learned (not just character collection)
222
- - **Retraining**: Delete old tokenizer file before retraining with new settings
223
-
224
- ## Development
225
-
226
- ### Extending the Application
227
-
228
- The modular structure makes it easy to extend:
229
-
230
- 1. **Add new features**: Create new handler functions in `gradio_handlers.py` and corresponding UI components in `gradio_ui.py`
231
- 2. **Modify tokenizer**: Update `hindi_bpe_encoder.py` without touching UI code
232
- 3. **Change configuration**: Update constants in `constants.py`
233
- 4. **Customize UI**: Modify `gradio_ui.py` to change layout, styling, or add new tabs
234
-
235
- ### Using the Tokenizer Programmatically
236
-
237
- You can import and use the tokenizer in other Python scripts:
238
-
239
- ```python
240
- from hindi_bpe_encoder import HindiBPEEncoder
241
-
242
- # Initialize encoder
243
- encoder = HindiBPEEncoder()
244
-
245
- # Train on your corpus
246
- encoder.train_tokenizer(hindi_text, vocab_size=5000)
247
-
248
- # Encode text
249
- result = encoder.encode("हिंदी में कुछ लिखें")
250
- print(result["token_ids"])
251
-
252
- # Decode tokens
253
- text = encoder.decode([1, 2, 3, 4])
254
- print(text)
255
- ```
256
-
257
- ## Files
258
-
259
- - `app.py`: Main application entry point
260
- - `hindi_bpe_encoder.py`: Core BPE tokenizer implementation with byte-level BPE and Unicode normalization
261
- - `hindi_preprocessor.py`: Regex-based Hindi text preprocessing and normalization
262
- - `gradio_handlers.py`: Gradio event handlers
263
- - `gradio_ui.py`: Gradio UI components
264
- - `constants.py`: Configuration and constants
265
- - `train_tokenizer.py`: Script to train tokenizer from corpus file
266
- - `collect_hindi_data.py`: Script to download Hindi Wikipedia dataset
267
- - `requirements.txt`: Python dependencies
268
- - `README.md`: This file
269
- - `hindi_bpe_tokenizer.json`: Saved tokenizer (created after training)
270
- - `hindi_training_corpus.txt`: Training corpus (created by collect_hindi_data.py)
271
-
272
- ## License
273
-
274
- MIT License
 
1
+ ---
2
+ title: HindiBPE
3
+ emoji: 💻
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 6.0.1
8
+ app_file: app.py
9
+ pinned: false
10
+ short_description: BPE tokenizer for Hindi
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference