File size: 8,737 Bytes
38ca16f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80b213e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install termcolor==1.1.0 transformers==4.18.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73f81039",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "from termcolor import colored\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44668ca1",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Ner_Extractor:\n",
    "    \"\"\"\n",
    "    Labeling each token in sentence as named entity\n",
    "\n",
    "    :param model_checkpoint: name or path to model \n",
    "    :type model_checkpoint: string\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, model_checkpoint: str):\n",
    "        self.token_pred_pipeline = pipeline(\"token-classification\", \n",
    "                                            model=model_checkpoint, \n",
    "                                            aggregation_strategy=\"average\")\n",
    "    \n",
    "    @staticmethod\n",
    "    def text_color(txt, txt_c=\"blue\", txt_hglt=\"on_yellow\"):\n",
    "        \"\"\"\n",
    "        Coloring part of text \n",
    "        \n",
    "        :param txt: part of text from sentence \n",
    "        :type txt: string\n",
    "        :param txt_c: text color  \n",
    "        :type txt_c: string        \n",
    "        :param txt_hglt: color of text highlighting  \n",
    "        :type txt_hglt: string\n",
    "        :return: string with color labeling\n",
    "        :rtype: string\n",
    "        \"\"\"\n",
    "        return colored(txt, txt_c, txt_hglt)\n",
    "    \n",
    "    @staticmethod\n",
    "    def concat_entities(ner_result):\n",
    "        \"\"\"\n",
    "        Concatenation entities from model output on grouped entities\n",
    "        \n",
    "        :param ner_result: output from model pipeline \n",
    "        :type ner_result: list\n",
    "        :return: list of grouped entities with start - end position in text\n",
    "        :rtype: list\n",
    "        \"\"\"\n",
    "        entities = []\n",
    "        prev_entity = None\n",
    "        prev_end = 0\n",
    "        for i in range(len(ner_result)):\n",
    "            \n",
    "            if (ner_result[i][\"entity_group\"] == prev_entity) &\\\n",
    "               (ner_result[i][\"start\"] == prev_end):\n",
    "                \n",
    "                entities[i-1][2] = ner_result[i][\"end\"]\n",
    "                prev_entity = ner_result[i][\"entity_group\"]\n",
    "                prev_end = ner_result[i][\"end\"]\n",
    "            else:\n",
    "                entities.append([ner_result[i][\"entity_group\"], \n",
    "                                 ner_result[i][\"start\"], \n",
    "                                 ner_result[i][\"end\"]])\n",
    "                prev_entity = ner_result[i][\"entity_group\"]\n",
    "                prev_end = ner_result[i][\"end\"]\n",
    "        \n",
    "        return entities\n",
    "    \n",
    "    \n",
    "    def colored_text(self, text: str, entities: list):\n",
    "        \"\"\"\n",
    "        Highlighting in the text named entities\n",
    "        \n",
    "        :param text: sentence or a part of corpus\n",
    "        :type text: string\n",
    "        :param entities: concated entities on groups with start - end position in text\n",
    "        :type entities: list\n",
    "        :return: Highlighted sentence\n",
    "        :rtype: string\n",
    "        \"\"\"\n",
    "        colored_text = \"\"\n",
    "        init_pos = 0\n",
    "        for ent in entities:\n",
    "            if ent[1] > init_pos:\n",
    "                colored_text += text[init_pos: ent[1]]\n",
    "                colored_text += self.text_color(text[ent[1]: ent[2]]) + f\"({ent[0]})\"\n",
    "                init_pos = ent[2]\n",
    "            else:\n",
    "                colored_text += self.text_color(text[ent[1]: ent[2]]) + f\"({ent[0]})\"\n",
    "                init_pos = ent[2]\n",
    "        \n",
    "        return colored_text\n",
    "    \n",
    "    \n",
    "    def get_entities(self, text: str):\n",
    "        \"\"\"\n",
    "        Extracting entities from text with them position in text\n",
    "        \n",
    "        :param text: input sentence for preparing\n",
    "        :type text: string\n",
    "        :return: list with entities from text\n",
    "        :rtype: list\n",
    "        \"\"\"\n",
    "        assert len(text) > 0, text\n",
    "        entities = self.token_pred_pipeline(text)\n",
    "        concat_ent = self.concat_entities(entities)\n",
    "        \n",
    "        return concat_ent\n",
    "    \n",
    "    \n",
    "    def show_ents_on_text(self, text: str):\n",
    "        \"\"\"\n",
    "        Highlighting named entities in input text \n",
    "        \n",
    "        :param text: input sentence for preparing\n",
    "        :type text: string\n",
    "        :return: Highlighting text\n",
    "        :rtype: string\n",
    "        \"\"\"\n",
    "        assert len(text) > 0, text\n",
    "        entities = self.get_entities(text)\n",
    "        \n",
    "        return self.colored_text(text, entities)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aaa0a5bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "seqs_example = [\"Из Дзюбы вышел бы отличный бразилец». Интервью Клаудиньо\",\n",
    "                \"Самый яркий бразилец «Зенита» рассказал о встрече с Пеле\",\n",
    "                \"Стали известны подробности нового иска РФС к УЕФА и ФИФА\",\n",
    "                \"Реванш «Баварии», голы от «Реала» с «Челси»: ставим на ЛЧ\",\n",
    "                \"Кварацхелия не вернется в «Рубин» и станет игроком «Наполи»\",\n",
    "                \"«Манчестер Сити» сделал грандиозное предложение по Холанду\",\n",
    "                \"В России хотят возродить Кубок лиги. Он проводился в 2003 году\",\n",
    "                \"Экс-игрок «Реала» находится в критическом состоянии после ДТП\",\n",
    "                \"Аршавин посмеялся над показателями Глушакова в игре с ЦСКА\",\n",
    "                \"Арьен Роббен пробежал 42-километровый марафон\"\n",
    "               ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "380d9824",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "## init model for inference\n",
    "extractor = Ner_Extractor(model_checkpoint = \"surdan/LaBSE_ner_nerel\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37ebcf51",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "## get highlighting sentences\n",
    "show_entities_in_text = (extractor.show_ents_on_text(i) for i in seqs_example)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e03b28c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "## get list of entities from sentence\n",
    "l_entities = [extractor.get_entities(i) for i in seqs_example]\n",
    "len(l_entities), len(seqs_example)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2d4ae84",
   "metadata": {},
   "outputs": [],
   "source": [
    "## print highlighting sentences\n",
    "for i in range(len(seqs_example)):\n",
    "    print(next(show_entities_in_text, \"End of generator\"))\n",
    "    print(\"-*-\"*25)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ce3e083",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}