Commit ·
004ae91
1
Parent(s): ffa5c9b
Create create_dataset.py
Browse filesFile to convert the dataset into JSON format so that it can be easily loaded in the Huggingface dataset.
- create_dataset.py +162 -0
create_dataset.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import glob
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
from io import StringIO
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
Steps to convert the data into JSON format.
|
| 10 |
+
|
| 11 |
+
Step-0: Use a python environment where pandas is installed.
|
| 12 |
+
Step-1: Download the source file from here: https://figshare.com/articles/dataset/MACCROBAT2018/9764942
|
| 13 |
+
Step-2: Unzip the file in put that into a folder (say `data` folder).
|
| 14 |
+
All unzipped files will be present here.
|
| 15 |
+
* data/MACCROBAT2020/*.txt
|
| 16 |
+
* data/MACCROBAT2020/*.ann
|
| 17 |
+
Step-3: Use the correct paths and run this file.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def remove_overlapped_ner_tags(ner_details: list[dict]):
|
| 21 |
+
"""remove overlapping entities.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
ner_details (List[dict]): a list of dictionary where each dictionary holds
|
| 25 |
+
the information of a entity.
|
| 26 |
+
|
| 27 |
+
NOTE: Priority is given to the entity that is labelled first after sorting all by start index in ascending order.
|
| 28 |
+
(i.e. it's end-index is less than other start of other overlapping entity.)
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
list[dict]: updated list (removed item if something was overlapping)
|
| 32 |
+
"""
|
| 33 |
+
# funtion to remove the overlapping NER-tags
|
| 34 |
+
new_ner_details = []
|
| 35 |
+
|
| 36 |
+
ner_details = sorted(ner_details, key=lambda x: x["start"])
|
| 37 |
+
for i, ner_detail in enumerate(ner_details):
|
| 38 |
+
if i == 0:
|
| 39 |
+
start = ner_detail["start"]
|
| 40 |
+
end = ner_detail["end"]
|
| 41 |
+
new_ner_details.append(ner_detail)
|
| 42 |
+
continue
|
| 43 |
+
|
| 44 |
+
current_start = ner_detail["start"]
|
| 45 |
+
current_end = ner_detail["end"]
|
| 46 |
+
if current_start < end:
|
| 47 |
+
continue
|
| 48 |
+
|
| 49 |
+
# update the start and end
|
| 50 |
+
start = current_start
|
| 51 |
+
end = current_end
|
| 52 |
+
|
| 53 |
+
new_ner_details.append(ner_detail)
|
| 54 |
+
return new_ner_details
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_ner_details(ann_file):
|
| 58 |
+
with open(ann_file, "r") as f:
|
| 59 |
+
lines = f.readlines()
|
| 60 |
+
lines = [line.strip() for line in lines]
|
| 61 |
+
csv_data = "\n".join(lines)
|
| 62 |
+
csv_data = StringIO(csv_data)
|
| 63 |
+
df = pd.read_csv(csv_data, sep="\t", header=None)
|
| 64 |
+
|
| 65 |
+
df.columns = ["EntityID", "EntityDetails", "EntityText"]
|
| 66 |
+
# print(df.shape)
|
| 67 |
+
|
| 68 |
+
# remove rows where entity-id start other than `T`
|
| 69 |
+
df = df[df["EntityID"].apply(lambda x: str(x).strip().startswith("T"))]
|
| 70 |
+
|
| 71 |
+
# remove the rows which contains the ";" in the `EntityDetails`
|
| 72 |
+
df = df[df["EntityDetails"].apply(lambda x: ";" not in str(x))]
|
| 73 |
+
|
| 74 |
+
# drop where None is present
|
| 75 |
+
df.dropna(axis=1, inplace=True)
|
| 76 |
+
|
| 77 |
+
ner_info = []
|
| 78 |
+
for i, row in df.iterrows():
|
| 79 |
+
text = row["EntityText"]
|
| 80 |
+
details = row["EntityDetails"]
|
| 81 |
+
try:
|
| 82 |
+
ner_tag, start, end = details.split(" ")
|
| 83 |
+
except:
|
| 84 |
+
print(ann_file)
|
| 85 |
+
print(details)
|
| 86 |
+
start = int(float(start))
|
| 87 |
+
end = int(float(end))
|
| 88 |
+
|
| 89 |
+
ner_info.append({"text": text, "label": ner_tag.upper(), "start": start, "end": end})
|
| 90 |
+
|
| 91 |
+
# remove the overlapping entities
|
| 92 |
+
ner_info = remove_overlapped_ner_tags(ner_details=ner_info)
|
| 93 |
+
# print(ner_info)
|
| 94 |
+
|
| 95 |
+
return ner_info
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main(input_path: str = "data/MACCROBAT2020", output_path: str = "data/MACCROBAT2020-V2.json"):
|
| 99 |
+
txt_files = glob.glob(os.path.join(input_path, "*.txt"))
|
| 100 |
+
txt_files.sort()
|
| 101 |
+
|
| 102 |
+
ner_data = {"data": [], "verson": "MACCROBAT-V2 (https://figshare.com/articles/dataset/MACCROBAT2018/9764942)"}
|
| 103 |
+
|
| 104 |
+
for txt_file in tqdm(txt_files, desc="Extracting data..."):
|
| 105 |
+
with open(txt_file, "r") as f:
|
| 106 |
+
full_text = f.read()
|
| 107 |
+
a = txt_file.replace(".txt", ".ann")
|
| 108 |
+
ner_info = get_ner_details(a)
|
| 109 |
+
data = {"full_text": full_text, "ner_info": ner_info}
|
| 110 |
+
ner_data["data"].append(data)
|
| 111 |
+
|
| 112 |
+
ALL_NER_LABLES = set()
|
| 113 |
+
for details in tqdm(ner_data["data"], desc="Splitting into tokens..."):
|
| 114 |
+
text = details["full_text"]
|
| 115 |
+
ner_details = details["ner_info"]
|
| 116 |
+
|
| 117 |
+
tokens = []
|
| 118 |
+
ner_labels = []
|
| 119 |
+
start = 0
|
| 120 |
+
for ner_detail in ner_details:
|
| 121 |
+
ner_start = ner_detail["start"]
|
| 122 |
+
ner_end = ner_detail["end"]
|
| 123 |
+
|
| 124 |
+
before_ner_token = text[start:ner_start]
|
| 125 |
+
ner_token = text[ner_start:ner_end]
|
| 126 |
+
|
| 127 |
+
tokens.append(before_ner_token)
|
| 128 |
+
ner_labels.append("O")
|
| 129 |
+
tokens.append(ner_token)
|
| 130 |
+
ner_labels.append(f'B-{ner_detail["label"]}')
|
| 131 |
+
ALL_NER_LABLES.add(f'B-{ner_detail["label"]}')
|
| 132 |
+
ALL_NER_LABLES.add(f'I-{ner_detail["label"]}')
|
| 133 |
+
start = ner_end
|
| 134 |
+
if len(text) >= start:
|
| 135 |
+
ner_labels.append("O")
|
| 136 |
+
tokens.append(text[start:])
|
| 137 |
+
assert len(tokens) == len(ner_labels)
|
| 138 |
+
|
| 139 |
+
details["tokens"] = tokens
|
| 140 |
+
details["ner_labels"] = ner_labels
|
| 141 |
+
|
| 142 |
+
ner_data["all_ner_labels"] = sorted(list(ALL_NER_LABLES), key=lambda x: x.split("-")[-1])
|
| 143 |
+
|
| 144 |
+
label_2_index = {k: i for i, k in enumerate(ner_data["all_ner_labels"])}
|
| 145 |
+
index_2_label = {v: k for k, v in label_2_index.items()}
|
| 146 |
+
ner_data["label_2_index"] = label_2_index
|
| 147 |
+
ner_data["index_2_label"] = index_2_label
|
| 148 |
+
|
| 149 |
+
for details in tqdm(ner_data["data"], desc="label2index..."):
|
| 150 |
+
ner_labels = details["ner_labels"]
|
| 151 |
+
ner_labels_ids = []
|
| 152 |
+
for ner in ner_labels:
|
| 153 |
+
ner_labels_ids.append(label_2_index.get(ner))
|
| 154 |
+
details["ner_labels"] = ner_labels_ids
|
| 155 |
+
with open(output_path, "w") as f:
|
| 156 |
+
json.dump(ner_data, f, indent=4)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
input_path: str = "data/MACCROBAT2020"
|
| 161 |
+
output_path: str = "data/MACCROBAT2020-V2.json"
|
| 162 |
+
main(input_path=input_path, output_path=output_path)
|