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1 |
+
from torch import nn
|
2 |
+
from transformers import CanineModel, CanineForTokenClassification, CaninePreTrainedModel, CanineTokenizer
|
3 |
+
from transformers.modeling_outputs import TokenClassifierOutput
|
4 |
+
import gradio as gr
|
5 |
+
|
6 |
+
|
7 |
+
arabic_to_hebrew = {
|
8 |
+
# regular letters
|
9 |
+
"ا": "א", "أ": "א", "إ": "א", "ء": "א", "ئ": "א", "ؤ": "א",
|
10 |
+
"آ": "אא", "ى": "א", "ب": "ב", "ت": "ת", "ث": "ת'", "ج": "ג'",
|
11 |
+
"ح": "ח", "خ": "ח'", "د": "ד", "ذ": "ד'", "ر": "ר", "ز": "ז",
|
12 |
+
"س": "ס", "ش": "ש", "ص": "צ", "ض": "צ'", "ط": "ט", "ظ": "ט'",
|
13 |
+
"ع": "ע", "غ": "ע'", "ف": "פ", "ق": "ק", "ك": "כ", "ل": "ל",
|
14 |
+
"م": "מ", "ن": "נ", "ه": "ה", "و": "ו", "ي": "י", "ة": "ה",
|
15 |
+
# special characters
|
16 |
+
"،": ",", "َ": "ַ", "ُ": "ֻ", "ِ": "ִ",
|
17 |
+
}
|
18 |
+
|
19 |
+
final_letters = {
|
20 |
+
"ن": "ן", "م": "ם", "ص": "ץ", "ض": "ץ'", "ف": "ף",
|
21 |
+
}
|
22 |
+
|
23 |
+
def to_taatik(arabic):
|
24 |
+
taatik = []
|
25 |
+
for index, letter in enumerate(arabic):
|
26 |
+
if (
|
27 |
+
(index == len(arabic) - 1 or arabic[index + 1] in {" ", ".", "،"}) and
|
28 |
+
letter in final_letters
|
29 |
+
):
|
30 |
+
taatik.append(final_letters[letter])
|
31 |
+
elif letter not in arabic_to_hebrew:
|
32 |
+
taatik.append(letter)
|
33 |
+
else:
|
34 |
+
taatik.append(arabic_to_hebrew[letter])
|
35 |
+
return taatik
|
36 |
+
|
37 |
+
|
38 |
+
class TaatikModel(CaninePreTrainedModel):
|
39 |
+
# based on CaninePreTrainedModel
|
40 |
+
# slightly modified for multilabel classification
|
41 |
+
|
42 |
+
def __init__(self, config, num_labels=7):
|
43 |
+
# Note: one label for each nikud type, plus one for the deletion flag
|
44 |
+
super().__init__(config)
|
45 |
+
config.num_labels = num_labels
|
46 |
+
self.num_labels = config.num_labels
|
47 |
+
|
48 |
+
self.canine = CanineModel(config)
|
49 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
50 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
51 |
+
|
52 |
+
# Initialize weights and apply final processing
|
53 |
+
self.post_init()
|
54 |
+
|
55 |
+
self.criterion = nn.BCEWithLogitsLoss()
|
56 |
+
|
57 |
+
def forward(
|
58 |
+
self,
|
59 |
+
input_ids=None,
|
60 |
+
attention_mask=None,
|
61 |
+
token_type_ids=None,
|
62 |
+
position_ids=None,
|
63 |
+
head_mask=None,
|
64 |
+
inputs_embeds=None,
|
65 |
+
labels=None,
|
66 |
+
output_attentions=None,
|
67 |
+
output_hidden_states=None,
|
68 |
+
):
|
69 |
+
|
70 |
+
outputs = self.canine(
|
71 |
+
input_ids,
|
72 |
+
attention_mask=attention_mask,
|
73 |
+
token_type_ids=token_type_ids,
|
74 |
+
position_ids=position_ids,
|
75 |
+
head_mask=head_mask,
|
76 |
+
inputs_embeds=inputs_embeds,
|
77 |
+
output_attentions=output_attentions,
|
78 |
+
output_hidden_states=output_hidden_states
|
79 |
+
)
|
80 |
+
|
81 |
+
sequence_output = outputs[0]
|
82 |
+
|
83 |
+
sequence_output = self.dropout(sequence_output)
|
84 |
+
logits = self.classifier(sequence_output)
|
85 |
+
|
86 |
+
loss = None
|
87 |
+
if labels is not None:
|
88 |
+
# print(logits)
|
89 |
+
# print("-----------")
|
90 |
+
# print(labels)
|
91 |
+
loss = self.criterion(logits, labels)
|
92 |
+
|
93 |
+
return TokenClassifierOutput(
|
94 |
+
loss=loss,
|
95 |
+
logits=logits,
|
96 |
+
hidden_states=outputs.hidden_states,
|
97 |
+
attentions=outputs.attentions,
|
98 |
+
)
|
99 |
+
|
100 |
+
# tokenizer = CanineTokenizer.from_pretrained("google/canine-c")
|
101 |
+
# model = TashkeelModel.from_pretrained("google/canine-c")
|
102 |
+
|
103 |
+
tokenizer = CanineTokenizer.from_pretrained("google/canine-s")
|
104 |
+
# model = TaatikModel.from_pretrained("google/canine-s")
|
105 |
+
# model = TaatikModel.from_pretrained("./checkpoint-19034/")
|
106 |
+
model = TaatikModel.from_pretrained("guymorlan/Arabic2Taatik")
|
107 |
+
|
108 |
+
|
109 |
+
def convert_nikkud_to_harakat(nikkud):
|
110 |
+
labels = []
|
111 |
+
if "SHADDA" in nikkud:
|
112 |
+
labels.append("SHADDA")
|
113 |
+
if "TSERE" in nikkud:
|
114 |
+
labels.append("KASRA")
|
115 |
+
if "HOLAM" in nikkud:
|
116 |
+
labels.append("DAMMA")
|
117 |
+
if "PATACH" in nikkud:
|
118 |
+
labels.append("FATHA")
|
119 |
+
if "SHVA" in nikkud:
|
120 |
+
labels.append("SUKUN")
|
121 |
+
if "KUBUTZ" in nikkud:
|
122 |
+
labels.append("DAMMA")
|
123 |
+
if "HIRIQ" in nikkud:
|
124 |
+
labels.append("KASRA")
|
125 |
+
return labels
|
126 |
+
|
127 |
+
def convert_binary_to_labels(binary_labels):
|
128 |
+
labels = []
|
129 |
+
if binary_labels[0] == 1:
|
130 |
+
labels.append("SHADDA")
|
131 |
+
if binary_labels[1] == 1:
|
132 |
+
labels.append("TSERE")
|
133 |
+
if binary_labels[2] == 1:
|
134 |
+
labels.append("HOLAM")
|
135 |
+
if binary_labels[3] == 1:
|
136 |
+
labels.append("PATACH")
|
137 |
+
if binary_labels[4] == 1:
|
138 |
+
labels.append("SHVA")
|
139 |
+
if binary_labels[5] == 1:
|
140 |
+
labels.append("KUBUTZ")
|
141 |
+
if binary_labels[6] == 1:
|
142 |
+
labels.append("HIRIQ")
|
143 |
+
return labels
|
144 |
+
|
145 |
+
def convert_label_names_to_chars(label):
|
146 |
+
if label == "SHADDA":
|
147 |
+
return "ّ"
|
148 |
+
if label == "TSERE":
|
149 |
+
return "ֵ"
|
150 |
+
if label == "HOLAM":
|
151 |
+
return "ֹ"
|
152 |
+
if label == "PATACH":
|
153 |
+
return "ַ"
|
154 |
+
if label == "SHVA":
|
155 |
+
return "ְ"
|
156 |
+
if label == "KUBUTZ":
|
157 |
+
return "ֻ"
|
158 |
+
if label == "HIRIQ":
|
159 |
+
return "ִ"
|
160 |
+
|
161 |
+
# for these, return arabic harakat
|
162 |
+
if label == "DAMMA":
|
163 |
+
return "ُ"
|
164 |
+
if label == "KASRA":
|
165 |
+
return "ِ"
|
166 |
+
if label == "FATHA":
|
167 |
+
return "َ"
|
168 |
+
if label == "SUKUN":
|
169 |
+
return "ْ"
|
170 |
+
return ""
|
171 |
+
|
172 |
+
def predict(input, prefix = "P "):
|
173 |
+
print(input)
|
174 |
+
input_tok = tokenizer(prefix+input, return_tensors="pt")
|
175 |
+
print(input_tok)
|
176 |
+
outputs = model(**input_tok)
|
177 |
+
print(outputs)
|
178 |
+
labels = outputs.logits.sigmoid().round().int()
|
179 |
+
labels = labels.tolist()[0][3:-1]
|
180 |
+
print(labels)
|
181 |
+
labels_hebrew = [convert_binary_to_labels(x) for x in labels]
|
182 |
+
labels_arabic = [convert_nikkud_to_harakat(x) for x in labels_hebrew]
|
183 |
+
print(f"labels_hebrew: {labels_hebrew}")
|
184 |
+
print(f"labels_arabic: {labels_arabic}")
|
185 |
+
|
186 |
+
hebrew = [[x] for x in to_taatik(input)]
|
187 |
+
print(hebrew)
|
188 |
+
arabic = [[x] for x in input]
|
189 |
+
print(arabic)
|
190 |
+
|
191 |
+
print(f"len hebrew: {len(hebrew)}")
|
192 |
+
print(f"len arabic: {len(arabic)}")
|
193 |
+
print(f"len labels_hebrew: {len(labels_hebrew)}")
|
194 |
+
print(f"len labels_arabic: {len(labels_arabic)}")
|
195 |
+
print(f"labels: {labels}")
|
196 |
+
print(f"labels_hebrew: {labels_hebrew}")
|
197 |
+
print(f"labels_arabic: {labels_arabic}")
|
198 |
+
|
199 |
+
for i in range(len(hebrew)):
|
200 |
+
hebrew[i].extend([convert_label_names_to_chars(x) for x in labels_hebrew[i]])
|
201 |
+
arabic[i].extend([convert_label_names_to_chars(x) for x in labels_arabic[i]])
|
202 |
+
|
203 |
+
|
204 |
+
hebrew = ["".join(x) for x in hebrew]
|
205 |
+
arabic = ["".join(x) for x in arabic]
|
206 |
+
|
207 |
+
# loop over hebrew, if there is a ' in the second position move it to last position
|
208 |
+
for i in range(len(hebrew)):
|
209 |
+
if len(hebrew[i]) > 1 and hebrew[i][1] == "'":
|
210 |
+
hebrew[i] = hebrew[i][0] + hebrew[i][2:] + hebrew[i][1]
|
211 |
+
|
212 |
+
hebrew = "".join(hebrew)
|
213 |
+
arabic = "".join(arabic)
|
214 |
+
|
215 |
+
|
216 |
+
return f"<p dir='rtl' style='font-size: 1.5em; font-family: Arial Unicode MS;'>{hebrew}</p><p dir='rtl' style='font-size: 1.5em; font-family: Noto;'>{arabic}</p>"
|
217 |
+
|
218 |
+
font = "Arial Unicode MS, Tahoma, sans-serif"
|
219 |
+
return f"<p dir='rtl' style='font-size: 1.5em; font-family: {font};'>{hebrew}</p><p dir='rtl' style='font-size: 1.5em; font-family: {font};'>{arabic}</p>"
|
220 |
+
return f"<p dir='rtl' style='font-size: 1.5em; font-family: Heebo;'>{hebrew}</p><p dir='rtl' style='font-size: 1.5em; font-family: Heebo;'>{arabic}</p>"
|
221 |
+
|
222 |
+
# return f"<p dir='rtl' style='font-size: 1.5em'>{hebrew}</p><p dir='rtl' style='font-size: 1.5em'>{arabic}</p>"
|
223 |
+
|
224 |
+
font_url = "<link href='https://fonts.googleapis.com/css2?family=Heebo&display=swap' rel='stylesheet'>"
|
225 |
+
|
226 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Ammiya Diacritizer") as demo:
|
227 |
+
gr.HTML("<h2><span style='color: #2563eb'>Colloquial Arabic</span></h2> Diacritizer and Hebrew Transliterator" + font_url)
|
228 |
+
with gr.Row():
|
229 |
+
with gr.Column():
|
230 |
+
input = gr.Textbox(label="Input", placeholder="Enter Arabic text", lines=1)
|
231 |
+
gr.Examples(["بديش اروح معك"], input)
|
232 |
+
btn = gr.Button(label="Analyze")
|
233 |
+
with gr.Column():
|
234 |
+
with gr.Box():
|
235 |
+
html = gr.HTML()
|
236 |
+
btn.click(predict, inputs=[input], outputs=[html])
|
237 |
+
input.submit(predict, inputs = [input], outputs=[html])
|
238 |
+
|
239 |
+
demo.load()
|
240 |
+
demo.launch()
|
241 |
+
|