ggunio commited on
Commit
2d68769
ยท
verified ยท
1 Parent(s): 64eb0a1

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +377 -0
app.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Intelligent Tokenizer v6.0 - Working Demo for Hugging Face Spaces
5
+ ์‹ค์ œ ์ž‘๋™ํ•˜๋Š” ๋ฐ๋ชจ - ์‹œ๋ฎฌ๋ ˆ์ด์…˜ ์—†์Œ
6
+ """
7
+
8
+ import gradio as gr
9
+ import torch
10
+ import sys
11
+ import io
12
+ from pathlib import Path
13
+ import json
14
+ import time
15
+
16
+ # UTF-8 ์„ค์ •
17
+ if sys.stdout.encoding != 'utf-8':
18
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
19
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
20
+
21
+ # Add path
22
+ sys.path.append(str(Path(__file__).parent))
23
+
24
+ # Import actual modules
25
+ from core.boundary_aware_model import BoundaryAwareTokenizerModel
26
+ from src.core.byte_tokenizer_v6 import ByteTokenizerV6
27
+
28
+ # Device
29
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
30
+
31
+ class IntelligentTokenizerDemo:
32
+ def __init__(self):
33
+ """Initialize the actual model"""
34
+ self.device = device
35
+ self.tokenizer = ByteTokenizerV6()
36
+ self.model = None
37
+ self.load_model()
38
+
39
+ def load_model(self):
40
+ """Load the actual trained model"""
41
+ try:
42
+ # Try loading from pytorch_model.bin first (extracted weights)
43
+ model_path = Path("pytorch_model.bin")
44
+ if not model_path.exists():
45
+ # Fallback to checkpoint
46
+ model_path = Path("checkpoints/latest_checkpoint.pt")
47
+
48
+ if model_path.exists():
49
+ print(f"Loading model from {model_path}...")
50
+ checkpoint = torch.load(model_path, map_location=self.device, weights_only=False)
51
+
52
+ # Get model config
53
+ if 'model_config' in checkpoint:
54
+ model_config = checkpoint['model_config']
55
+ else:
56
+ # Load from config.json
57
+ with open("config.json", "r") as f:
58
+ config = json.load(f)
59
+ model_config = {
60
+ 'vocab_size': config['vocab_size'],
61
+ 'hidden_dim': config.get('decoder_hidden', 768),
62
+ 'num_heads': config['num_heads'],
63
+ 'num_encoder_layers': 5,
64
+ 'num_decoder_layers': config['num_decoder_layers'],
65
+ 'dropout': config['dropout']
66
+ }
67
+
68
+ # Initialize model
69
+ self.model = BoundaryAwareTokenizerModel(**model_config)
70
+
71
+ # Load weights
72
+ if 'model_state_dict' in checkpoint:
73
+ self.model.load_state_dict(checkpoint['model_state_dict'])
74
+ else:
75
+ self.model.load_state_dict(checkpoint)
76
+
77
+ self.model = self.model.to(self.device)
78
+ self.model.eval()
79
+ print("Model loaded successfully!")
80
+
81
+ else:
82
+ print("Warning: No model checkpoint found, using untrained model")
83
+ # Initialize untrained model for testing
84
+ model_config = {
85
+ 'vocab_size': 260,
86
+ 'hidden_dim': 768,
87
+ 'num_heads': 8,
88
+ 'num_encoder_layers': 5,
89
+ 'num_decoder_layers': 6,
90
+ 'dropout': 0.1
91
+ }
92
+ self.model = BoundaryAwareTokenizerModel(**model_config)
93
+ self.model = self.model.to(self.device)
94
+ self.model.eval()
95
+
96
+ except Exception as e:
97
+ print(f"Error loading model: {e}")
98
+ raise
99
+
100
+ def embed_text(self, text):
101
+ """์‹ค์ œ ์ž„๋ฒ ๋”ฉ ์ƒ์„ฑ"""
102
+ if not text:
103
+ return None, "Please enter text"
104
+
105
+ try:
106
+ # Encode text
107
+ encoded = self.tokenizer.encode(text)
108
+ byte_ids = encoded['input_ids']
109
+
110
+ # Truncate if too long
111
+ if len(byte_ids) > 256:
112
+ byte_ids = byte_ids[:256]
113
+ byte_ids[-1] = self.tokenizer.EOS
114
+
115
+ # Prepare tensors
116
+ input_ids = torch.tensor([byte_ids], device=self.device)
117
+ attention_mask = torch.tensor([encoded['attention_mask'][:len(byte_ids)]], device=self.device)
118
+
119
+ # Generate embeddings
120
+ with torch.no_grad():
121
+ encoder_outputs = self.model.encoder(input_ids, attention_mask)
122
+ embeddings = encoder_outputs['last_hidden_state']
123
+
124
+ # Statistics
125
+ original_bytes = len(text.encode('utf-8'))
126
+ compressed_tokens = embeddings.shape[1]
127
+ compression_ratio = original_bytes / compressed_tokens if compressed_tokens > 0 else 0
128
+
129
+ result = f"""โœ… **Embedding Generated Successfully**
130
+
131
+ **Input Text:** {text[:100]}{'...' if len(text) > 100 else ''}
132
+ **Original Size:** {original_bytes} bytes
133
+ **Compressed Size:** {compressed_tokens} tokens
134
+ **Compression Ratio:** {compression_ratio:.2f}x
135
+ **Embedding Shape:** {list(embeddings.shape)}
136
+ **Device:** {self.device}
137
+
138
+ **First 10 values:** {embeddings[0, 0, :10].cpu().numpy().tolist()}
139
+ """
140
+ return embeddings, result
141
+
142
+ except Exception as e:
143
+ return None, f"Error: {str(e)}"
144
+
145
+ def restore_text(self, text):
146
+ """์‹ค์ œ ๋ณต์› ํ…Œ์ŠคํŠธ"""
147
+ if not text:
148
+ return "Please enter text"
149
+
150
+ try:
151
+ # Encode text
152
+ encoded = self.tokenizer.encode(text)
153
+ byte_ids = encoded['input_ids']
154
+
155
+ # Truncate if needed
156
+ if len(byte_ids) > 256:
157
+ byte_ids = byte_ids[:256]
158
+ byte_ids[-1] = self.tokenizer.EOS
159
+ truncated = True
160
+ else:
161
+ truncated = False
162
+
163
+ if len(byte_ids) <= 1:
164
+ return "Text too short for restoration test"
165
+
166
+ # Prepare tensors
167
+ input_ids = torch.tensor([byte_ids], device=self.device)
168
+ attention_mask = torch.tensor([encoded['attention_mask'][:len(byte_ids)]], device=self.device)
169
+
170
+ # Teacher forcing restoration
171
+ with torch.no_grad():
172
+ decoder_input = input_ids[:, :-1]
173
+ labels = input_ids[:, 1:]
174
+
175
+ outputs = self.model(
176
+ input_ids=input_ids,
177
+ attention_mask=attention_mask,
178
+ decoder_input_ids=decoder_input,
179
+ labels=labels,
180
+ use_cross_attention=True
181
+ )
182
+
183
+ # Get predictions
184
+ predictions = torch.argmax(outputs['logits'], dim=-1)
185
+ accuracy = (predictions == labels).float().mean().item()
186
+
187
+ # Decode predictions
188
+ pred_list = predictions[0].cpu().tolist()
189
+ full_sequence = [self.tokenizer.BOS] + pred_list
190
+
191
+ # Convert to text
192
+ filtered = [b for b in full_sequence if 0 <= b < 256]
193
+ if filtered:
194
+ restored_bytes = bytes(filtered)
195
+ restored_text = restored_bytes.decode('utf-8', errors='ignore')
196
+ else:
197
+ restored_text = "[Unable to restore]"
198
+
199
+ result = f"""โœ… **Restoration Test Complete**
200
+
201
+ **Original Text:** {text[:100]}{'...' if len(text) > 100 else ''}
202
+ **Restored Text:** {restored_text[:100]}{'...' if len(restored_text) > 100 else ''}
203
+ **Accuracy:** {accuracy:.1%}
204
+ **Bytes Processed:** {len(byte_ids)}
205
+ {'**Note:** Text was truncated to 256 bytes' if truncated else ''}
206
+
207
+ **Status:** {'Perfect Match! โœจ' if accuracy > 0.95 else 'Good Match' if accuracy > 0.8 else 'Partial Match'}
208
+ """
209
+ return result
210
+
211
+ except Exception as e:
212
+ return f"Error: {str(e)}"
213
+
214
+ def compress_stats(self, text):
215
+ """์••์ถ• ํ†ต๊ณ„ ๋ถ„์„"""
216
+ if not text:
217
+ return "Please enter text"
218
+
219
+ try:
220
+ lines = text.strip().split('\n')
221
+ results = []
222
+
223
+ for line in lines[:10]: # Limit to 10 lines
224
+ if not line.strip():
225
+ continue
226
+
227
+ # Get compression stats
228
+ encoded = self.tokenizer.encode(line)
229
+ byte_ids = encoded['input_ids']
230
+
231
+ if len(byte_ids) > 256:
232
+ byte_ids = byte_ids[:256]
233
+
234
+ input_ids = torch.tensor([byte_ids], device=self.device)
235
+ attention_mask = torch.tensor([encoded['attention_mask'][:len(byte_ids)]], device=self.device)
236
+
237
+ with torch.no_grad():
238
+ encoder_outputs = self.model.encoder(input_ids, attention_mask)
239
+ compressed_size = encoder_outputs['last_hidden_state'].shape[1]
240
+
241
+ original_size = len(line.encode('utf-8'))
242
+ ratio = original_size / compressed_size if compressed_size > 0 else 0
243
+
244
+ results.append({
245
+ 'text': line[:50] + '...' if len(line) > 50 else line,
246
+ 'original': original_size,
247
+ 'compressed': compressed_size,
248
+ 'ratio': ratio
249
+ })
250
+
251
+ # Format results
252
+ output = "**Compression Analysis Results**\n\n"
253
+ output += "| Text | Original | Compressed | Ratio |\n"
254
+ output += "|------|----------|------------|-------|\n"
255
+
256
+ for r in results:
257
+ output += f"| {r['text']} | {r['original']} bytes | {r['compressed']} tokens | {r['ratio']:.2f}x |\n"
258
+
259
+ # Average stats
260
+ if results:
261
+ avg_ratio = sum(r['ratio'] for r in results) / len(results)
262
+ total_original = sum(r['original'] for r in results)
263
+ total_compressed = sum(r['compressed'] for r in results)
264
+
265
+ output += f"\n**Summary:**\n"
266
+ output += f"- Average Compression: {avg_ratio:.2f}x\n"
267
+ output += f"- Total Original: {total_original} bytes\n"
268
+ output += f"- Total Compressed: {total_compressed} tokens\n"
269
+ output += f"- Overall Ratio: {total_original/total_compressed if total_compressed > 0 else 0:.2f}x\n"
270
+
271
+ return output
272
+
273
+ except Exception as e:
274
+ return f"Error: {str(e)}"
275
+
276
+ # Initialize demo
277
+ print("Initializing Intelligent Tokenizer Demo...")
278
+ demo = IntelligentTokenizerDemo()
279
+
280
+ # Gradio Interface
281
+ with gr.Blocks(title="Intelligent Tokenizer v6.0", theme=gr.themes.Base()) as app:
282
+ gr.Markdown("""
283
+ # ๐Ÿš€ Intelligent Tokenizer v6.0 - Live Demo
284
+
285
+ **World's First Pure Learning-Based Byte-Level Tokenizer**
286
+ - No vocabulary files, no language rules - just intelligence!
287
+ - 260 fixed vocab (256 bytes + 4 special tokens)
288
+ - Works with ANY language/script/emoji
289
+ """)
290
+
291
+ with gr.Tab("๐Ÿ”ค Embedding"):
292
+ with gr.Row():
293
+ with gr.Column():
294
+ embed_input = gr.Textbox(
295
+ label="Input Text",
296
+ placeholder="Enter any text in any language...",
297
+ lines=3
298
+ )
299
+ embed_btn = gr.Button("Generate Embedding", variant="primary")
300
+
301
+ with gr.Column():
302
+ embed_output = gr.Markdown(label="Result")
303
+
304
+ embed_btn.click(
305
+ lambda x: demo.embed_text(x)[1],
306
+ inputs=embed_input,
307
+ outputs=embed_output
308
+ )
309
+
310
+ with gr.Tab("๐Ÿ”„ Restoration"):
311
+ with gr.Row():
312
+ with gr.Column():
313
+ restore_input = gr.Textbox(
314
+ label="Input Text",
315
+ placeholder="Enter text to test restoration...",
316
+ lines=3
317
+ )
318
+ restore_btn = gr.Button("Test Restoration", variant="primary")
319
+
320
+ with gr.Column():
321
+ restore_output = gr.Markdown(label="Result")
322
+
323
+ restore_btn.click(
324
+ demo.restore_text,
325
+ inputs=restore_input,
326
+ outputs=restore_output
327
+ )
328
+
329
+ with gr.Tab("๐Ÿ“Š Compression Analysis"):
330
+ with gr.Row():
331
+ with gr.Column():
332
+ compress_input = gr.Textbox(
333
+ label="Input Text (one item per line)",
334
+ placeholder="Enter multiple texts, one per line...",
335
+ lines=5
336
+ )
337
+ compress_btn = gr.Button("Analyze Compression", variant="primary")
338
+
339
+ with gr.Column():
340
+ compress_output = gr.Markdown(label="Analysis")
341
+
342
+ compress_btn.click(
343
+ demo.compress_stats,
344
+ inputs=compress_input,
345
+ outputs=compress_output
346
+ )
347
+
348
+ with gr.Tab("โ„น๏ธ About"):
349
+ gr.Markdown("""
350
+ ## About Intelligent Tokenizer v6.0
351
+
352
+ ### Key Features:
353
+ - **Pure Learning-Based**: No predefined rules or vocabularies
354
+ - **Universal Coverage**: Works with all 204+ languages equally
355
+ - **Compression**: 2-3x currently, targeting 5-10x
356
+ - **Real Model**: This demo uses the actual trained model (1.2GB)
357
+
358
+ ### Architecture:
359
+ - Encoder: 5-layer transformer (512โ†’768 dims)
360
+ - Decoder: 6-layer transformer (768 hidden)
361
+ - Total: ~274M parameters
362
+ - Training: 23 epochs on multilingual data
363
+
364
+ ### Development:
365
+ - Solo developer, 4 months development
366
+ - Trained on personal RTX 3060
367
+ - No prior AI experience
368
+
369
+ ### Links:
370
+ - [GitHub Repository](https://github.com/ggunio/intelligent-tokenizer)
371
+ - [Hugging Face Model](https://huggingface.co/ggunio/intelligent-tokenizer-v6)
372
+ """)
373
+
374
+ if __name__ == "__main__":
375
+ print(f"Running on device: {device}")
376
+ print("Launching Gradio app...")
377
+ app.launch()