{ "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 }