NourFakih commited on
Commit
5edd0fc
·
verified ·
1 Parent(s): bc49386

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. README.md +23 -0
  2. config.json +31 -0
  3. inference.py +77 -0
  4. label2id.json +19 -0
  5. meta.json +26 -0
  6. model.safetensors +3 -0
  7. stoi.json +1 -0
README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ar
3
+ library_name: pytorch
4
+ tags:
5
+ - arabic
6
+ - poetry
7
+ - meter
8
+ - classification
9
+ ---
10
+
11
+ # ashaar-meter-classification-pytorch
12
+
13
+ PyTorch character-level Arabic meter classifier.
14
+
15
+ ## Artifacts
16
+ - `model.safetensors`: model weights
17
+ - `config.json`: architecture + class list
18
+ - `stoi.json`: character-to-id mapping (0 is padding)
19
+ - `label2id.json`: meter label mapping
20
+ - `meta.json`: training metadata
21
+
22
+ ## Notes
23
+ This repo stores only the trained model + metadata (no training arrays).
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task": "text-classification",
3
+ "tokenization": "character-level",
4
+ "max_length": 128,
5
+ "vocab_size": 46,
6
+ "num_classes": 17,
7
+ "classes": [
8
+ "البسيط",
9
+ "الخفيف",
10
+ "الرجز",
11
+ "الرمل",
12
+ "السريع",
13
+ "الطويل",
14
+ "الكامل",
15
+ "المتدارك",
16
+ "المتقارب",
17
+ "المجتث",
18
+ "المديد",
19
+ "المضارع",
20
+ "المقتضب",
21
+ "المنسرح",
22
+ "الهزج",
23
+ "الوافر",
24
+ "نثر"
25
+ ],
26
+ "emb_dim": 64,
27
+ "num_heads": 4,
28
+ "ff_dim": 256,
29
+ "gru_blocks": 3,
30
+ "dropout": 0.1
31
+ }
inference.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import json, numpy as np, torch
3
+ import torch.nn as nn
4
+ from safetensors.torch import load_file
5
+
6
+ class TransformerBlock(nn.Module):
7
+ def __init__(self, dim, heads, ff_dim, dropout):
8
+ super().__init__()
9
+ self.mha = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
10
+ self.ln1 = nn.LayerNorm(dim); self.ln2 = nn.LayerNorm(dim)
11
+ self.drop = nn.Dropout(dropout)
12
+ self.ffn = nn.Sequential(nn.Linear(dim, ff_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(ff_dim, dim))
13
+ def forward(self, x, key_padding_mask=None):
14
+ attn_out, _ = self.mha(x, x, x, key_padding_mask=key_padding_mask, need_weights=False)
15
+ x = self.ln1(x + self.drop(attn_out))
16
+ ff_out = self.ffn(x)
17
+ return self.ln2(x + self.drop(ff_out))
18
+
19
+ class BiGRUResidualBlock(nn.Module):
20
+ def __init__(self, dim, dropout):
21
+ super().__init__()
22
+ self.gru = nn.GRU(dim, dim//2, num_layers=1, batch_first=True, bidirectional=True)
23
+ self.ln = nn.LayerNorm(dim); self.drop = nn.Dropout(dropout)
24
+ def forward(self, x):
25
+ out, _ = self.gru(x)
26
+ return self.ln(x + self.drop(out))
27
+
28
+ class MeterModel(nn.Module):
29
+ def __init__(self, vocab_size, num_classes, T, emb_dim=64, num_heads=4, ff_dim=256, gru_blocks=3, dropout=0.1):
30
+ super().__init__()
31
+ self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
32
+ self.pos = nn.Embedding(T, emb_dim)
33
+ self.drop = nn.Dropout(dropout)
34
+ self.tr = TransformerBlock(emb_dim, num_heads, ff_dim, dropout)
35
+ self.gru_blocks = nn.ModuleList([BiGRUResidualBlock(emb_dim, dropout) for _ in range(gru_blocks)])
36
+ self.head = nn.Sequential(nn.Linear(emb_dim, 128), nn.ReLU(), nn.Dropout(dropout), nn.Linear(128, num_classes))
37
+ def forward(self, x):
38
+ B, T = x.shape
39
+ pos = torch.arange(T, device=x.device).unsqueeze(0).expand(B, T)
40
+ h = self.drop(self.emb(x) + self.pos(pos))
41
+ pad_mask = (x == 0)
42
+ h = self.tr(h, key_padding_mask=pad_mask)
43
+ for blk in self.gru_blocks:
44
+ h = blk(h)
45
+ mask = (~pad_mask).float().unsqueeze(-1)
46
+ pooled = (h * mask).sum(1) / mask.sum(1).clamp_min(1.0)
47
+ return self.head(pooled)
48
+
49
+ def load_local(repo_dir="."):
50
+ cfg = json.load(open(f"{repo_dir}/config.json", "r", encoding="utf-8"))
51
+ stoi = json.load(open(f"{repo_dir}/stoi.json", "r", encoding="utf-8"))
52
+ classes = cfg["classes"]
53
+ model = MeterModel(
54
+ vocab_size=cfg["vocab_size"], num_classes=cfg["num_classes"], T=cfg["max_length"],
55
+ emb_dim=cfg["emb_dim"], num_heads=cfg["num_heads"], ff_dim=cfg["ff_dim"],
56
+ gru_blocks=cfg["gru_blocks"], dropout=cfg["dropout"]
57
+ )
58
+ sd = load_file(f"{repo_dir}/model.safetensors")
59
+ model.load_state_dict(sd)
60
+ model.eval()
61
+ return model, stoi, classes, cfg["max_length"]
62
+
63
+ def encode(text, stoi, max_len):
64
+ ids = np.zeros((max_len,), dtype=np.int64)
65
+ for i, ch in enumerate(text[:max_len]):
66
+ ids[i] = stoi.get(ch, 0)
67
+ return torch.from_numpy(ids).unsqueeze(0)
68
+
69
+ @torch.no_grad()
70
+ def predict(text, model, stoi, classes, max_len, topk=5):
71
+ x = encode(text, stoi, max_len)
72
+ logits = model(x)[0]
73
+ probs = torch.softmax(logits, dim=-1)
74
+ topv, topi = torch.topk(probs, k=min(topk, probs.numel()))
75
+ pred = classes[int(topi[0])]
76
+ top = [(classes[int(i)], float(v)) for v, i in zip(topv, topi)]
77
+ return pred, top
label2id.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "البسيط": 0,
3
+ "الخفيف": 1,
4
+ "الرجز": 2,
5
+ "الرمل": 3,
6
+ "السريع": 4,
7
+ "الطويل": 5,
8
+ "الكامل": 6,
9
+ "المتدارك": 7,
10
+ "المتقارب": 8,
11
+ "المجتث": 9,
12
+ "المديد": 10,
13
+ "المضارع": 11,
14
+ "المقتضب": 12,
15
+ "المنسرح": 13,
16
+ "الهزج": 14,
17
+ "الوافر": 15,
18
+ "نثر": 16
19
+ }
meta.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "N": 1657003,
3
+ "T": 128,
4
+ "vocab_size": 46,
5
+ "num_classes": 17,
6
+ "test_samples": 163917,
7
+ "classes": [
8
+ "البسيط",
9
+ "الخفيف",
10
+ "الرجز",
11
+ "الرمل",
12
+ "السريع",
13
+ "الطويل",
14
+ "الكامل",
15
+ "المتدارك",
16
+ "المتقارب",
17
+ "المجتث",
18
+ "المديد",
19
+ "المضارع",
20
+ "المقتضب",
21
+ "المنسرح",
22
+ "الهزج",
23
+ "الوافر",
24
+ "نثر"
25
+ ]
26
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4d99dab2a1e84c6d190fa9e4b3ebe198d7400401e3de42bddc833d6bd5a8b54
3
+ size 518076
stoi.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {" ": 1, "ء": 2, "آ": 3, "أ": 4, "ؤ": 5, "إ": 6, "ئ": 7, "ا": 8, "ب": 9, "ة": 10, "ت": 11, "ث": 12, "ج": 13, "ح": 14, "خ": 15, "د": 16, "ذ": 17, "ر": 18, "ز": 19, "س": 20, "ش": 21, "ص": 22, "ض": 23, "ط": 24, "ظ": 25, "ع": 26, "غ": 27, "ف": 28, "ق": 29, "ك": 30, "ل": 31, "م": 32, "ن": 33, "ه": 34, "و": 35, "ى": 36, "ي": 37, "ً": 38, "ٌ": 39, "ٍ": 40, "َ": 41, "ُ": 42, "ِ": 43, "ّ": 44, "ْ": 45}