Use an Arabic Segmentation Tool + Support the new Transformer Pipeline
Browse files
README.md
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
---
|
| 2 |
language: ar
|
| 3 |
datasets:
|
|
@@ -33,39 +34,98 @@ Person, Location, Organization, Nationality, Job, Product, Event, Time, Art-Work
|
|
| 33 |
|
| 34 |
Install the following Python packages
|
| 35 |
|
| 36 |
-
`$ pip3 install transformers==4.
|
| 37 |
|
| 38 |
> If you are using `Google Colab`, please restart your runtime after installing the packages.
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
-----------
|
| 41 |
|
| 42 |
```python
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
import logging
|
| 44 |
import re
|
| 45 |
|
| 46 |
import nltk
|
| 47 |
nltk.download('punkt')
|
| 48 |
-
from nltk.tokenize import word_tokenize
|
|
|
|
|
|
|
| 49 |
|
| 50 |
# disable INFO Logs
|
| 51 |
transformers_logger = logging.getLogger("transformers")
|
| 52 |
transformers_logger.setLevel(logging.WARNING)
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
custom_labels = ["O", "B-job", "I-job", "B-nationality", "B-person", "I-person", "B-location",
|
| 55 |
"B-time", "I-time", "B-event", "I-event", "B-organization", "I-organization",
|
| 56 |
"I-location", "I-nationality", "B-product", "I-product", "B-artwork", "I-artwork"]
|
| 57 |
|
| 58 |
-
|
| 59 |
-
from transformers import pipeline
|
| 60 |
-
|
| 61 |
-
# ===== import the model
|
| 62 |
m_name = "marefa-nlp/marefa-ner"
|
| 63 |
tokenizer = AutoTokenizer.from_pretrained(m_name)
|
| 64 |
model = AutoModelForTokenClassification.from_pretrained(m_name)
|
| 65 |
|
| 66 |
ar_ner = pipeline("ner", model=model, tokenizer=tokenizer, grouped_entities=True, aggregation_strategy="simple")
|
| 67 |
|
| 68 |
-
# Model Inference
|
| 69 |
samples = [
|
| 70 |
"تلقى تعليمه في الكتاب ثم انضم الى الأزهر عام 1873م. تعلم على يد السيد جمال الدين الأفغاني والشيخ محمد عبده",
|
| 71 |
"بعد عودته إلى القاهرة، التحق نجيب الريحاني فرقة جورج أبيض، الذي كان قد ضمَّ - قُبيل ذلك - فرقته إلى فرقة سلامة حجازي . و منها ذاع صيته",
|
|
@@ -73,44 +133,57 @@ samples = [
|
|
| 73 |
"Government extends flight ban from India and Pakistan until June 21"
|
| 74 |
]
|
| 75 |
|
| 76 |
-
#
|
| 77 |
samples = [ " ".join(word_tokenize(sample.strip())) for sample in samples if sample.strip() != "" ]
|
| 78 |
|
| 79 |
for sample in samples:
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
print("=========\n")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
| 114 |
```
|
| 115 |
|
| 116 |
## Fine-Tuning
|
|
|
|
| 1 |
+
|
| 2 |
---
|
| 3 |
language: ar
|
| 4 |
datasets:
|
|
|
|
| 34 |
|
| 35 |
Install the following Python packages
|
| 36 |
|
| 37 |
+
`$ pip3 install transformers==4.8.0 nltk==3.5 protobuf==3.15.3 torch==1.9.0 `
|
| 38 |
|
| 39 |
> If you are using `Google Colab`, please restart your runtime after installing the packages.
|
| 40 |
|
| 41 |
+
[**OPTIONAL**]
|
| 42 |
+
Using of an Arabic segmentation tool approved better results in many scenarios. If you want to use `FarasaPy`to segment the texts, please ensure that you have `openjdk-11`installed in your machine, then install the package via:
|
| 43 |
+
```bash
|
| 44 |
+
# install openjdk-11-jdk
|
| 45 |
+
$ apt-get install -y build-essential
|
| 46 |
+
$ apt-get install -y openjdk-11-jdk
|
| 47 |
+
|
| 48 |
+
# instll FarasaPy
|
| 49 |
+
$ pip3 install farasapy==0.0.13
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
*Do not forget to set `USE_FARASAPY` to `True` in the following code*
|
| 53 |
+
|
| 54 |
+
Also, you can set `USE_SENTENCE_TOKENIZER` to `True` for getting better results for long texts.
|
| 55 |
+
|
| 56 |
-----------
|
| 57 |
|
| 58 |
```python
|
| 59 |
+
|
| 60 |
+
# ==== Set configurations
|
| 61 |
+
# do you want to use FarasaPy Segmentation tool ?
|
| 62 |
+
USE_FARASAPY = False # set to True to use it
|
| 63 |
+
|
| 64 |
+
# do you want to split text into sentences [better for long texts] ?
|
| 65 |
+
USE_SENTENCE_TOKENIZER = False # set to True to use it
|
| 66 |
+
|
| 67 |
+
# ==== Import required modules
|
| 68 |
import logging
|
| 69 |
import re
|
| 70 |
|
| 71 |
import nltk
|
| 72 |
nltk.download('punkt')
|
| 73 |
+
from nltk.tokenize import word_tokenize, sent_tokenize
|
| 74 |
+
|
| 75 |
+
from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline
|
| 76 |
|
| 77 |
# disable INFO Logs
|
| 78 |
transformers_logger = logging.getLogger("transformers")
|
| 79 |
transformers_logger.setLevel(logging.WARNING)
|
| 80 |
|
| 81 |
+
def _extract_ner(sent: str, ner: pipeline) -> str:
|
| 82 |
+
grouped_ents = []
|
| 83 |
+
current_ent = {}
|
| 84 |
+
|
| 85 |
+
results = ner(sent)
|
| 86 |
+
for ent in results:
|
| 87 |
+
if len(current_ent) == 0:
|
| 88 |
+
current_ent = ent
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
if current_ent["end"] == ent["start"] and current_ent["entity_group"] == ent["entity_group"]:
|
| 92 |
+
current_ent["word"] = current_ent["word"]+ent["word"]
|
| 93 |
+
else:
|
| 94 |
+
grouped_ents.append(current_ent)
|
| 95 |
+
current_ent = ent
|
| 96 |
+
|
| 97 |
+
if len(grouped_ents) > 0 and grouped_ents[-1] != ent:
|
| 98 |
+
grouped_ents.append(current_ent)
|
| 99 |
+
elif len(grouped_ents) == 0 and len(current_ent) > 0:
|
| 100 |
+
grouped_ents.append(current_ent)
|
| 101 |
+
|
| 102 |
+
return [ g for g in grouped_ents if len(g["word"].strip()) ]
|
| 103 |
+
|
| 104 |
+
if USE_FARASAPY:
|
| 105 |
+
from farasa.segmenter import FarasaSegmenter
|
| 106 |
+
segmenter = FarasaSegmenter()
|
| 107 |
+
|
| 108 |
+
def _segment_text(text: str, segmenter: FarasaSegmenter) -> str:
|
| 109 |
+
segmented = segmenter.segment(text)
|
| 110 |
+
f_segments = { w.replace("+",""): w.replace("و+","و ").replace("+","") for w in segmented.split(" ") if w.strip() != "" and w.startswith("و+") }
|
| 111 |
+
for s,t in f_segments.items():
|
| 112 |
+
text = text.replace(s, t)
|
| 113 |
+
return text
|
| 114 |
+
|
| 115 |
+
_ = _segment_text("نص تجريبي للتأكد من عمل الأداة", segmenter)
|
| 116 |
+
|
| 117 |
custom_labels = ["O", "B-job", "I-job", "B-nationality", "B-person", "I-person", "B-location",
|
| 118 |
"B-time", "I-time", "B-event", "I-event", "B-organization", "I-organization",
|
| 119 |
"I-location", "I-nationality", "B-product", "I-product", "B-artwork", "I-artwork"]
|
| 120 |
|
| 121 |
+
# ==== Import/Download the NER Model
|
|
|
|
|
|
|
|
|
|
| 122 |
m_name = "marefa-nlp/marefa-ner"
|
| 123 |
tokenizer = AutoTokenizer.from_pretrained(m_name)
|
| 124 |
model = AutoModelForTokenClassification.from_pretrained(m_name)
|
| 125 |
|
| 126 |
ar_ner = pipeline("ner", model=model, tokenizer=tokenizer, grouped_entities=True, aggregation_strategy="simple")
|
| 127 |
|
| 128 |
+
# ==== Model Inference
|
| 129 |
samples = [
|
| 130 |
"تلقى تعليمه في الكتاب ثم انضم الى الأزهر عام 1873م. تعلم على يد السيد جمال الدين الأفغاني والشيخ محمد عبده",
|
| 131 |
"بعد عودته إلى القاهرة، التحق نجيب الريحاني فرقة جورج أبيض، الذي كان قد ضمَّ - قُبيل ذلك - فرقته إلى فرقة سلامة حجازي . و منها ذاع صيته",
|
|
|
|
| 133 |
"Government extends flight ban from India and Pakistan until June 21"
|
| 134 |
]
|
| 135 |
|
| 136 |
+
# [optional]
|
| 137 |
samples = [ " ".join(word_tokenize(sample.strip())) for sample in samples if sample.strip() != "" ]
|
| 138 |
|
| 139 |
for sample in samples:
|
| 140 |
+
ents = []
|
| 141 |
+
|
| 142 |
+
if USE_FARASAPY:
|
| 143 |
+
sample = _segment_text(sample, segmenter)
|
| 144 |
+
|
| 145 |
+
if USE_SENTENCE_TOKENIZER:
|
| 146 |
+
for sent in sent_tokenize(sample):
|
| 147 |
+
ents += _extract_ner(sent, ar_ner)
|
| 148 |
+
else:
|
| 149 |
+
ents = _extract_ner(sample, ar_ner)
|
| 150 |
+
|
| 151 |
+
# print the results
|
| 152 |
+
print("(", sample, ")")
|
| 153 |
+
for ent in ents:
|
| 154 |
+
print("\t", ent["word"], "=>", ent["entity_group"])
|
| 155 |
print("=========\n")
|
| 156 |
+
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
Output
|
| 160 |
+
|
| 161 |
+
```
|
| 162 |
+
( تلقى تعليمه في الكتاب ثم انضم الى الأزهر عام 1873م . تعلم على يد السيد جمال الدين الأفغاني والشيخ محمد عبده )
|
| 163 |
+
الأزهر => organization
|
| 164 |
+
عام 1873م => time
|
| 165 |
+
جمال الدين الأفغاني => person
|
| 166 |
+
محمد عبده => person
|
| 167 |
+
=========
|
| 168 |
+
|
| 169 |
+
( بعد عودته إلى القاهرة، التحق نجيب الريحاني فرقة جورج أبيض، الذي كان قد ضمَّ - قُبيل ذلك - فرقته إلى فرقة سلامة حجازي . و منها ذاع صيته )
|
| 170 |
+
القاهرة => location
|
| 171 |
+
نجيب الريحاني => person
|
| 172 |
+
فرقة جورج أبيض => organization
|
| 173 |
+
فرقة سلامة حجازي => organization
|
| 174 |
+
=========
|
| 175 |
+
|
| 176 |
+
( امبارح اتفرجت على مباراة مانشستر يونايتد مع ريال مدريد في غياب الدون كرستيانو رونالدو )
|
| 177 |
+
مانشستر يونايتد => organization
|
| 178 |
+
ريال مدريد => organization
|
| 179 |
+
كرستيانو رونالدو => person
|
| 180 |
+
=========
|
| 181 |
+
|
| 182 |
+
( Government extends flight ban from India and Pakistan until June 21 )
|
| 183 |
+
India => location
|
| 184 |
+
Pakistan => location
|
| 185 |
+
June 21 => time
|
| 186 |
+
=========
|
| 187 |
```
|
| 188 |
|
| 189 |
## Fine-Tuning
|