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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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fc75ebf",
   "metadata": {},
   "outputs": [],
   "source": [
    "## datasets==2.0.0 pandas==1.4.2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9cc126c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import re\n",
    "from tqdm import tqdm\n",
    "from datasets import Dataset, DatasetDict\n",
    "import pickle\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2adeaf52",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_list_values(text):\n",
    "    return text.split()\n",
    "\n",
    "def replc_t_n(text):\n",
    "    return re.sub(\"\\t|\\n\", \" \", text).strip()\n",
    "\n",
    "def read_file(filepath, readlines=False):\n",
    "    with open(filepath, \"r\") as f:\n",
    "        if readlines:\n",
    "            txt = f.readlines()\n",
    "        else:\n",
    "            txt = f.read()\n",
    "    return txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26a51547",
   "metadata": {},
   "outputs": [],
   "source": [
    "def split_text_on_labeled_tokens(text, labels):\n",
    "    \"\"\"\n",
    "    Split text on labeled token\n",
    "\n",
    "    :param text: input text\n",
    "    :type text: string\n",
    "    :param labels: token labels with position in text \n",
    "    :type labels: list\n",
    "    :return: list of splited text on tokens, list of entity label for each token\n",
    "    :rtype: list, list\n",
    "    \"\"\"\n",
    "    ### inner function\n",
    "    def chunk_text_labeling(text, start, end, is_ner = False):\n",
    "        \"\"\"\n",
    "        Labeling part of text by text position\n",
    "\n",
    "        :param text: input text\n",
    "        :type text: string\n",
    "        :param start: start position of entity in text \n",
    "        :type start: int\n",
    "        :param end: end position of entity in text \n",
    "        :type end: int\n",
    "        :param is_ner: part of text is named entity or not \n",
    "        :type is_ner: bool\n",
    "        \"\"\"\n",
    "        chunk_iter = 0\n",
    "        ner_chunk = text[start: end].split()\n",
    "        for part_of_chunk in ner_chunk:\n",
    "            split_text.append(part_of_chunk)\n",
    "            if is_ner:\n",
    "                if chunk_iter == 0:\n",
    "                    ner_label.append(\"B-\"+ner)\n",
    "                else:\n",
    "                    ner_label.append(\"I-\"+ner)\n",
    "                chunk_iter += 1\n",
    "            else:\n",
    "                ner_label.append(\"O\") \n",
    "    ### inner function\n",
    "                \n",
    "    init_start = 0\n",
    "    split_text = []\n",
    "    ner_label = []\n",
    "    for ner, start, end in labels:\n",
    "\n",
    "        if start > init_start:\n",
    "\n",
    "            chunk_text_labeling(text, init_start, start)        \n",
    "            chunk_text_labeling(text, start, end, True)\n",
    "            init_start = end\n",
    "        else:\n",
    "            chunk_text_labeling(text, start, end, True)\n",
    "            init_start = end\n",
    "    \n",
    "    return split_text, ner_label"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ba5da7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def grouped_and_sort_labeled_data(annotation_file):\n",
    "    \"\"\"\n",
    "    Get list of entities with corresponding position in text\n",
    "\n",
    "    :param annotation_file: List of entities\n",
    "    :type annotation_file: list\n",
    "    :return: list entitiens sorted by start position in text\n",
    "    :rtype: list\n",
    "    \"\"\"\n",
    "    df_ann = pd.DataFrame([get_list_values(replc_t_n(i)) for i in annotation_file if \";\" not in i]) \n",
    "    df_ann[2] = df_ann[2].astype(\"int\")\n",
    "    df_ann[3] = df_ann[3].astype(\"int\")\n",
    "    grouped = df_ann.groupby([1, 2])[3].min().reset_index()\n",
    "    \n",
    "    return grouped.sort_values(by=2)[[1,2,3]].values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46fdb74b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def check_isalnum(text):\n",
    "    return any(i.isalnum() for i in text)\n",
    "\n",
    "def keep_only_alnum(text):\n",
    "    return \"\".join([i if i.isalnum() else \" \" for i in text]).strip()\n",
    "\n",
    "def drop_punct(seq, labels):\n",
    "    \"\"\"\n",
    "    Drop punctuation from labeled data\n",
    "\n",
    "    :param seq: List of tokens\n",
    "    :type seq: list\n",
    "    :param labels: List of entities\n",
    "    :type labels: list\n",
    "    \"\"\"\n",
    "    new_seq = []\n",
    "    new_labels = []\n",
    "    for i in range(len(seq)):\n",
    "        if seq[i].isalnum():\n",
    "            new_seq.append(seq[i])\n",
    "            new_labels.append(labels[i])   \n",
    "    return new_seq, new_labels\n",
    "\n",
    "def drop_duplicate_tokens(seq, labels):\n",
    "    new_seq = []\n",
    "    new_labels = []\n",
    "    for i in range(len(seq)):\n",
    "        if (i != 0) & (seq[i-1] == seq[i]):\n",
    "            continue\n",
    "        else:\n",
    "            new_seq.append(seq[i])\n",
    "            new_labels.append(labels[i])\n",
    "    return new_seq, new_labels\n",
    "\n",
    "def prepare_sequences(seqs, labels):\n",
    "    clear_tokens = [keep_only_alnum(i) if check_isalnum(i) else i for i in seqs]\n",
    "    d_p_tokens, d_p_labels = drop_punct(clear_tokens, labels)\n",
    "    return drop_duplicate_tokens(d_p_tokens, d_p_labels)\n",
    "    \n",
    "\n",
    "def map_label_to_id(ids_dict, labels):\n",
    "    \"\"\"\n",
    "    Convert string label to corresponding id\n",
    "\n",
    "    :param ids_dict: {\"age\": 0, \"event\": 1.....}\n",
    "    :type ids_dict: dict\n",
    "    :param labels: List of entities [\"age\", \"event\", \"O\"....]\n",
    "    :type labels: list\n",
    "    \"\"\"\n",
    "    return [ids_dict[i] for i in labels]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b735210",
   "metadata": {},
   "source": [
    "### Preparing files in folders"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23ad44bb",
   "metadata": {},
   "source": [
    "#### The data have been taken from https://github.com/dialogue-evaluation/RuNNE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c2748fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "folders = [\"train\", \"test\", \"dev\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab65dc18",
   "metadata": {},
   "outputs": [],
   "source": [
    "for folder in folders:\n",
    "    base_path = f\"RuNNE/data/{folder}\"\n",
    "    temp_folder = os.listdir(base_path)\n",
    "    \n",
    "    ## getting list filenames of annotation\n",
    "    files_with_ann = [i for i in temp_folder if \".ann\" in i]\n",
    "\n",
    "    all_sequences = []\n",
    "    all_labels = []\n",
    "    \n",
    "    for f_ann in tqdm(files_with_ann):\n",
    "        \n",
    "        ## getting filename for text by replaced of extension\n",
    "        txt_file = f_ann.replace(\".ann\", \".txt\")\n",
    "\n",
    "        ann = read_file(base_path +\"/\"+ f_ann, readlines=True)\n",
    "        txt = read_file(base_path +\"/\"+ txt_file)\n",
    "        \n",
    "        ## check len, because in dev folder there are empty files\n",
    "        if len(ann) == 0:\n",
    "            continue\n",
    "        labels = grouped_and_sort_labeled_data(ann)\n",
    "        \n",
    "        ## splitting text on tokens and labeling each of them\n",
    "        split_text, ner_label = split_text_on_labeled_tokens(txt, labels)\n",
    "        seq_split_indexes = [i for i, v in enumerate(split_text) if v == \".\"]\n",
    "        \n",
    "        ## adding prepared data from each file to general list\n",
    "        prev = 0\n",
    "        for i in seq_split_indexes:\n",
    "            \n",
    "            short_text = split_text[prev: i]\n",
    "            short_label = ner_label[prev: i]\n",
    "            \n",
    "            clear_tokens, clear_label = prepare_sequences(short_text, short_label)\n",
    "            \n",
    "            all_sequences.append(clear_tokens)\n",
    "            all_labels.append(clear_label)\n",
    "            ## we don't take into account the dots in text  \n",
    "            prev = i+1\n",
    "    \n",
    "    ## save data to file for each part of splitted dataset\n",
    "    df_folder = pd.DataFrame({\"sequences\": all_sequences, \"labels\": all_labels})\n",
    "    with open(f'{folder}_data.pickle', 'wb') as f:\n",
    "        pickle.dump(df_folder, f)\n",
    "    print(f\"For folder <{folder}> prepared <{df_folder.shape[0]}> sequences\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc61030b",
   "metadata": {},
   "source": [
    "### Creating DatasetDict fro prepared data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c24ab41",
   "metadata": {},
   "outputs": [],
   "source": [
    "## load 3 dataframe and init them into transformer dataset\n",
    "dsd = DatasetDict()\n",
    "for folder in folders:\n",
    "    with open(f'{folder}_data.pickle', 'rb') as f:\n",
    "        data = pickle.load(f)\n",
    "    dsd[folder] = Dataset.from_pandas(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04e76e90",
   "metadata": {},
   "source": [
    "### Creating dictionary for labels ids "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce021634",
   "metadata": {},
   "outputs": [],
   "source": [
    "## get unique entyties\n",
    "for_df = []\n",
    "for folder in folders:\n",
    "    with open(f'{folder}_data.pickle', 'rb') as f:\n",
    "        for_df.append(pickle.load(f))\n",
    "lbls = pd.concat(for_df)[\"labels\"].values\n",
    "\n",
    "dd = dict()\n",
    "ids = 0\n",
    "for ll in lbls:\n",
    "    for lbl in ll:\n",
    "        if lbl not in dd:\n",
    "            dd[lbl] = ids\n",
    "            ids += 1\n",
    "\n",
    "            \n",
    "# # count each entity\n",
    "# countss = dict()\n",
    "# for ll in lbls:\n",
    "#     for lbl in ll:\n",
    "#         if lbl not in countss:\n",
    "#             countss[lbl] = 1\n",
    "#         else:\n",
    "#             countss[lbl] += 1\n",
    "\n",
    "# del countss[\"O\"]\n",
    "# sorted_counts = {k: v for k, v in sorted(countss.items(), key=lambda item: item[0].split(\"-\")[1])}\n",
    "\n",
    "# for k, v in sorted_counts.items():\n",
    "#     print(\"- \"+k+f\": {v}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58000df7",
   "metadata": {},
   "outputs": [],
   "source": [
    "## sort mapper\n",
    "\n",
    "ll = [i for i in dd.keys() if i != \"O\"]            \n",
    "ll_sort = (sorted(ll, key=lambda x: x.split(\"-\")[1]))\n",
    "new_dd = {k: v for v, k in enumerate([\"O\"] + ll_sort)}\n",
    "            \n",
    "            \n",
    "reverse_dd = {v: k for k, v in new_dd.items()}\n",
    "with open('id_to_label_map.pickle', 'wb') as f:\n",
    "        pickle.dump(reverse_dd, f)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b30a7098",
   "metadata": {},
   "source": [
    "### Creating new column with numerical labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51fd6b38",
   "metadata": {},
   "outputs": [],
   "source": [
    "dsd_with_ids = dsd.map(\n",
    "    lambda x: {\"ids\": [map_label_to_id(new_dd, i) for i in x[\"labels\"]]}, batched=True, remove_columns = \"labels\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7ecf94f",
   "metadata": {},
   "outputs": [],
   "source": [
    "dsd_with_ids.push_to_hub(\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5eb5f3fa",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "hf_env",
   "language": "python",
   "name": "hf_env"
  },
  "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
}