Dhairyashil Ghatage commited on
Commit
0afd597
·
1 Parent(s): b03d2be

add all required files

Browse files
Files changed (4) hide show
  1. app.py +226 -0
  2. merges_15000.json +0 -0
  3. requirements.txt +4 -0
  4. vocab_15000.json +0 -0
app.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import regex as re
4
+ import json
5
+ import ast
6
+ import pandas as pd
7
+
8
+ def clean_text(text, valid_chars_set, replaced_char=None):
9
+ text = replace_unwanted_chars(text, valid_chars_set, replaced_char)
10
+ #gpt2pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
11
+ gpt2pat = re.compile(r"""
12
+ 's|'t|'re|'ve|'m|'ll|'d| # English contractions
13
+ \s*[\u0900-\u097F]+(?:[\u093E-\u094D\u0950-\u0954\u0962-\u0963]+)*| # Devanagari letters and diacritics with leading spaces
14
+ \s*\d+| # Digits with leading spaces
15
+ [^\s\w\u0900-\u097F]+| # Punctuation and symbols
16
+ \s+ # Whitespace
17
+ """, re.VERBOSE)
18
+ return re.findall(gpt2pat, text)
19
+
20
+ def replace_unwanted_chars(text, valid_chars_set, replaced_char=None):
21
+ # Use list comprehension to quickly replace unwanted characters
22
+ if replaced_char == None:
23
+ replaced_char = ''
24
+ result = ''.join([char if char in valid_chars_set else replaced_char for char in text])
25
+ return result
26
+
27
+ def get_stats(ids, counts=None):
28
+ counts = {} if counts is None else counts
29
+ for pair in zip(ids, ids[1:]):
30
+ counts[pair] = counts.get(pair, 0) + 1
31
+ return counts
32
+
33
+ def merge(ids, pair, idx):
34
+ newids = []
35
+ i = 0
36
+ #print(f"ids {ids} pair {pair} idx {idx}")
37
+ #print("lllr")
38
+ while i < len(ids):
39
+ #print("newids ",newids)
40
+ #if i < len(id) and id[i] == pair[0] and id[i+1] == pair[1]:
41
+ if ids[i] == pair[0] and i < len(ids) - 1 and ids[i+1] == pair[1]:
42
+ newids.append(idx)
43
+ i += 2
44
+ else:
45
+ #print("mer ids-i ",ids[i], i, newids)
46
+ newids.append(ids[i])
47
+ i += 1
48
+ return newids
49
+
50
+ def get_vocab(merges, univ_vocab):
51
+ #vocab = {sr: chr(idx) for sr, idx in enumerate (uni_chars)}
52
+ for (p0, p1), idx in merges.items():
53
+ univ_vocab[idx] = univ_vocab[p0] + univ_vocab[p1]
54
+ return univ_vocab
55
+
56
+ def get_init_vocab(u_ids):
57
+ vocab = {idx: chr(idx) for idx in u_ids}
58
+ #print("init vocab", vocab)
59
+ #print(u_ids)
60
+ return vocab
61
+
62
+ def decode(ids, univ_vocab):
63
+ # given ids , return Python strings
64
+ text = "".join(univ_vocab[idx] for idx in ids)
65
+ return text
66
+
67
+ def encode(text, merges):
68
+ global char_to_int
69
+ # given string, return list of ints
70
+ #print(text)
71
+ tokens = [char_to_int[char] for char in text]
72
+ # list(map(ord, text)) #list(text.encode("utf-8"))
73
+ #print(tokens)
74
+ while len(tokens) >= 2:
75
+ stats = get_stats(tokens)
76
+ #print("stats ", stats)
77
+ pair = min(stats, key=lambda p: merges.get(p, float("inf")))
78
+ if pair not in merges:
79
+ break # nothing else can be merged
80
+ #print("merges",merges)
81
+ idx = merges[pair]
82
+ #print("idx ",idx)
83
+ tokens = merge(tokens, pair, idx)
84
+ #print("encode token ",tokens)
85
+ #print("done endode tok ", tokens)
86
+ return tokens
87
+
88
+ def encode_ordinary(text, merges, valid_char_set):
89
+ """Encoding that ignores any special tokens."""
90
+ # split text into chunks of text by categories defined in regex pattern
91
+ replace_char = chr(191) # inverted char
92
+ text_chunks = clean_text(text,valid_char_set,replace_char)
93
+ # all chunks of text are encoded separately, then results are joined
94
+ ids = []
95
+ for chunk in text_chunks:
96
+ #chunk_bytes = chunk.encode("utf-8") # raw bytes
97
+ chunk_ids = encode(chunk, merges)
98
+ ids.extend(chunk_ids)
99
+ #print("encode ord ",ids)
100
+ return ids
101
+
102
+ def unicode_chars_range(start, end):
103
+ return [chr(i) for i in range(start, end+1)]
104
+
105
+ def list_unicode_chars(sp_list):
106
+ return [chr(i) for i in sp_list]
107
+
108
+ def prepare_init_vocab():
109
+ # functions to list characters in a given Unicode range
110
+ # Devanagari
111
+ special_chars = unicode_chars_range(0x0020, 0x0040)
112
+ punchuation1_chars = unicode_chars_range(0x005B, 0x0060)
113
+ punchuation2_chars = unicode_chars_range(0x007B, 0x007E)
114
+
115
+ # Devanagari
116
+ devanagari_chars = unicode_chars_range(0x0900, 0x097F)
117
+ #print(f"devanagari_chars : {devanagari_chars}")
118
+
119
+ # Devanagari Extended
120
+ devanagari_extended_chars = unicode_chars_range(0xA8E0, 0xA8FF)
121
+ #print(f"devanagari_extended_chars : {devanagari_extended_chars}")
122
+
123
+ # General Punctuations list from wiki page
124
+ # (–,—,―,‗,‛,“,”,„,†,‡,•,…,‰,′,″,‹,›,‼,‾,⁄)
125
+ pun_list = [0x2013,0x2014,0x2015,0x2017,0x2018,0x2019,0x201A,0x201B,0x201C,0x201D,0x201E,0x2020\
126
+ ,0x2021,0x2022,0x2026,0x2030,0x2032,0x2033,0x2039,0x203A,0x203C,0x203E,0x2044,0x204A]
127
+ # append inverted-? and newline
128
+ pun_list.append(0x00BF)
129
+ pun_list.append(10)
130
+ punctuation_chars = list_unicode_chars(pun_list)
131
+
132
+ # Superscripts and Subscripts
133
+ #super_subscript_chars = unicode_chars_range(0x2070, 0x209F)
134
+
135
+ # Combine all characters
136
+ all_chars_list = (devanagari_chars + devanagari_extended_chars + special_chars + punchuation1_chars + \
137
+ punchuation2_chars + punctuation_chars)
138
+
139
+ # Print all characters with their Unicode code points
140
+ #for char in all_chars:
141
+ # print(f"Character: {char}, Unicode: {ord(char)}")
142
+ #init_vocab = {ord(ch1): ch1 for ch1 in (all_chars_list)}
143
+ init_vocab = {ii: ch1 for ii, ch1 in enumerate(all_chars_list)}
144
+ char_to_int = {ch1: ii for ii, ch1 in enumerate(all_chars_list)}
145
+ return set(all_chars_list), init_vocab, char_to_int
146
+
147
+
148
+ valid_char_set, univ_vocab, char_to_int = prepare_init_vocab()
149
+ n_vocab_init = len(univ_vocab)
150
+
151
+ # Function to read and print the contents of a JSON file
152
+ def read_json_file(filename):
153
+ with open(filename, 'r', encoding='utf-8') as file:
154
+ data = json.load(file)
155
+
156
+ converted_data = {ast.literal_eval(k): v for k, v in data.items()}
157
+ return converted_data
158
+
159
+ # File names
160
+ vocab_filename = 'vocab_15000.json'
161
+ merges_filename = 'merges_15000.json'
162
+
163
+ # Read the vocabulary JSON file
164
+ univ_vocab = read_json_file(vocab_filename)
165
+ #print("Vocabulary Data:")
166
+ #print(vocab_data)
167
+
168
+ # Read the merges JSON file
169
+ merges = read_json_file(merges_filename)
170
+ #print("\nMerges Data:")
171
+ #print(merges_data)
172
+
173
+ def tokenize(text):
174
+ global n_orig_corpus_chars, merges
175
+ global valid_char_set, univ_vocab
176
+ #print(" n merges ", num_merges)
177
+ n_orig_corpus_chars = len(text)
178
+
179
+ tokens_corpus = encode_ordinary(text, merges, valid_char_set)
180
+ n_tokens_corpus = len(tokens_corpus)
181
+ #print(" n_tokens_corpus for voc size ", vocab_size, " -- ", n_tokens_corpus)
182
+
183
+ ids_tokens = encode_ordinary(text, merges, valid_char_set)
184
+ #out_text = decode(out_tokens, univ_vocab)
185
+ txt_tokens = [univ_vocab[tok1] for tok1 in ids_tokens]
186
+
187
+ return ids_tokens, txt_tokens
188
+
189
+ #in_text = input("provide some text : ")
190
+ #print(in_text)
191
+ #tokenize(in_text)
192
+
193
+
194
+
195
+ # Streamlit app
196
+ st.title("Marathi Language Tokenizer")
197
+
198
+ # Input text
199
+ input_text = st.text_area("Enter text to tokenize:")
200
+
201
+ st.write("""
202
+ This app can tokenize your input Marathi text. It recognizes devnagari and special characters [unrecognizable input characters appear as inverted-?(question mark)]
203
+ Enter any text in the box below and click "Tokenize" to see the tokens and their corresponding IDs. e.g. \"क्रिकेट हा जगभरातला आणि त्यातही भारतात विशेष लोकप्रिय असलेला खेळ आहे. त्यात यंदा क्रिकेट
204
+ वर्ल्ड कप भारतात होणार असल्याने क्रिकेटरसिकांच्या उत्साहाला उधाण आलं आहे.\"
205
+ """)
206
+
207
+ if st.button("Tokenize"):
208
+ if input_text:
209
+ # Tokenize the input text
210
+ tokens, token_ids = tokenize(input_text)
211
+
212
+ st.write(f"Stats | Number of input characters : {len(input_text)} | Number of tokens : {len(tokens)} | Compression : {len(input_text)/len(tokens)} |" )
213
+
214
+ # Display the tokens and their IDs
215
+ # Create a DataFrame for better readability
216
+ df = pd.DataFrame(list(zip(tokens, token_ids)), columns=["Token", "Token ID"])
217
+
218
+ # Display the tokens and their IDs in a table
219
+ st.write("Tokens and Token IDs:")
220
+ st.dataframe(df)
221
+
222
+ else:
223
+ st.write("Please enter some text to tokenize.")
224
+
225
+
226
+
merges_15000.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pandas
2
+ json
3
+ regex
4
+ streamlit
vocab_15000.json ADDED
The diff for this file is too large to render. See raw diff