Download better_decoder.py from CodeIsAbstract/sanskrit-sandhi-boundaries-v2: direct link, hf CLI and curl.
- Browser
- Download file 38.3 kB
-
https://huggingface.co/datasets/CodeIsAbstract/sanskrit-sandhi-boundaries-v2/resolve/main/better_decoder.py
- Command line
-
hf download hf://datasets/CodeIsAbstract/sanskrit-sandhi-boundaries-v2/better_decoder.py
-
curl -L -o better_decoder.py https://huggingface.co/datasets/CodeIsAbstract/sanskrit-sandhi-boundaries-v2/resolve/main/better_decoder.py
38.3 kB
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import os | |
| import sys | |
| import json | |
| from typing import List, Tuple, Optional, Dict | |
| import torch | |
| import torch.nn.functional as F | |
| from model import HybridTimeScaleConfig | |
| from train_split_model import ( | |
| BinaryBoundaryModel, | |
| SLP1_CHARS, | |
| char_to_idx, | |
| PAD_ID, | |
| VOCAB_SIZE, | |
| ) | |
| from vidyut.sandhi import Splitter | |
| from vidyut.kosha import Kosha, PadaEntry | |
| from vidyut import kosha as kosha_mod, cheda as cheda_mod | |
| from SanskritTokenizer.cache import get_default_data_path | |
| from vidyut.prakriya import Vyakarana | |
| from vidyut import lipi | |
| from sanskrit_parser.base.sanskrit_base import SanskritImmutableString | |
| from sanskrit_parser.parser.sandhi import Sandhi | |
| import logging | |
| logger = logging.getLogger("sanskrit_parser") | |
| logger.setLevel(logging.WARNING) | |
| data_path = get_default_data_path() | |
| rules_csv = os.path.join(data_path, "sandhi", "rules.csv") | |
| _splitter = Splitter.from_csv(rules_csv) | |
| _sandhi = Sandhi() | |
| _kosha = Kosha(data_path+'/kosha') | |
| chedaka = cheda_mod.Chedaka(data_path) | |
| vyakarana = Vyakarana() | |
| import re | |
| _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] | |
| _make_normal = lambda word: re.sub('s$', '', word) | |
| _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)] | |
| _check = lambda word: _make_normal(word) == _filter(_make_normal(word))[0] | |
| def predict(model, text: str, delay: int=2) -> torch.Tensor: | |
| model.eval() | |
| device = next(model.parameters()).device | |
| # Build input: real chars + N pad chars at end | |
| N = delay | |
| L = len(text) | |
| total_len = L + N | |
| input_ids = torch.tensor( | |
| [[char_to_idx.get(c, PAD_ID) for c in text] + [PAD_ID] * N], | |
| dtype=torch.long, device=device, | |
| ) | |
| attention_mask = torch.ones(total_len, dtype=torch.long, device=device).unsqueeze(0) | |
| # Mark appended pads as valid for model processing (so it can predict | |
| # boundaries in the last N chars of real text) | |
| attention_mask[0, L:] = 1 # keep pads in attention | |
| with torch.no_grad(): | |
| output = model(input_ids=input_ids, attention_mask=attention_mask) | |
| raw_probs = torch.sigmoid(output["logits"][0]).cpu() # (total_len,) | |
| # Shift: output at position bnd+N predicts for position bnd | |
| # So probs[bnd] = raw_probs[bnd + N] | |
| probs = torch.zeros(L) | |
| for bnd in range(L): | |
| if bnd + N < total_len: | |
| probs[bnd] = raw_probs[bnd + N] | |
| return probs | |
| def predicted_pos(model, text, threshold=0.85, delay=2, send_refined=True): | |
| prob = predict(model, text, delay=delay) | |
| base_pos = torch.flatten(torch.nonzero(prob > threshold)) | |
| refined_prob = prob_refiner(prob, threshold) | |
| return refined_prob if send_refined else base_pos, prob | |
| import torch | |
| from typing import List, Union | |
| def prob_refiner(prob: Union[torch.Tensor, List[float]], threshold: float = 0.85) -> torch.Tensor: | |
| """ | |
| Refines probability tensors into split indices using custom domain heuristics: | |
| 1. Isolated low-probability spikes (e.g. [0, 0, 0.5, 0]) are accepted. | |
| 2. Drops below 50% of the previous value break continuous runs. | |
| 3. Triplets (e.g. [0.9, 0.95, 0.9] or [0.9, 0.7, 0.9]) discard the center and pick outer elements. | |
| 4. Continuous runs >= threshold are grouped in pairs of 2, picking the 2nd index per group. | |
| Args: | |
| prob: 1D probability sequence (PyTorch Tensor or List). | |
| threshold: High-confidence threshold (default: 0.85). | |
| Returns: | |
| 1D torch.LongTensor of accepted split candidate indices. | |
| """ | |
| if isinstance(prob, list): | |
| prob = torch.tensor(prob, dtype=torch.float32) | |
| elif not isinstance(prob, torch.Tensor): | |
| prob = torch.as_tensor(prob, dtype=torch.float32) | |
| n = len(prob) | |
| if n == 0: | |
| return torch.tensor([], dtype=torch.long) | |
| candidates = [] | |
| # ------------------------------------------------------------- | |
| # Rule 1: Accept isolated spikes significantly larger than 0 surroundings | |
| # ------------------------------------------------------------- | |
| for i in range(n): | |
| val = prob[i].item() | |
| if 0.3 < val < threshold: | |
| left = prob[i - 1].item() if i > 0 else 0.0 | |
| right = prob[i + 1].item() if i < n - 1 else 0.0 | |
| # If both surrounding values are <= half of current value (or zero) | |
| if left <= (val / 2.0) and right <= (val / 2.0): | |
| candidates.append(i) | |
| # ------------------------------------------------------------- | |
| # Rule 2: Collect high-confidence indices and break on >50% relative drops | |
| # ------------------------------------------------------------- | |
| above_thresh = (prob >= threshold).nonzero(as_tuple=True)[0].tolist() | |
| if not above_thresh: | |
| return torch.tensor(sorted(list(set(candidates))), dtype=torch.long) | |
| # Group consecutive indices into continuous blocks | |
| blocks = [] | |
| current_block = [above_thresh[0]] | |
| for idx in above_thresh[1:]: | |
| prev_idx = current_block[-1] | |
| # Check if adjacent AND probability hasn't dropped below half of previous | |
| if idx == prev_idx + 1: | |
| if prob[idx].item() < (prob[prev_idx].item() * 0.5): | |
| # Prob dropped below 50% of previous -> end current block & start new block | |
| blocks.append(current_block) | |
| current_block = [idx] | |
| else: | |
| current_block.append(idx) | |
| else: | |
| blocks.append(current_block) | |
| current_block = [idx] | |
| blocks.append(current_block) | |
| # ------------------------------------------------------------- | |
| # Rule 3 & 4: Apply Triplet Outer-Selection & Pair Grouping | |
| # ------------------------------------------------------------- | |
| for block in blocks: | |
| b_len = len(block) | |
| if b_len == 1: | |
| candidates.append(block[0]) | |
| elif b_len == 2: | |
| # Pair: accept the later (2nd) candidate | |
| candidates.append(block[1]) | |
| elif b_len == 3: | |
| # Triplet rule: Pick outer bounds (idx 0 and idx 2), discard middle peak | |
| candidates.append(block[1]) | |
| else: | |
| # Block length >= 4: Group by 2 for continuous section, pick 2nd per pair | |
| for i in range(0, b_len, 2): | |
| pair = block[i:i+2] | |
| if len(pair) == 2: | |
| candidates.append(pair[1]) | |
| else: | |
| # Trailing single element for odd-length blocks | |
| candidates.append(pair[0]) | |
| # Deduplicate and return sorted indices | |
| final_candidates = sorted(list(set(candidates))) | |
| return torch.tensor(final_candidates, dtype=torch.long) | |
| def split_at_indices(text, indices): | |
| """ | |
| Splits a string into substrings at the specified indices. | |
| """ | |
| # Sort indices just in case they are out of order | |
| # Add 0 at the start and None at the end to capture the full string | |
| split_points = [-1] + sorted(indices) + [len(text)] | |
| # Slice the string between each pair of points | |
| # The 'if' condition prevents empty strings if an index is out of bounds | |
| return [ | |
| [text[split_points[i]+1 : min(len(text), split_points[i+1]+1)], split_points[i+1] - split_points[i]] | |
| for i in range(len(split_points)-1) | |
| if text[split_points[i]+1 : min(len(text), split_points[i+1]+1)] | |
| ] | |
| def give_model_split(model, text, threshold=0.85, delay=2): | |
| pos, prob = predicted_pos(model, text, threshold, delay) | |
| return split_at_indices(text, list(pos)) | |
| def do_sandhi_join(*arg_words): | |
| if len(arg_words)==0: | |
| return '' | |
| join = arg_words[0] | |
| for word in arg_words[1:]: | |
| join_list = sorted(list(_sandhi.join(SanskritImmutableString(join, encoding='slp1'), SanskritImmutableString(word, encoding='slp1')))) | |
| filtered = [_ords for _ords in join_list if _ords!=(join+word)] | |
| if len(filtered): | |
| join = filtered[0] | |
| else: | |
| join = join_list[0] | |
| return join.replace(' ', '') | |
| def verify_sandhi_split(first_word, second_word, compound_word=None): | |
| if compound_word is None: | |
| print("compound_word is none") | |
| return False | |
| return compound_word in _sandhi.join(SanskritImmutableString(first_word, encoding='slp1'), SanskritImmutableString(second_word, encoding='slp1')) | |
| def give_vidyut_sandhi_split(first_word, second_word, first_index, next_char): | |
| verified_splits = [] | |
| count = {} | |
| for delta in [0, -1, 1]: | |
| if delta == 0: | |
| compound_word = first_word + second_word | |
| if delta == -1: | |
| compound_word = (first_word + second_word)[:-1] | |
| if delta == 1: | |
| compound_word = (first_word + second_word) + next_char | |
| if first_index>=len(compound_word): | |
| continue | |
| splits = _splitter.split_at(compound_word, first_index) | |
| valid_splits = [split for split in splits if split.is_valid] | |
| for split in valid_splits: | |
| if verify_sandhi_split(split.first, split.second, compound_word): | |
| verified_splits.append([split, delta]) | |
| for split,_ in verified_splits: | |
| count[split.first] = 1 + count.get(split.first, 0) | |
| first_verified_word = sorted(list(count.items()), key=lambda x: x[-1])[-1][0] if len(verified_splits) else '' | |
| for split, delta in verified_splits: | |
| if split.first == first_verified_word: | |
| return split.first, split.second, delta | |
| return '', '', None | |
| def give_vidyut_chedaka_split(first_word, second_word, first_index, next_char): | |
| verified_splits = [] | |
| for delta in [0, -1, 1]: | |
| if delta == 0: | |
| compound_word = first_word + second_word | |
| if delta == -1: | |
| compound_word = (first_word + second_word)[:-1] | |
| if delta == 1: | |
| compound_word = (first_word + second_word) + next_char | |
| chedaka_run = chedaka.run(compound_word) | |
| all_words = [_cheda.text for _cheda in chedaka_run] | |
| sandhi_joined = do_sandhi_join(*all_words) if len(all_words) else '' | |
| if len(chedaka_run)>1 and sandhi_joined == compound_word: | |
| verified_splits.append([chedaka_run, delta]) | |
| min_chedaka_count = min([len(cheda_run) for cheda_run, _ in verified_splits]) if len(verified_splits) else 0 | |
| for chedaka_run, delta in verified_splits: | |
| if len(chedaka_run)==min_chedaka_count: | |
| return chedaka_run, delta | |
| return None, None | |
| def do_delta_transform(delta, splited_text, second_word, chedaka_residue=None): | |
| if delta == 0: | |
| pass | |
| elif delta == -1: | |
| if len(splited_text): | |
| splited_text[-1][0] = second_word[-1] + splited_text[-1][0] | |
| splited_text[-1][-1] = splited_text[-1][-1] + 1 | |
| elif delta == 1: | |
| if len(splited_text): | |
| splited_text[-1][0] = splited_text[-1][0][1:] | |
| splited_text[-1][-1] = splited_text[-1][-1] - 1 | |
| if chedaka_residue: | |
| splited_text[-1][0] = chedaka_residue + splited_text[-1][0] | |
| splited_text[-1][-1] = splited_text[-1][-1] + len(chedaka_residue) | |
| return splited_text | |
| def score_word_with_kosha(word: str, kosha: Kosha = _kosha) -> float: | |
| """ | |
| Scores a candidate Sanskrit string (in SLP1) using Vidyut's dictionary. | |
| Returns: | |
| 1.0 -> Fully inflected word / valid Pada (e.g., 'kamalA', 'uktvA', 'aDikAraH') | |
| 0.5 -> Compound stem / Pratipadika (e.g., 'kamala', 'hita') | |
| 0.0 -> Non-word / Sandhi hallucination (e.g., 'uktva', 'akamala') | |
| """ | |
| entries = kosha.get(word) | |
| if word == 'eva': | |
| print(word) | |
| # 1. Zero points for non-words | |
| if not entries: | |
| return 0.0 | |
| # 2. Maximum points for a complete, inflected word (Pada) | |
| if any(isinstance(entry, PadaEntry) for entry in entries): | |
| return 1.0 | |
| # 3. Partial points for uninflected compound stems | |
| return 0.5 | |
| def score_sandhi_split_candidates(list_candidates, compound_word, external_comp): | |
| score = {} | |
| for idx, (first_word_w, second_word_w, _delta) in enumerate(list_candidates): | |
| first_word = first_word_w[0] | |
| expected_length = first_word_w[1] | |
| if first_word not in compound_word: | |
| score[idx] = score.get(idx, 0) + 0.2 | |
| score[idx] = score.get(idx, 0) - abs((expected_length-len(first_word))/expected_length) | |
| score[idx] = score.get(idx, 0) - _delta/2 | |
| if first_word == external_comp: | |
| score[idx] = score.get(idx, 0) + 0.5 | |
| score[idx] = score.get(idx, 0) + score_word_with_kosha(first_word) | |
| wining_idx = sorted(list(score.items()), key = lambda x: x[1], reverse=True)[0][0] if score else None | |
| return list_candidates[wining_idx] if wining_idx else [['', None], ['', None], None] | |
| def give_refinement(splited_text): | |
| refined_result = [] | |
| splited_text.reverse() # for easier poping | |
| # doing preemptive check to remove model's correct preds | |
| # preemptive_check = copy.deepcopy(splited_text)[::-1] | |
| # for _split in preemptive_check: | |
| # if _kosha.get(_split[0]): | |
| # refined_result.append(splited_text.pop()) | |
| # else: | |
| # break | |
| # if refined_result and splited_text: | |
| # # adding the len zero chck of while loop below to keep consistence with preemptive check | |
| # refined_result.append(splited_text.pop()) | |
| while len(splited_text): | |
| if len(refined_result)==0: | |
| refined_result.append(splited_text.pop()) | |
| continue | |
| first_word, first_index = refined_result.pop() # refining last appended word | |
| second_word, second_index = splited_text.pop() | |
| first_word = first_word | |
| second_word = second_word | |
| if len(splited_text)==0: | |
| # last word so we will do check complete word completion | |
| try: | |
| compound_word = first_word + second_word | |
| if _make_normal(compound_word) == _make_normal(vyakarana.derive(_kosha.get(compound_word)[0])[0].text): | |
| refined_result.append([compound_word, -1]) | |
| continue | |
| except: | |
| pass | |
| next_char = '' | |
| if len(splited_text): | |
| next_char = splited_text[-1][0][0] | |
| chedaka_run, chedaka_delta = give_vidyut_chedaka_split(first_word, second_word, first_index, next_char) | |
| sandhi_candidates = [] | |
| for index_delta in [-1, -2, 0, -3, 1, 2]: | |
| if (first_index+index_delta)<0 or (first_index+index_delta)>len(first_word+second_word): | |
| continue | |
| sandhi_first, sandhi_second, sandhi_delta = give_vidyut_sandhi_split(first_word, second_word, first_index+index_delta, next_char) | |
| delta = None | |
| if chedaka_run is not None: | |
| chedaka_split_index = len(chedaka_run[0].text) | |
| else: | |
| chedaka_split_index = 10000 | |
| if sandhi_delta is not None: | |
| sandhi_split_index = len(sandhi_first) | |
| else: | |
| sandhi_split_index = 10000 | |
| if (sandhi_delta is not None): | |
| sandhi_candidates.append([[sandhi_first, first_index], [sandhi_second, second_index], sandhi_delta]) | |
| chedana_first = chedaka_run[0].text if chedaka_run else '' | |
| best_sandhi_candidate = score_sandhi_split_candidates(sandhi_candidates, (first_word+second_word), chedana_first) | |
| sandhi_delta = best_sandhi_candidate[-1] | |
| chedaka_residue = None | |
| if (chedaka_run and do_sandhi_join(first_word, second_word)==do_sandhi_join(*[cheda.text for cheda in chedaka_run])) and \ | |
| (((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))): | |
| # prefer chedaka over sandhi if same first word | |
| refined_result.append([chedaka_run[0].text, first_index]) | |
| refined_result.append([chedaka_run[1].text, second_index]) | |
| chedaka_residue = do_sandhi_join(*[cheda.text for cheda in chedaka_run[2:]]) if len(chedaka_run)>2 else None | |
| delta = chedaka_delta | |
| elif (sandhi_delta is not None): | |
| refined_result.append([best_sandhi_candidate[0][0], best_sandhi_candidate[0][1]]) | |
| refined_result.append([best_sandhi_candidate[1][0], best_sandhi_candidate[1][1]]) | |
| delta = sandhi_delta | |
| if delta is not None: | |
| splited_text = do_delta_transform(delta, splited_text, second_word, chedaka_residue) | |
| elif delta is None: | |
| # we have failed to have any proper split for this compound | |
| # we will check against shabda kosha if any of the word is available to us | |
| try: | |
| second_word_valid = _check(second_word) | |
| except: | |
| second_word_valid = False | |
| if _kosha.get(first_word): | |
| refined_result.append([first_word, first_index]) | |
| refined_result.append([second_word, second_index]) | |
| continue | |
| # otherwise we might consider, relabling of the remaining string: | |
| left_overstring = ''.join([w_i[0] for w_i in splited_text[::-1]]) | |
| remaining_string = first_word + second_word + left_overstring | |
| # we don;t have access to model right now, so we will send the string to caller and loop the iterations | |
| refined_result.append([remaining_string, -10]) | |
| return refined_result # return early for handling this case | |
| return refined_result | |
| def refinement_looper(model, text, threshold=0.85, threshold_limit=0.4): | |
| _input_text = text | |
| result = [] | |
| loop_for_now = True | |
| splits = give_model_split(model, _input_text, threshold) | |
| while loop_for_now and threshold>threshold_limit: # looping condition | |
| splits = give_model_split(model, _input_text, threshold) | |
| splits = give_refinement(splits) | |
| if len(splits)==1: | |
| # resolution fail | |
| # will retry with lower threshold | |
| threshold -= 0.1 | |
| continue | |
| loop_for_now = False | |
| for split in splits: | |
| if split[-1]!=-10: | |
| result.append(split[0]) | |
| else: | |
| # there is left over string | |
| _input_text = splits[-1][0] | |
| loop_for_now = True | |
| return result + ([split[0] for split in splits] if loop_for_now else []) | |
| def refinement_seq(model, text, threshold=0.85, threshold_limit=0.4): | |
| _inpt = ['asti', text] | |
| result = [] | |
| while threshold>threshold_limit: | |
| remaining = do_sandhi_join(*_inpt[1:]) | |
| if len(_inpt)<=2: | |
| threshold-=0.12 | |
| _inpt=refinement_looper(model, do_sandhi_join(*_inpt[:]), threshold, threshold_limit) | |
| result.append(_inpt.pop(1)) if (len(_inpt)>1 and _inpt[0]=='asti') else '' | |
| if _inpt[0] != 'asti' and do_sandhi_join(*_inpt)!='asti': | |
| _inpt = ['', remaining] | |
| return result | |
| def give_chedaka_refinement(splited_text): | |
| refined_result = [] | |
| splited_text.reverse() # for easier poping | |
| while len(splited_text): | |
| if len(refined_result)==0: | |
| refined_result.append(splited_text.pop()) | |
| continue | |
| # try: | |
| # if len(refined_result)>1 and _check(refined_result[-1][0]): | |
| # refined_result.append(splited_text.pop()) | |
| # except: | |
| # pass | |
| first_word, first_index = refined_result.pop() # refining last appended word | |
| second_word, second_index = splited_text.pop() | |
| compound_word = first_word+second_word | |
| if len(splited_text)==0: | |
| # last word so we will do check complete word completion | |
| try: | |
| if _make_normal(compound_word) == _make_normal(vyakarana.derive(_kosha.get(compound_word)[0])[0].text): | |
| refined_result.append([compound_word, -1]) | |
| continue | |
| except: | |
| pass | |
| for delta in [0, -1, 1]: | |
| if delta == 0: | |
| chedaka_run = chedaka.run(compound_word) | |
| elif delta == -1: | |
| chedaka_run = chedaka.run(compound_word[:delta]) | |
| elif delta == 1: | |
| if len(splited_text): | |
| next_char = splited_text[-1][0][0] | |
| else: | |
| next_char = '' | |
| chedaka_run = chedaka.run(compound_word+next_char) | |
| if len(chedaka_run)>1: | |
| chedaka_split_idx = len(chedaka_run[0].text) | |
| sandhi_splits = _splitter.split_at(compound_word, min(len(compound_word)-1, first_index-1)) | |
| valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid] | |
| if len(valid_sandhi_splits): | |
| list_candidates = [[[split.first, first_index], [split.second, second_index], -1] for split in valid_sandhi_splits] | |
| ((sandhi_first, _), (sandhi_second, _), is_score_not_none) = score_sandhi_split_candidates(list_candidates, compound_word, chedaka_run[0].text) | |
| 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 | |
| sandhi_split_index = len(sandhi_split.first) if sandhi_split else None | |
| else: | |
| sandhi_split_index = None | |
| sandhi_split = None | |
| if sandhi_split_index is None or abs(sandhi_split_index-first_index)>abs(chedaka_split_idx-first_index): | |
| for _cheda in chedaka_run: | |
| refined_result.append([_cheda.text, second_index]) # this losses first index info but okay for simplicity, only last index matters | |
| else: | |
| try: | |
| if _check(sandhi_split.first): | |
| refined_result.append([sandhi_split.first, first_index]) | |
| refined_result.append([sandhi_split.second, second_index]) | |
| elif _check(chedaka_run[0].text): | |
| for _cheda in chedaka_run: | |
| refined_result.append([_cheda.text, second_index]) # this losses first index info but okay for simplicity, only last index matters | |
| except: | |
| try: | |
| if _check(chedaka_run[0].text): | |
| for _cheda in chedaka_run: | |
| refined_result.append([_cheda.text, second_index]) # this losses first index info but okay for simplicity, only last index matters | |
| except: | |
| refined_result.append([sandhi_split.first, first_index]) | |
| refined_result.append([sandhi_split.second, second_index]) | |
| if delta == 0: | |
| pass | |
| elif delta == -1: | |
| if len(splited_text): | |
| splited_text[-1][0] = compound_word[-1] + splited_text[-1][0] | |
| elif delta == 1: | |
| if len(splited_text): | |
| splited_text[-1][0] = splited_text[-1][0][1:] | |
| break | |
| if len(chedaka_run)<=1: | |
| for delta in [0, -1, 1]: | |
| if delta == 0: | |
| sandhi_splits = _splitter.split_at(compound_word, first_index-1) | |
| valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid] | |
| sandhi_split = valid_sandhi_splits[0] if len(valid_sandhi_splits) else None | |
| sandhi_split_index = len(sandhi_split.first) if sandhi_split else None | |
| elif delta == -1: | |
| sandhi_splits = _splitter.split_at(compound_word[:delta], first_index-1) | |
| valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid] | |
| sandhi_split = valid_sandhi_splits[0] if len(valid_sandhi_splits) else None | |
| sandhi_split_index = len(sandhi_split.first) if sandhi_split else None | |
| elif delta == 1: | |
| if len(splited_text): | |
| next_char = splited_text[-1][0][0] | |
| else: | |
| next_char = '' | |
| sandhi_splits = _splitter.split_at(compound_word+next_char, first_index-1) | |
| valid_sandhi_splits = [split for split in sandhi_splits if split.is_valid] | |
| sandhi_split = valid_sandhi_splits[0] if len(valid_sandhi_splits) else None | |
| sandhi_split_index = len(sandhi_split.first) if sandhi_split else None | |
| if sandhi_split_index is not None: | |
| if delta == 0: | |
| pass | |
| elif delta == -1: | |
| if len(splited_text): | |
| splited_text[-1][0] = second_word[-1] + splited_text[-1][0] | |
| elif delta == 1: | |
| if len(splited_text): | |
| splited_text[-1][0] = splited_text[-1][0][1:] | |
| break | |
| if sandhi_split_index is not None: | |
| refined_result.append([sandhi_split.first, first_index]) | |
| refined_result.append([sandhi_split.second, second_index]) | |
| else: | |
| refined_result.append([compound_word, second_index]) | |
| return refined_result | |
| def give_split(text, id, skip=0): | |
| _segmentation = _splitter.split_at(text[skip:], id - skip)[0] | |
| if _segmentation.is_valid: | |
| return _segmentation.first | |
| def get_best_vidyut_split(text, split_idx, neural_prob): | |
| candidates = _splitter.split_at(text, split_idx) | |
| best_candidate = None | |
| best_score = -1.0 | |
| for cand in candidates: | |
| # 1. Grammar is King: Does Vidyut recognize the resulting words in its lexicon? | |
| is_lexically_valid = cand.is_valid | |
| # Heavy penalty for proposing non-words (e.g., 'uktva' gets crushed here) | |
| base_score = 1.0 if is_lexically_valid else 0.1 | |
| # 2. Smart Sandhi Evaluation | |
| # Check if the split required changing letters (Sandhi inversion) | |
| is_sandhi_inversion = (cand.first != text[:len(cand.first)]) | |
| if is_sandhi_inversion: | |
| if is_lexically_valid: | |
| # REWARD: It's a real dictionary word that required un-joining (e.g., hito -> hita) | |
| base_score += 0.2 | |
| else: | |
| # PENALIZE: It's hallucinating fake sandhi rules to force a split (e.g., uktvA -> uktva) | |
| base_score -= 0.05 | |
| else: | |
| if is_lexically_valid: | |
| # SLIGHT REWARD: Valid literal cuts (like uktvA + kamalA) are highly reliable | |
| base_score += 0.1 | |
| if is_lexically_valid: | |
| base_score += score_word_with_kosha(cand.second) | |
| # 3. Combine with Neural Confidence | |
| total_score = base_score * neural_prob | |
| if total_score > best_score: | |
| best_score = total_score | |
| best_candidate = cand | |
| return best_candidate | |
| def get_score_cand_nxt(text, cand, next_word): | |
| base_score = 0 | |
| # 1. Grammar is King: Does Vidyut recognize the resulting words in its lexicon? | |
| is_lexically_valid = cand.is_valid | |
| # Heavy penalty for proposing non-words (e.g., 'uktva' gets crushed here) | |
| base_score = 1.0 if is_lexically_valid else 0.1 | |
| # 2. Smart Sandhi Evaluation | |
| # Check if the split required changing letters (Sandhi inversion) | |
| is_sandhi_inversion = (cand.first != text[:len(cand.first)]) | |
| if is_sandhi_inversion: | |
| if is_lexically_valid: | |
| # REWARD: It's a real dictionary word that required un-joining (e.g., hito -> hita) | |
| base_score += 0.3 | |
| else: | |
| # PENALIZE: It's hallucinating fake sandhi rules to force a split (e.g., uktvA -> uktva) | |
| base_score -= 0.05 | |
| else: | |
| if is_lexically_valid: | |
| # SLIGHT REWARD: Valid literal cuts (like uktvA + kamalA) are highly reliable | |
| base_score += 0.1 | |
| if is_lexically_valid: | |
| base_score += score_word_with_kosha(cand.second) | |
| base_score += score_word_with_kosha(next_word) | |
| return base_score | |
| def get_best_with_next_word(model, text, original_split_idx, neural_prob): | |
| candidate = get_best_vidyut_split(text, original_split_idx, neural_prob) | |
| next_best_guess_word = sequential_backward_split(model, candidate.second)[0] if candidate.is_valid and candidate.second else '' | |
| return candidate, next_best_guess_word | |
| def get_searched_vidyut_split(text, original_split_idx, neural_prob, minus_1_prob, model=None): | |
| if model is None: | |
| plus_1_cand = get_best_vidyut_split(text, original_split_idx+1, neural_prob) | |
| orginal_cand = get_best_vidyut_split(text, original_split_idx, neural_prob) | |
| minus_1_cand = get_best_vidyut_split(text, original_split_idx-1, neural_prob) if original_split_idx-1>0 else orginal_cand | |
| if minus_1_cand.is_valid and minus_1_prob>0.3: | |
| return minus_1_cand | |
| if neural_prob<0.95 and plus_1_cand.is_valid: | |
| return plus_1_cand | |
| return orginal_cand | |
| else: | |
| score_orginal_cand = 0 | |
| score_plus_cand = 0 | |
| score_minus_cand = 0 | |
| orginal_cand, next_org_word = get_best_with_next_word(model, text, original_split_idx, neural_prob) | |
| 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) | |
| 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) | |
| plus_score = get_score_cand_nxt(text, plus_1_cand, next_plus_word) | |
| org_score = get_score_cand_nxt(text, orginal_cand, next_org_word) | |
| minus_score = get_score_cand_nxt(text, minus_1_cand, next_minus_word) | |
| score_word = [[plus_score, plus_1_cand], [org_score, orginal_cand], [minus_score, minus_1_cand]] | |
| return sorted(score_word, reverse=True)[0][-1] | |
| def sequential_split(model, text, threshold=0.85, delay=2): | |
| result_texts = [] | |
| while text!="": | |
| split_candidate = give_refinement(give_model_split(model, text))[0][0] | |
| print(split_candidate) | |
| result_texts.append(split_candidate) | |
| valid_ = [v for v in _splitter.split_at(text, max(0, len(split_candidate)-1)) if v.is_valid] | |
| text = valid_[0].second if valid_ else _splitter.split_at(text, max(0, len(split_candidate)-1))[0].second | |
| return result_texts | |
| def sequential_backward_split(model, text, threshold=0.85, delay=2): | |
| result_texts = [] | |
| positions_split, prob_split = predicted_pos(model, text, threshold=threshold, delay=delay) # init values | |
| while text!="" and len(positions_split)>0: | |
| positions_split, prob_split = predicted_pos(model, text, threshold=threshold, delay=delay) | |
| positions_split = list(positions_split) | |
| while len(positions_split): | |
| pos_split = positions_split.pop() | |
| split_candidate = get_searched_vidyut_split(text, pos_split, prob_split[pos_split], prob_split[max(0, pos_split-1)], model=model) | |
| if split_candidate.is_valid and split_candidate.second: | |
| result_texts.append(split_candidate.second) | |
| # print("splited : ", split_candidate.first) | |
| # print(len(positions_split)) | |
| text = split_candidate.first | |
| break # for chunking remainging compound | |
| else: | |
| pass # skip unvieriied splits for now simple | |
| # print(text, positions_split) | |
| if text!='': | |
| result_texts.append(text) | |
| result_texts.reverse() | |
| return result_texts | |
| # --------------------------------------------------------------------------- | |
| # Load model | |
| # --------------------------------------------------------------------------- | |
| def load_model(checkpoint_dir: str, device: torch.device) -> Tuple[BinaryBoundaryModel, int]: | |
| """Load model and extract delay from config or checkpoint.""" | |
| config_path = os.path.join(checkpoint_dir, "config.json") | |
| if os.path.exists(config_path): | |
| config = HybridTimeScaleConfig.from_pretrained(checkpoint_dir) | |
| else: | |
| # Infer config from checkpoint weights | |
| print(f"[warn] No config.json, inferring from checkpoint", file=sys.stderr) | |
| from safetensors.torch import load_file | |
| sd_path = os.path.join(checkpoint_dir, "model.safetensors") | |
| if not os.path.exists(sd_path): | |
| sd_path = os.path.join(checkpoint_dir, "pytorch_model.bin") | |
| sd = torch.load(sd_path, map_location="cpu", weights_only=False) | |
| else: | |
| sd = load_file(sd_path) | |
| # Clean keys | |
| sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()} | |
| latent_dim = sd["embedding.weight"].shape[1] | |
| q_out = sd["blocks.0.mixer.q_proj.weight"].shape[0] | |
| # num_heads defaults to max(1, latent_dim // 64) in HybridSpectralBlock | |
| num_heads = max(1, latent_dim // 64) | |
| num_modes = q_out // num_heads | |
| num_layers = sum(1 for k in sd if k.startswith("blocks.") and k.endswith(".ffn.1.weight")) | |
| print(f" Inferred: latent_dim={latent_dim}, num_modes={num_modes}, " | |
| f"num_heads={num_heads}, num_layers={num_layers}", file=sys.stderr) | |
| config = HybridTimeScaleConfig( | |
| vocab_size=VOCAB_SIZE, latent_dim=latent_dim, num_layers=num_layers, | |
| num_modes=num_modes, | |
| layer_types=["linear", "softmax"][:num_layers] or ["linear", "softmax"], | |
| time_scale=float(2 * num_modes), | |
| dropout=0.1, pad_token_id=PAD_ID, | |
| bos_token_id=0, eos_token_id=0, tie_word_embeddings=False, | |
| ) | |
| delay = getattr(config, "delay", 0) | |
| print(f"Model delay: {delay}", file=sys.stderr) | |
| model = BinaryBoundaryModel(config) | |
| sd_path = os.path.join(checkpoint_dir, "model.safetensors") | |
| if os.path.exists(sd_path): | |
| from safetensors.torch import load_file | |
| state_dict = load_file(sd_path) | |
| else: | |
| sd_path = os.path.join(checkpoint_dir, "pytorch_model.bin") | |
| state_dict = torch.load(sd_path, map_location="cpu", weights_only=False) | |
| state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()} | |
| model.load_state_dict(state_dict, strict=False) | |
| model = model.to(device) | |
| model.eval() | |
| return model, delay | |
| import copy | |
| def better_decode(model, text): | |
| _input = text | |
| result = [] | |
| splits = give_refinement(give_model_split(model, copy.deepcopy(_input), 0.3)) | |
| while _input or len(splits)>1: | |
| _input = text[len(splits[0][0]):] | |
| result.append(splits[0][0]) | |
| splits = give_refinement(give_model_split(model, copy.deepcopy(_input), 0.3)) | |
| return result + [li[0] for li in splits] | |
| def give_correct_slp1_input(text): | |
| return do_sandhi_join(*lipi.transliterate(text, lipi.Scheme.Devanagari, lipi.Scheme.Slp1).split()) | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Run Sandhi vigraha test suite.") | |
| parser.add_argument("text", nargs="?", default=None) | |
| parser.add_argument("--batch", default=None) | |
| parser.add_argument("--test-file", default="test_cases.json") | |
| parser.add_argument("--checkpoint", default="checkpoints/delayed_model_save_fixed_delay2_v2") | |
| parser.add_argument("--delay", type=int, default=2) | |
| parser.add_argument("--threshold", type=float, default=0.85) | |
| parser.add_argument("--bias-first-word", action="store_true") | |
| parser.add_argument("--verbose", "-v", action="store_true") | |
| args = parser.parse_args() | |
| if torch.cuda.is_available(): | |
| device = torch.device("cuda") | |
| elif torch.backends.mps.is_available(): | |
| device = torch.device("mps") | |
| else: | |
| device = torch.device("cpu") | |
| print(f"Device: {device}", file=sys.stderr) | |
| # Load model | |
| print(f"Loading model from {args.checkpoint}...", file=sys.stderr) | |
| model, delay = load_model(args.checkpoint, device) | |
| if args.delay is not None: | |
| delay = args.delay | |
| print(f"Model loaded (delay={delay})", file=sys.stderr) | |
| threshold = args.threshold | |
| # Load test cases | |
| with open(args.test_file) as f: | |
| test_cases = json.load(f) | |
| print(f"\nLoaded {len(test_cases)} test cases\n", file=sys.stderr) | |
| text = 'vidyAdadAtivinayaMvinayAdyAtipAtratAm' | |
| res = refinement_seq(model, text) | |
| print(res) | |
| give_chedaka_refinement(give_model_split(model, 'karmARyevADikArastemAphalezukadAcana', 0.7)) | |
| give_refinement(give_model_split(model, 'karmARyevADikArastemAphalezukadAcana', 0.4)) | |
| if test_cases: | |
| for test_case in test_cases: | |
| text = test_case.get('input', '') | |
| expected_output = test_case.get('expected', '').split() | |
| pred_output = sequential_split(model, text, threshold=threshold) | |
| print("Input Text:\t", text) | |
| print('Expected Output:\t', expected_output) | |
| print('Predicted Output:\t', pred_output) | |
| print() | |
| texts: List[str] = [] | |
| if args.batch: | |
| with open(args.batch) as f: | |
| texts = [line.strip() for line in f if line.strip()] | |
| elif args.text: | |
| texts = [args.text] | |
| else: | |
| print("\nEnter Sanskrit text (SLP1), Ctrl+D to exit:", file=sys.stderr) | |
| while True: | |
| try: | |
| t = input(">>> ").strip() | |
| if t: | |
| print(sequential_split(model, t, threshold=threshold)) | |
| texts.append(t) | |
| except EOFError: | |
| break | |
| for text in texts: | |
| print(sequential_split(model, text, threshold=threshold)) | |
| if __name__ =='__main__': | |
| main() | |