File size: 6,846 Bytes
b93bebe |
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 |
{
"cells": [
{
"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": "b8a8891e",
"metadata": {},
"outputs": [],
"source": [
"# !pip install termcolor==1.1.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "44668ca1",
"metadata": {},
"outputs": [],
"source": [
"class Ner_Extractor:\n",
" \n",
" def __init__(self, model_checkpoint):\n",
" \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",
" return colored(txt, txt_c, txt_hglt)\n",
" \n",
" @staticmethod\n",
" def concat_entities(ner_result):\n",
" \n",
" entities = []\n",
" prev_entity = None\n",
" prev_end = 0\n",
" for i in range(len(ner_result)):\n",
" if (ner_result[i][\"entity_group\"] == prev_entity) &\\\n",
" (ner_result[i][\"start\"] == prev_end):\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, entities):\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",
" 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",
" 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",
"\"Аршавин посмеялся над показателями Глушакова в игре с ЦСКА\",\n",
"\"Арьен Роббен пробежал 42-километровый марафон\",\n",
"\"Бывший игрок «Спартака» предложил бить футболистов палками\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "380d9824",
"metadata": {},
"outputs": [],
"source": [
"%%time\n",
"extractor = Ner_Extractor(model_checkpoint = \"surdan/LaBSE_ner_nerel\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "37ebcf51",
"metadata": {},
"outputs": [],
"source": [
"%%time\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",
"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": [
"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": "47fbcff9",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "41c32b90",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "07bb735e",
"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
}
|