"""Self-contained CPU inference for alim-arabic-models (torch + safetensors only). from inference_example import vocalize, predict_meter vocalize("diac-prose", "العلم نور يهدي صاحبه الى الخير") predict_meter("meter-16", "قفا نبك من ذكرى حبيب ومنزل", "بأرض العدا") """ import json import sys from functools import lru_cache from pathlib import Path if sys.stdout.encoding != "utf-8": import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") import torch import torch.nn as nn from safetensors.torch import load_file ROOT = Path(__file__).parent _MARKS = set("ًٌٍَُِّْ") _LETTERS = set("ابتثجحخدذرزسشصضطظعغفقكلمنهويءآأؤإئاةوينلر") _INV_DIAC = {1: "َ", 2: "ُ", 3: "ِ", 4: "ْ"} _INV_TANWIN = {1: "ً", 2: "ٌ", 3: "ٍ"} class _Diac(nn.Module): # ALIMDiacritizer, eval path (dropout = identity) def __init__(self, c): super().__init__() E, H, L, NH = c["embed_dim"], c["hidden_dim"], c["num_layers"], c["num_heads"] self.embedding = nn.Embedding(c["vocab_size"], E, padding_idx=0) self.embed_dropout = nn.Dropout(0.3) self.lstm = nn.LSTM(E, H, L, bidirectional=True, batch_first=True) self.attention_norm = nn.LayerNorm(2 * H) self.attention = nn.MultiheadAttention(2 * H, NH, batch_first=True) self.ffn_norm = nn.LayerNorm(2 * H) self.ffn = nn.Sequential(nn.Linear(2 * H, 8 * H), nn.GELU(), nn.Dropout(0.3), nn.Linear(8 * H, 2 * H), nn.Dropout(0.3)) self.diacritic_classifier = nn.Linear(2 * H, 5) self.shadda_classifier = nn.Linear(2 * H, 2) self.tanwin_classifier = nn.Linear(2 * H, 4) def forward(self, x): lo, _ = self.lstm(self.embed_dropout(self.embedding(x))) n = self.attention_norm(lo) a, _ = self.attention(n, n, n, key_padding_mask=(x == 0)) a = a + lo f = self.ffn(self.ffn_norm(a)) + a return (self.diacritic_classifier(f), self.shadda_classifier(f), self.tanwin_classifier(f)) class _Meter(nn.Module): # MeterClassifier, eval path def __init__(self, c): super().__init__() E, H = c["embed_dim"], c["hidden_dim"] self.embedding = nn.Embedding(c["vocab_size"], E, padding_idx=0) self.lstm = nn.LSTM(E, H, c["num_layers"], bidirectional=True, batch_first=True) self.attention = nn.MultiheadAttention(2 * H, c["num_heads"], batch_first=True) self.attention_norm = nn.LayerNorm(2 * H) self.classifier = nn.Sequential(nn.Linear(2 * H, H), nn.GELU(), nn.Dropout(0.3), nn.Linear(H, c["num_classes"])) def forward(self, x, ln): lo, _ = self.lstm(nn.utils.rnn.pack_padded_sequence( self.embedding(x), ln.cpu(), batch_first=True, enforce_sorted=False)) lo, _ = nn.utils.rnn.pad_packed_sequence(lo, batch_first=True) t = lo.size(1) pm = torch.arange(t).unsqueeze(0) >= ln.clamp(max=t).unsqueeze(1) a, _ = self.attention(lo, lo, lo, key_padding_mask=pm) a = self.attention_norm(a + lo) m = (torch.arange(t).unsqueeze(0) < ln.unsqueeze(1)).float().unsqueeze(-1) return self.classifier((a * m).sum(1) / m.sum(1).clamp(min=1)) @lru_cache(maxsize=4) def _load(kind): d = ROOT / kind cfg = json.loads((d / "config.json").read_text(encoding="utf-8")) if kind.startswith("diac"): m = _Diac(cfg) else: m = _Meter(cfg) m.vocab = json.loads((d / "vocab.json").read_text(encoding="utf-8")) m.i2m = json.loads((d / "idx_to_meter.json").read_text(encoding="utf-8")) m.load_state_dict(load_file(str(d / "model.safetensors"))) return m.eval() @torch.no_grad() def vocalize(kind, text, max_letters=64): """Vocalize bare Arabic text. kind: 'diac-prose' or 'diac-verse'.""" m = _load(kind) letters = [c for c in text if c in _LETTERS][:max_letters] x = torch.tensor([[ord(c) % 50000 for c in letters] + [0] * (max_letters - len(letters))]) d, s, w = (t[0][: len(letters)].argmax(-1).tolist() for t in m(x)) out, li = [], 0 for ch in text: if ch in _LETTERS and li < len(letters): r = ch + ("ّ" if s[li] else "") + ( _INV_TANWIN.get(w[li], "") or _INV_DIAC.get(d[li], "")) out.append(r) li += 1 else: out.append(ch) return "".join(out) @torch.no_grad() def predict_meter(kind, sadr, ajuz, max_len=128): """Predict canonical meter family for a (sadr, ajuz) bayt.""" m = _load(kind) txt = (sadr + " | " + ajuz)[:max_len] idx = [m.vocab.get(ch, m.vocab.get("", 1)) for ch in txt] x = torch.tensor([idx + [0] * (max_len - len(idx))]) return m.i2m[str(m(x, torch.tensor([max(len(idx), 1)])).argmax(-1).item())] if __name__ == "__main__": print(vocalize("diac-prose", "العلم نور يهدي صاحبه الى الخير")) print(predict_meter("meter-16", "قفا نبك من ذكرى حبيب ومنزل", "بسقط اللوى بين الدخول فحومل"))