CodeIsAbstract commited on
Commit
6114ead
·
verified ·
1 Parent(s): b95bd7b

Upload better_decoder.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. better_decoder.py +850 -0
better_decoder.py ADDED
@@ -0,0 +1,850 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import os
6
+ import sys
7
+ import json
8
+ from typing import List, Tuple, Optional, Dict
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+
13
+ from model import HybridTimeScaleConfig
14
+ from train_split_model import (
15
+ BinaryBoundaryModel,
16
+ SLP1_CHARS,
17
+ char_to_idx,
18
+ PAD_ID,
19
+ VOCAB_SIZE,
20
+ )
21
+
22
+ from vidyut.sandhi import Splitter
23
+ from vidyut.kosha import Kosha, PadaEntry
24
+ from vidyut import kosha as kosha_mod, cheda as cheda_mod
25
+ from SanskritTokenizer.cache import get_default_data_path
26
+ from vidyut.prakriya import Vyakarana
27
+ from vidyut import lipi
28
+ from sanskrit_parser.base.sanskrit_base import SanskritImmutableString
29
+ from sanskrit_parser.parser.sandhi import Sandhi
30
+ import logging
31
+ logger = logging.getLogger("sanskrit_parser")
32
+ logger.setLevel(logging.WARNING)
33
+
34
+
35
+ data_path = get_default_data_path()
36
+ rules_csv = os.path.join(data_path, "sandhi", "rules.csv")
37
+ _splitter = Splitter.from_csv(rules_csv)
38
+ _sandhi = Sandhi()
39
+ _kosha = Kosha(data_path+'/kosha')
40
+ chedaka = cheda_mod.Chedaka(data_path)
41
+ vyakarana = Vyakarana()
42
+ import re
43
+ _filter = lambda word: [vyakarana.derive(_kosha.get(word)[0])[i].text for i in range(len(vyakarana.derive(_kosha.get(word)[0]))) if vyakarana.derive(_kosha.get(word)[0])[i].text == word]
44
+ _make_normal = lambda word: re.sub('s$', '', word)
45
+ _filter = lambda word: [vyakarana.derive(_kosha.get(re.sub('M$', 'm', word))[0])[i].text for i in range(len(vyakarana.derive(_kosha.get(re.sub('M$', 'm', word))[0]))) if vyakarana.derive(_kosha.get(re.sub('M$', 'm', word))[0])[i].text == re.sub('M$', 'm', word)]
46
+ _check = lambda word: _make_normal(word) == _filter(_make_normal(word))[0]
47
+
48
+ def predict(model, text: str, delay: int=2) -> torch.Tensor:
49
+ model.eval()
50
+ device = next(model.parameters()).device
51
+
52
+ # Build input: real chars + N pad chars at end
53
+ N = delay
54
+ L = len(text)
55
+ total_len = L + N
56
+
57
+ input_ids = torch.tensor(
58
+ [[char_to_idx.get(c, PAD_ID) for c in text] + [PAD_ID] * N],
59
+ dtype=torch.long, device=device,
60
+ )
61
+ attention_mask = torch.ones(total_len, dtype=torch.long, device=device).unsqueeze(0)
62
+ # Mark appended pads as valid for model processing (so it can predict
63
+ # boundaries in the last N chars of real text)
64
+ attention_mask[0, L:] = 1 # keep pads in attention
65
+
66
+ with torch.no_grad():
67
+ output = model(input_ids=input_ids, attention_mask=attention_mask)
68
+ raw_probs = torch.sigmoid(output["logits"][0]).cpu() # (total_len,)
69
+
70
+ # Shift: output at position bnd+N predicts for position bnd
71
+ # So probs[bnd] = raw_probs[bnd + N]
72
+ probs = torch.zeros(L)
73
+ for bnd in range(L):
74
+ if bnd + N < total_len:
75
+ probs[bnd] = raw_probs[bnd + N]
76
+
77
+ return probs
78
+
79
+ def predicted_pos(model, text, threshold=0.85, delay=2, send_refined=True):
80
+ prob = predict(model, text, delay=delay)
81
+ base_pos = torch.flatten(torch.nonzero(prob > threshold))
82
+ refined_prob = prob_refiner(prob, threshold)
83
+ return refined_prob if send_refined else base_pos, prob
84
+
85
+ import torch
86
+ from typing import List, Union
87
+
88
+ def prob_refiner(prob: Union[torch.Tensor, List[float]], threshold: float = 0.85) -> torch.Tensor:
89
+ """
90
+ Refines probability tensors into split indices using custom domain heuristics:
91
+ 1. Isolated low-probability spikes (e.g. [0, 0, 0.5, 0]) are accepted.
92
+ 2. Drops below 50% of the previous value break continuous runs.
93
+ 3. Triplets (e.g. [0.9, 0.95, 0.9] or [0.9, 0.7, 0.9]) discard the center and pick outer elements.
94
+ 4. Continuous runs >= threshold are grouped in pairs of 2, picking the 2nd index per group.
95
+
96
+ Args:
97
+ prob: 1D probability sequence (PyTorch Tensor or List).
98
+ threshold: High-confidence threshold (default: 0.85).
99
+
100
+ Returns:
101
+ 1D torch.LongTensor of accepted split candidate indices.
102
+ """
103
+ if isinstance(prob, list):
104
+ prob = torch.tensor(prob, dtype=torch.float32)
105
+ elif not isinstance(prob, torch.Tensor):
106
+ prob = torch.as_tensor(prob, dtype=torch.float32)
107
+
108
+ n = len(prob)
109
+ if n == 0:
110
+ return torch.tensor([], dtype=torch.long)
111
+
112
+ candidates = []
113
+
114
+ # -------------------------------------------------------------
115
+ # Rule 1: Accept isolated spikes significantly larger than 0 surroundings
116
+ # -------------------------------------------------------------
117
+ for i in range(n):
118
+ val = prob[i].item()
119
+ if 0.3 < val < threshold:
120
+ left = prob[i - 1].item() if i > 0 else 0.0
121
+ right = prob[i + 1].item() if i < n - 1 else 0.0
122
+
123
+ # If both surrounding values are <= half of current value (or zero)
124
+ if left <= (val / 2.0) and right <= (val / 2.0):
125
+ candidates.append(i)
126
+
127
+ # -------------------------------------------------------------
128
+ # Rule 2: Collect high-confidence indices and break on >50% relative drops
129
+ # -------------------------------------------------------------
130
+ above_thresh = (prob >= threshold).nonzero(as_tuple=True)[0].tolist()
131
+
132
+ if not above_thresh:
133
+ return torch.tensor(sorted(list(set(candidates))), dtype=torch.long)
134
+
135
+ # Group consecutive indices into continuous blocks
136
+ blocks = []
137
+ current_block = [above_thresh[0]]
138
+
139
+ for idx in above_thresh[1:]:
140
+ prev_idx = current_block[-1]
141
+
142
+ # Check if adjacent AND probability hasn't dropped below half of previous
143
+ if idx == prev_idx + 1:
144
+ if prob[idx].item() < (prob[prev_idx].item() * 0.5):
145
+ # Prob dropped below 50% of previous -> end current block & start new block
146
+ blocks.append(current_block)
147
+ current_block = [idx]
148
+ else:
149
+ current_block.append(idx)
150
+ else:
151
+ blocks.append(current_block)
152
+ current_block = [idx]
153
+
154
+ blocks.append(current_block)
155
+
156
+ # -------------------------------------------------------------
157
+ # Rule 3 & 4: Apply Triplet Outer-Selection & Pair Grouping
158
+ # -------------------------------------------------------------
159
+ for block in blocks:
160
+ b_len = len(block)
161
+
162
+ if b_len == 1:
163
+ candidates.append(block[0])
164
+
165
+ elif b_len == 2:
166
+ # Pair: accept the later (2nd) candidate
167
+ candidates.append(block[1])
168
+
169
+ elif b_len == 3:
170
+ # Triplet rule: Pick outer bounds (idx 0 and idx 2), discard middle peak
171
+ candidates.append(block[1])
172
+
173
+ else:
174
+ # Block length >= 4: Group by 2 for continuous section, pick 2nd per pair
175
+ for i in range(0, b_len, 2):
176
+ pair = block[i:i+2]
177
+ if len(pair) == 2:
178
+ candidates.append(pair[1])
179
+ else:
180
+ # Trailing single element for odd-length blocks
181
+ candidates.append(pair[0])
182
+
183
+ # Deduplicate and return sorted indices
184
+ final_candidates = sorted(list(set(candidates)))
185
+ return torch.tensor(final_candidates, dtype=torch.long)
186
+
187
+
188
+ def split_at_indices(text, indices):
189
+ """
190
+ Splits a string into substrings at the specified indices.
191
+ """
192
+ # Sort indices just in case they are out of order
193
+ # Add 0 at the start and None at the end to capture the full string
194
+ split_points = [-1] + sorted(indices) + [len(text)]
195
+
196
+ # Slice the string between each pair of points
197
+ # The 'if' condition prevents empty strings if an index is out of bounds
198
+ return [
199
+ [text[split_points[i]+1 : min(len(text), split_points[i+1]+1)], split_points[i+1] - split_points[i]]
200
+ for i in range(len(split_points)-1)
201
+ if text[split_points[i]+1 : min(len(text), split_points[i+1]+1)]
202
+ ]
203
+
204
+
205
+ def give_model_split(model, text, threshold=0.85, delay=2):
206
+ pos, prob = predicted_pos(model, text, threshold, delay)
207
+ return split_at_indices(text, list(pos))
208
+
209
+
210
+ def do_sandhi_join(*arg_words):
211
+ if len(arg_words)==0:
212
+ return ''
213
+ join = arg_words[0]
214
+ for word in arg_words[1:]:
215
+ join_list = sorted(list(_sandhi.join(SanskritImmutableString(join, encoding='slp1'), SanskritImmutableString(word, encoding='slp1'))))
216
+ filtered = [_ords for _ords in join_list if _ords!=(join+word)]
217
+ if len(filtered):
218
+ join = filtered[0]
219
+ else:
220
+ join = join_list[0]
221
+ return join.replace(' ', '')
222
+
223
+
224
+ def verify_sandhi_split(first_word, second_word, compound_word=None):
225
+ if compound_word is None:
226
+ print("compound_word is none")
227
+ return False
228
+ return compound_word in _sandhi.join(SanskritImmutableString(first_word, encoding='slp1'), SanskritImmutableString(second_word, encoding='slp1'))
229
+
230
+ def give_vidyut_sandhi_split(first_word, second_word, first_index, next_char):
231
+ verified_splits = []
232
+ count = {}
233
+ for delta in [0, -1, 1]:
234
+ if delta == 0:
235
+ compound_word = first_word + second_word
236
+ if delta == -1:
237
+ compound_word = (first_word + second_word)[:-1]
238
+ if delta == 1:
239
+ compound_word = (first_word + second_word) + next_char
240
+ if first_index>=len(compound_word):
241
+ continue
242
+ splits = _splitter.split_at(compound_word, first_index)
243
+ valid_splits = [split for split in splits if split.is_valid]
244
+ for split in valid_splits:
245
+ if verify_sandhi_split(split.first, split.second, compound_word):
246
+ verified_splits.append([split, delta])
247
+ for split,_ in verified_splits:
248
+ count[split.first] = 1 + count.get(split.first, 0)
249
+ first_verified_word = sorted(list(count.items()), key=lambda x: x[-1])[-1][0] if len(verified_splits) else ''
250
+ for split, delta in verified_splits:
251
+ if split.first == first_verified_word:
252
+ return split.first, split.second, delta
253
+ return '', '', None
254
+
255
+ def give_vidyut_chedaka_split(first_word, second_word, first_index, next_char):
256
+ verified_splits = []
257
+ for delta in [0, -1, 1]:
258
+ if delta == 0:
259
+ compound_word = first_word + second_word
260
+ if delta == -1:
261
+ compound_word = (first_word + second_word)[:-1]
262
+ if delta == 1:
263
+ compound_word = (first_word + second_word) + next_char
264
+ chedaka_run = chedaka.run(compound_word)
265
+ all_words = [_cheda.text for _cheda in chedaka_run]
266
+ sandhi_joined = do_sandhi_join(*all_words) if len(all_words) else ''
267
+ if len(chedaka_run)>1 and sandhi_joined == compound_word:
268
+ verified_splits.append([chedaka_run, delta])
269
+ min_chedaka_count = min([len(cheda_run) for cheda_run, _ in verified_splits]) if len(verified_splits) else 0
270
+ for chedaka_run, delta in verified_splits:
271
+ if len(chedaka_run)==min_chedaka_count:
272
+ return chedaka_run, delta
273
+ return None, None
274
+
275
+ def do_delta_transform(delta, splited_text, second_word, chedaka_residue=None):
276
+ if delta == 0:
277
+ pass
278
+ elif delta == -1:
279
+ if len(splited_text):
280
+ splited_text[-1][0] = second_word[-1] + splited_text[-1][0]
281
+ splited_text[-1][-1] = splited_text[-1][-1] + 1
282
+ elif delta == 1:
283
+ if len(splited_text):
284
+ splited_text[-1][0] = splited_text[-1][0][1:]
285
+ splited_text[-1][-1] = splited_text[-1][-1] - 1
286
+ if chedaka_residue:
287
+ splited_text[-1][0] = chedaka_residue + splited_text[-1][0]
288
+ splited_text[-1][-1] = splited_text[-1][-1] + len(chedaka_residue)
289
+ return splited_text
290
+
291
+ def score_word_with_kosha(word: str, kosha: Kosha = _kosha) -> float:
292
+ """
293
+ Scores a candidate Sanskrit string (in SLP1) using Vidyut's dictionary.
294
+
295
+ Returns:
296
+ 1.0 -> Fully inflected word / valid Pada (e.g., 'kamalA', 'uktvA', 'aDikAraH')
297
+ 0.5 -> Compound stem / Pratipadika (e.g., 'kamala', 'hita')
298
+ 0.0 -> Non-word / Sandhi hallucination (e.g., 'uktva', 'akamala')
299
+ """
300
+ entries = kosha.get(word)
301
+ if word == 'eva':
302
+ print(word)
303
+ # 1. Zero points for non-words
304
+ if not entries:
305
+ return 0.0
306
+
307
+ # 2. Maximum points for a complete, inflected word (Pada)
308
+ if any(isinstance(entry, PadaEntry) for entry in entries):
309
+ return 1.0
310
+
311
+ # 3. Partial points for uninflected compound stems
312
+ return 0.5
313
+
314
+ def score_sandhi_split_candidates(list_candidates, compound_word, external_comp):
315
+ score = {}
316
+ for idx, (first_word_w, second_word_w, _delta) in enumerate(list_candidates):
317
+ first_word = first_word_w[0]
318
+ expected_length = first_word_w[1]
319
+ if first_word not in compound_word:
320
+ score[idx] = score.get(idx, 0) + 0.2
321
+ score[idx] = score.get(idx, 0) - abs((expected_length-len(first_word))/expected_length)
322
+ score[idx] = score.get(idx, 0) - _delta/2
323
+ if first_word == external_comp:
324
+ score[idx] = score.get(idx, 0) + 0.5
325
+ score[idx] = score.get(idx, 0) + score_word_with_kosha(first_word)
326
+ wining_idx = sorted(list(score.items()), key = lambda x: x[1], reverse=True)[0][0] if score else None
327
+ return list_candidates[wining_idx] if wining_idx else [['', None], ['', None], None]
328
+
329
+ def give_refinement(splited_text):
330
+ refined_result = []
331
+ splited_text.reverse() # for easier poping
332
+ # doing preemptive check to remove model's correct preds
333
+ # preemptive_check = copy.deepcopy(splited_text)[::-1]
334
+ # for _split in preemptive_check:
335
+ # if _kosha.get(_split[0]):
336
+ # refined_result.append(splited_text.pop())
337
+ # else:
338
+ # break
339
+ # if refined_result and splited_text:
340
+ # # adding the len zero chck of while loop below to keep consistence with preemptive check
341
+ # refined_result.append(splited_text.pop())
342
+ while len(splited_text):
343
+ if len(refined_result)==0:
344
+ refined_result.append(splited_text.pop())
345
+ continue
346
+
347
+ first_word, first_index = refined_result.pop() # refining last appended word
348
+ second_word, second_index = splited_text.pop()
349
+ first_word = first_word
350
+ second_word = second_word
351
+ if len(splited_text)==0:
352
+ # last word so we will do check complete word completion
353
+ try:
354
+ compound_word = first_word + second_word
355
+ if _make_normal(compound_word) == _make_normal(vyakarana.derive(_kosha.get(compound_word)[0])[0].text):
356
+ refined_result.append([compound_word, -1])
357
+ continue
358
+ except:
359
+ pass
360
+
361
+ next_char = ''
362
+ if len(splited_text):
363
+ next_char = splited_text[-1][0][0]
364
+ chedaka_run, chedaka_delta = give_vidyut_chedaka_split(first_word, second_word, first_index, next_char)
365
+ sandhi_candidates = []
366
+ for index_delta in [-1, -2, 0, -3, 1, 2]:
367
+ if (first_index+index_delta)<0 or (first_index+index_delta)>len(first_word+second_word):
368
+ continue
369
+ sandhi_first, sandhi_second, sandhi_delta = give_vidyut_sandhi_split(first_word, second_word, first_index+index_delta, next_char)
370
+
371
+ delta = None
372
+ if chedaka_run is not None:
373
+ chedaka_split_index = len(chedaka_run[0].text)
374
+ else:
375
+ chedaka_split_index = 10000
376
+ if sandhi_delta is not None:
377
+ sandhi_split_index = len(sandhi_first)
378
+ else:
379
+ sandhi_split_index = 10000
380
+ if (sandhi_delta is not None):
381
+ sandhi_candidates.append([[sandhi_first, first_index], [sandhi_second, second_index], sandhi_delta])
382
+ chedana_first = chedaka_run[0].text if chedaka_run else ''
383
+ best_sandhi_candidate = score_sandhi_split_candidates(sandhi_candidates, (first_word+second_word), chedana_first)
384
+ sandhi_delta = best_sandhi_candidate[-1]
385
+ chedaka_residue = None
386
+ if (chedaka_run and do_sandhi_join(first_word, second_word)==do_sandhi_join(*[cheda.text for cheda in chedaka_run])) and \
387
+ (((sandhi_delta is not None) and chedaka_run[0].text == sandhi_first) or (abs(sandhi_split_index-first_index)>abs(chedaka_split_index-first_index))):
388
+ # prefer chedaka over sandhi if same first word
389
+ refined_result.append([chedaka_run[0].text, first_index])
390
+ refined_result.append([chedaka_run[1].text, second_index])
391
+ chedaka_residue = do_sandhi_join(*[cheda.text for cheda in chedaka_run[2:]]) if len(chedaka_run)>2 else None
392
+ delta = chedaka_delta
393
+ elif (sandhi_delta is not None):
394
+ refined_result.append([best_sandhi_candidate[0][0], best_sandhi_candidate[0][1]])
395
+ refined_result.append([best_sandhi_candidate[1][0], best_sandhi_candidate[1][1]])
396
+ delta = sandhi_delta
397
+ if delta is not None:
398
+ splited_text = do_delta_transform(delta, splited_text, second_word, chedaka_residue)
399
+ elif delta is None:
400
+ # we have failed to have any proper split for this compound
401
+ # we will check against shabda kosha if any of the word is available to us
402
+ try:
403
+ second_word_valid = _check(second_word)
404
+ except:
405
+ second_word_valid = False
406
+ if _kosha.get(first_word):
407
+ refined_result.append([first_word, first_index])
408
+ refined_result.append([second_word, second_index])
409
+ continue
410
+ # otherwise we might consider, relabling of the remaining string:
411
+ left_overstring = ''.join([w_i[0] for w_i in splited_text[::-1]])
412
+ remaining_string = first_word + second_word + left_overstring
413
+ # we don;t have access to model right now, so we will send the string to caller and loop the iterations
414
+ refined_result.append([remaining_string, -10])
415
+ return refined_result # return early for handling this case
416
+ return refined_result
417
+
418
+ def refinement_looper(model, text, threshold=0.85, threshold_limit=0.4):
419
+ _input_text = text
420
+ result = []
421
+ loop_for_now = True
422
+ splits = give_model_split(model, _input_text, threshold)
423
+ while loop_for_now and threshold>threshold_limit: # looping condition
424
+ splits = give_model_split(model, _input_text, threshold)
425
+ splits = give_refinement(splits)
426
+ if len(splits)==1:
427
+ # resolution fail
428
+ # will retry with lower threshold
429
+ threshold -= 0.1
430
+ continue
431
+
432
+ loop_for_now = False
433
+ for split in splits:
434
+ if split[-1]!=-10:
435
+ result.append(split[0])
436
+ else:
437
+ # there is left over string
438
+ _input_text = splits[-1][0]
439
+ loop_for_now = True
440
+ return result + ([split[0] for split in splits] if loop_for_now else [])
441
+
442
+
443
+ def refinement_seq(model, text, threshold=0.85, threshold_limit=0.4):
444
+ _inpt = ['asti', text]
445
+ result = []
446
+ while threshold>threshold_limit:
447
+ remaining = do_sandhi_join(*_inpt[1:])
448
+ if len(_inpt)<=2:
449
+ threshold-=0.12
450
+ _inpt=refinement_looper(model, do_sandhi_join(*_inpt[:]), threshold, threshold_limit)
451
+ result.append(_inpt.pop(1)) if (len(_inpt)>1 and _inpt[0]=='asti') else ''
452
+ if _inpt[0] != 'asti' and do_sandhi_join(*_inpt)!='asti':
453
+ _inpt = ['', remaining]
454
+ return result
455
+
456
+ def give_chedaka_refinement(splited_text):
457
+ refined_result = []
458
+ splited_text.reverse() # for easier poping
459
+ while len(splited_text):
460
+ if len(refined_result)==0:
461
+ refined_result.append(splited_text.pop())
462
+ continue
463
+ # try:
464
+ # if len(refined_result)>1 and _check(refined_result[-1][0]):
465
+ # refined_result.append(splited_text.pop())
466
+ # except:
467
+ # pass
468
+ first_word, first_index = refined_result.pop() # refining last appended word
469
+ second_word, second_index = splited_text.pop()
470
+ compound_word = first_word+second_word
471
+ if len(splited_text)==0:
472
+ # last word so we will do check complete word completion
473
+ try:
474
+ if _make_normal(compound_word) == _make_normal(vyakarana.derive(_kosha.get(compound_word)[0])[0].text):
475
+ refined_result.append([compound_word, -1])
476
+ continue
477
+ except:
478
+ pass
479
+ for delta in [0, -1, 1]:
480
+ if delta == 0:
481
+ chedaka_run = chedaka.run(compound_word)
482
+ elif delta == -1:
483
+ chedaka_run = chedaka.run(compound_word[:delta])
484
+ elif delta == 1:
485
+ if len(splited_text):
486
+ next_char = splited_text[-1][0][0]
487
+ else:
488
+ next_char = ''
489
+ chedaka_run = chedaka.run(compound_word+next_char)
490
+ if len(chedaka_run)>1:
491
+ chedaka_split_idx = len(chedaka_run[0].text)
492
+ sandhi_splits = _splitter.split_at(compound_word, min(len(compound_word)-1, first_index-1))
493
+ valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid]
494
+ if len(valid_sandhi_splits):
495
+ list_candidates = [[[split.first, first_index], [split.second, second_index], -1] for split in valid_sandhi_splits]
496
+ ((sandhi_first, _), (sandhi_second, _), is_score_not_none) = score_sandhi_split_candidates(list_candidates, compound_word, chedaka_run[0].text)
497
+ sandhi_split = [sandi for sandi in valid_sandhi_splits if (sandi.first==sandhi_first and sandi.second==sandhi_second)][0] if is_score_not_none else None
498
+ sandhi_split_index = len(sandhi_split.first) if sandhi_split else None
499
+ else:
500
+ sandhi_split_index = None
501
+ sandhi_split = None
502
+ if sandhi_split_index is None or abs(sandhi_split_index-first_index)>abs(chedaka_split_idx-first_index):
503
+ for _cheda in chedaka_run:
504
+ refined_result.append([_cheda.text, second_index]) # this losses first index info but okay for simplicity, only last index matters
505
+ else:
506
+ try:
507
+ if _check(sandhi_split.first):
508
+ refined_result.append([sandhi_split.first, first_index])
509
+ refined_result.append([sandhi_split.second, second_index])
510
+ elif _check(chedaka_run[0].text):
511
+ for _cheda in chedaka_run:
512
+ refined_result.append([_cheda.text, second_index]) # this losses first index info but okay for simplicity, only last index matters
513
+ except:
514
+ try:
515
+ if _check(chedaka_run[0].text):
516
+ for _cheda in chedaka_run:
517
+ refined_result.append([_cheda.text, second_index]) # this losses first index info but okay for simplicity, only last index matters
518
+ except:
519
+ refined_result.append([sandhi_split.first, first_index])
520
+ refined_result.append([sandhi_split.second, second_index])
521
+ if delta == 0:
522
+ pass
523
+ elif delta == -1:
524
+ if len(splited_text):
525
+ splited_text[-1][0] = compound_word[-1] + splited_text[-1][0]
526
+ elif delta == 1:
527
+ if len(splited_text):
528
+ splited_text[-1][0] = splited_text[-1][0][1:]
529
+ break
530
+ if len(chedaka_run)<=1:
531
+ for delta in [0, -1, 1]:
532
+ if delta == 0:
533
+ sandhi_splits = _splitter.split_at(compound_word, first_index-1)
534
+ valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid]
535
+ sandhi_split = valid_sandhi_splits[0] if len(valid_sandhi_splits) else None
536
+ sandhi_split_index = len(sandhi_split.first) if sandhi_split else None
537
+ elif delta == -1:
538
+ sandhi_splits = _splitter.split_at(compound_word[:delta], first_index-1)
539
+ valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid]
540
+ sandhi_split = valid_sandhi_splits[0] if len(valid_sandhi_splits) else None
541
+ sandhi_split_index = len(sandhi_split.first) if sandhi_split else None
542
+ elif delta == 1:
543
+ if len(splited_text):
544
+ next_char = splited_text[-1][0][0]
545
+ else:
546
+ next_char = ''
547
+ sandhi_splits = _splitter.split_at(compound_word+next_char, first_index-1)
548
+ valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid]
549
+ sandhi_split = valid_sandhi_splits[0] if len(valid_sandhi_splits) else None
550
+ sandhi_split_index = len(sandhi_split.first) if sandhi_split else None
551
+ if sandhi_split_index is not None:
552
+ if delta == 0:
553
+ pass
554
+ elif delta == -1:
555
+ if len(splited_text):
556
+ splited_text[-1][0] = second_word[-1] + splited_text[-1][0]
557
+ elif delta == 1:
558
+ if len(splited_text):
559
+ splited_text[-1][0] = splited_text[-1][0][1:]
560
+ break
561
+ if sandhi_split_index is not None:
562
+ refined_result.append([sandhi_split.first, first_index])
563
+ refined_result.append([sandhi_split.second, second_index])
564
+ else:
565
+ refined_result.append([compound_word, second_index])
566
+
567
+ return refined_result
568
+
569
+ def give_split(text, id, skip=0):
570
+ _segmentation = _splitter.split_at(text[skip:], id - skip)[0]
571
+ if _segmentation.is_valid:
572
+ return _segmentation.first
573
+
574
+ def get_best_vidyut_split(text, split_idx, neural_prob):
575
+ candidates = _splitter.split_at(text, split_idx)
576
+
577
+ best_candidate = None
578
+ best_score = -1.0
579
+
580
+ for cand in candidates:
581
+ # 1. Grammar is King: Does Vidyut recognize the resulting words in its lexicon?
582
+ is_lexically_valid = cand.is_valid
583
+
584
+ # Heavy penalty for proposing non-words (e.g., 'uktva' gets crushed here)
585
+ base_score = 1.0 if is_lexically_valid else 0.1
586
+
587
+ # 2. Smart Sandhi Evaluation
588
+ # Check if the split required changing letters (Sandhi inversion)
589
+ is_sandhi_inversion = (cand.first != text[:len(cand.first)])
590
+
591
+ if is_sandhi_inversion:
592
+ if is_lexically_valid:
593
+ # REWARD: It's a real dictionary word that required un-joining (e.g., hito -> hita)
594
+ base_score += 0.2
595
+ else:
596
+ # PENALIZE: It's hallucinating fake sandhi rules to force a split (e.g., uktvA -> uktva)
597
+ base_score -= 0.05
598
+ else:
599
+ if is_lexically_valid:
600
+ # SLIGHT REWARD: Valid literal cuts (like uktvA + kamalA) are highly reliable
601
+ base_score += 0.1
602
+
603
+ if is_lexically_valid:
604
+ base_score += score_word_with_kosha(cand.second)
605
+
606
+ # 3. Combine with Neural Confidence
607
+ total_score = base_score * neural_prob
608
+
609
+ if total_score > best_score:
610
+ best_score = total_score
611
+ best_candidate = cand
612
+
613
+ return best_candidate
614
+
615
+
616
+ def get_score_cand_nxt(text, cand, next_word):
617
+ base_score = 0
618
+ # 1. Grammar is King: Does Vidyut recognize the resulting words in its lexicon?
619
+ is_lexically_valid = cand.is_valid
620
+
621
+ # Heavy penalty for proposing non-words (e.g., 'uktva' gets crushed here)
622
+ base_score = 1.0 if is_lexically_valid else 0.1
623
+
624
+ # 2. Smart Sandhi Evaluation
625
+ # Check if the split required changing letters (Sandhi inversion)
626
+ is_sandhi_inversion = (cand.first != text[:len(cand.first)])
627
+
628
+ if is_sandhi_inversion:
629
+ if is_lexically_valid:
630
+ # REWARD: It's a real dictionary word that required un-joining (e.g., hito -> hita)
631
+ base_score += 0.3
632
+ else:
633
+ # PENALIZE: It's hallucinating fake sandhi rules to force a split (e.g., uktvA -> uktva)
634
+ base_score -= 0.05
635
+ else:
636
+ if is_lexically_valid:
637
+ # SLIGHT REWARD: Valid literal cuts (like uktvA + kamalA) are highly reliable
638
+ base_score += 0.1
639
+
640
+ if is_lexically_valid:
641
+ base_score += score_word_with_kosha(cand.second)
642
+ base_score += score_word_with_kosha(next_word)
643
+
644
+ return base_score
645
+
646
+
647
+ def get_best_with_next_word(model, text, original_split_idx, neural_prob):
648
+ candidate = get_best_vidyut_split(text, original_split_idx, neural_prob)
649
+ next_best_guess_word = sequential_backward_split(model, candidate.second)[0] if candidate.is_valid and candidate.second else ''
650
+ return candidate, next_best_guess_word
651
+
652
+ def get_searched_vidyut_split(text, original_split_idx, neural_prob, minus_1_prob, model=None):
653
+ if model is None:
654
+ plus_1_cand = get_best_vidyut_split(text, original_split_idx+1, neural_prob)
655
+ orginal_cand = get_best_vidyut_split(text, original_split_idx, neural_prob)
656
+ minus_1_cand = get_best_vidyut_split(text, original_split_idx-1, neural_prob) if original_split_idx-1>0 else orginal_cand
657
+ if minus_1_cand.is_valid and minus_1_prob>0.3:
658
+ return minus_1_cand
659
+ if neural_prob<0.95 and plus_1_cand.is_valid:
660
+ return plus_1_cand
661
+ return orginal_cand
662
+ else:
663
+ score_orginal_cand = 0
664
+ score_plus_cand = 0
665
+ score_minus_cand = 0
666
+ orginal_cand, next_org_word = get_best_with_next_word(model, text, original_split_idx, neural_prob)
667
+ plus_1_cand, next_plus_word = get_best_with_next_word(model, text, original_split_idx+1, neural_prob) if original_split_idx+1<len(text) else (orginal_cand, next_org_word)
668
+ minus_1_cand, next_minus_word = get_best_with_next_word(model, text, original_split_idx-1, neural_prob) if original_split_idx-1>0 else (orginal_cand, next_org_word)
669
+ plus_score = get_score_cand_nxt(text, plus_1_cand, next_plus_word)
670
+ org_score = get_score_cand_nxt(text, orginal_cand, next_org_word)
671
+ minus_score = get_score_cand_nxt(text, minus_1_cand, next_minus_word)
672
+ score_word = [[plus_score, plus_1_cand], [org_score, orginal_cand], [minus_score, minus_1_cand]]
673
+ return sorted(score_word, reverse=True)[0][-1]
674
+
675
+ def sequential_split(model, text, threshold=0.85, delay=2):
676
+ result_texts = []
677
+ while text!="":
678
+ split_candidate = give_refinement(give_model_split(model, text))[0][0]
679
+ print(split_candidate)
680
+ result_texts.append(split_candidate)
681
+ valid_ = [v for v in _splitter.split_at(text, max(0, len(split_candidate)-1)) if v.is_valid]
682
+ text = valid_[0].second if valid_ else _splitter.split_at(text, max(0, len(split_candidate)-1))[0].second
683
+ return result_texts
684
+
685
+ def sequential_backward_split(model, text, threshold=0.85, delay=2):
686
+ result_texts = []
687
+ positions_split, prob_split = predicted_pos(model, text, threshold=threshold, delay=delay) # init values
688
+ while text!="" and len(positions_split)>0:
689
+ positions_split, prob_split = predicted_pos(model, text, threshold=threshold, delay=delay)
690
+ positions_split = list(positions_split)
691
+ while len(positions_split):
692
+ pos_split = positions_split.pop()
693
+ split_candidate = get_searched_vidyut_split(text, pos_split, prob_split[pos_split], prob_split[max(0, pos_split-1)], model=model)
694
+ if split_candidate.is_valid and split_candidate.second:
695
+ result_texts.append(split_candidate.second)
696
+ # print("splited : ", split_candidate.first)
697
+ # print(len(positions_split))
698
+ text = split_candidate.first
699
+ break # for chunking remainging compound
700
+ else:
701
+ pass # skip unvieriied splits for now simple
702
+ # print(text, positions_split)
703
+ if text!='':
704
+ result_texts.append(text)
705
+ result_texts.reverse()
706
+ return result_texts
707
+
708
+ # ---------------------------------------------------------------------------
709
+ # Load model
710
+ # ---------------------------------------------------------------------------
711
+
712
+ def load_model(checkpoint_dir: str, device: torch.device) -> Tuple[BinaryBoundaryModel, int]:
713
+ """Load model and extract delay from config or checkpoint."""
714
+ config_path = os.path.join(checkpoint_dir, "config.json")
715
+ if os.path.exists(config_path):
716
+ config = HybridTimeScaleConfig.from_pretrained(checkpoint_dir)
717
+ else:
718
+ # Infer config from checkpoint weights
719
+ print(f"[warn] No config.json, inferring from checkpoint", file=sys.stderr)
720
+ from safetensors.torch import load_file
721
+ sd_path = os.path.join(checkpoint_dir, "model.safetensors")
722
+ if not os.path.exists(sd_path):
723
+ sd_path = os.path.join(checkpoint_dir, "pytorch_model.bin")
724
+ sd = torch.load(sd_path, map_location="cpu", weights_only=False)
725
+ else:
726
+ sd = load_file(sd_path)
727
+
728
+ # Clean keys
729
+ sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()}
730
+
731
+ latent_dim = sd["embedding.weight"].shape[1]
732
+ q_out = sd["blocks.0.mixer.q_proj.weight"].shape[0]
733
+ # num_heads defaults to max(1, latent_dim // 64) in HybridSpectralBlock
734
+ num_heads = max(1, latent_dim // 64)
735
+ num_modes = q_out // num_heads
736
+ num_layers = sum(1 for k in sd if k.startswith("blocks.") and k.endswith(".ffn.1.weight"))
737
+
738
+ print(f" Inferred: latent_dim={latent_dim}, num_modes={num_modes}, "
739
+ f"num_heads={num_heads}, num_layers={num_layers}", file=sys.stderr)
740
+
741
+ config = HybridTimeScaleConfig(
742
+ vocab_size=VOCAB_SIZE, latent_dim=latent_dim, num_layers=num_layers,
743
+ num_modes=num_modes,
744
+ layer_types=["linear", "softmax"][:num_layers] or ["linear", "softmax"],
745
+ time_scale=float(2 * num_modes),
746
+ dropout=0.1, pad_token_id=PAD_ID,
747
+ bos_token_id=0, eos_token_id=0, tie_word_embeddings=False,
748
+ )
749
+
750
+ delay = getattr(config, "delay", 0)
751
+ print(f"Model delay: {delay}", file=sys.stderr)
752
+
753
+ model = BinaryBoundaryModel(config)
754
+ sd_path = os.path.join(checkpoint_dir, "model.safetensors")
755
+ if os.path.exists(sd_path):
756
+ from safetensors.torch import load_file
757
+ state_dict = load_file(sd_path)
758
+ else:
759
+ sd_path = os.path.join(checkpoint_dir, "pytorch_model.bin")
760
+ state_dict = torch.load(sd_path, map_location="cpu", weights_only=False)
761
+ state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
762
+ model.load_state_dict(state_dict, strict=False)
763
+ model = model.to(device)
764
+ model.eval()
765
+ return model, delay
766
+
767
+
768
+ import copy
769
+ def better_decode(model, text):
770
+ _input = text
771
+ result = []
772
+ splits = give_refinement(give_model_split(model, copy.deepcopy(_input), 0.3))
773
+ while _input or len(splits)>1:
774
+ _input = text[len(splits[0][0]):]
775
+ result.append(splits[0][0])
776
+ splits = give_refinement(give_model_split(model, copy.deepcopy(_input), 0.3))
777
+ return result + [li[0] for li in splits]
778
+
779
+
780
+ def give_correct_slp1_input(text):
781
+ return do_sandhi_join(*lipi.transliterate(text, lipi.Scheme.Devanagari, lipi.Scheme.Slp1).split())
782
+
783
+ def main():
784
+ parser = argparse.ArgumentParser(description="Run Sandhi vigraha test suite.")
785
+ parser.add_argument("text", nargs="?", default=None)
786
+ parser.add_argument("--batch", default=None)
787
+ parser.add_argument("--test-file", default="test_cases.json")
788
+ parser.add_argument("--checkpoint", default="checkpoints/delayed_model_save_fixed_delay2_v2")
789
+ parser.add_argument("--delay", type=int, default=2)
790
+ parser.add_argument("--threshold", type=float, default=0.85)
791
+ parser.add_argument("--bias-first-word", action="store_true")
792
+ parser.add_argument("--verbose", "-v", action="store_true")
793
+ args = parser.parse_args()
794
+
795
+ if torch.cuda.is_available():
796
+ device = torch.device("cuda")
797
+ elif torch.backends.mps.is_available():
798
+ device = torch.device("mps")
799
+ else:
800
+ device = torch.device("cpu")
801
+ print(f"Device: {device}", file=sys.stderr)
802
+
803
+ # Load model
804
+ print(f"Loading model from {args.checkpoint}...", file=sys.stderr)
805
+ model, delay = load_model(args.checkpoint, device)
806
+ if args.delay is not None:
807
+ delay = args.delay
808
+ print(f"Model loaded (delay={delay})", file=sys.stderr)
809
+ threshold = args.threshold
810
+ # Load test cases
811
+ with open(args.test_file) as f:
812
+ test_cases = json.load(f)
813
+ print(f"\nLoaded {len(test_cases)} test cases\n", file=sys.stderr)
814
+ text = 'vidyAdadAtivinayaMvinayAdyAtipAtratAm'
815
+ res = refinement_seq(model, text)
816
+ print(res)
817
+ give_chedaka_refinement(give_model_split(model, 'karmARyevADikArastemAphalezukadAcana', 0.7))
818
+ give_refinement(give_model_split(model, 'karmARyevADikArastemAphalezukadAcana', 0.4))
819
+ if test_cases:
820
+ for test_case in test_cases:
821
+ text = test_case.get('input', '')
822
+ expected_output = test_case.get('expected', '').split()
823
+ pred_output = sequential_split(model, text, threshold=threshold)
824
+ print("Input Text:\t", text)
825
+ print('Expected Output:\t', expected_output)
826
+ print('Predicted Output:\t', pred_output)
827
+ print()
828
+
829
+ texts: List[str] = []
830
+ if args.batch:
831
+ with open(args.batch) as f:
832
+ texts = [line.strip() for line in f if line.strip()]
833
+ elif args.text:
834
+ texts = [args.text]
835
+ else:
836
+ print("\nEnter Sanskrit text (SLP1), Ctrl+D to exit:", file=sys.stderr)
837
+ while True:
838
+ try:
839
+ t = input(">>> ").strip()
840
+ if t:
841
+ print(sequential_split(model, t, threshold=threshold))
842
+ texts.append(t)
843
+ except EOFError:
844
+ break
845
+ for text in texts:
846
+ print(sequential_split(model, text, threshold=threshold))
847
+
848
+
849
+ if __name__ =='__main__':
850
+ main()