Skip to content

Instantly share code, notes, and snippets.

@alexeyev
Last active July 21, 2023 14:20
Show Gist options
  • Save alexeyev/e19b016699890bdbf731dedd4be07d2e to your computer and use it in GitHub Desktop.
Save alexeyev/e19b016699890bdbf731dedd4be07d2e to your computer and use it in GitHub Desktop.
Converting Doccano NER task export (JSONL file) to a CONLL03-formatted file
# coding: utf-8
import re
from builtins import frozenset
from typing import List, Tuple, Set
def find_occurrences(s, c):
return [i for i, letter in enumerate(s) if letter == c]
def annotation2sequences(original_text: str, label_spans: List[List], excluded_labels: Set = frozenset([]),
already_tokenized: bool = True, tokenize_fn=None):
original_text = original_text.rstrip()
# building tokens' spans
if already_tokenized:
token_spans = [[0]]
for m in re.finditer(" +", original_text):
token_spans[-1].append(m.start())
token_spans.append([m.end()])
token_spans[-1].append(len(original_text))
else:
token_spans = tokenize_fn(original_text)
# splitting into sentences
newlines_positions = find_occurrences(original_text, "\n") + [len(original_text)]
sentence_boundaries = [0]
for token_number, (l, r) in enumerate(token_spans):
if r == newlines_positions[0]:
sentence_boundaries.append(token_number + 1)
newlines_positions = newlines_positions[1:]
elif r > newlines_positions[0]:
raise Exception
# print(sentence_boundaries)
tokens = [original_text[fr: to] for fr, to in token_spans]
labels = ["O"] * len(token_spans)
curr_token_idx = 0
# everything that intersects -- gets tagged as the corresponding label
for span in label_spans:
prefix = "B-"
label_from, label_to, tag = span
while token_spans[curr_token_idx][1] <= label_from:
curr_token_idx += 1
while token_spans[curr_token_idx][0] < label_to:
if not tag in excluded_labels:
labels[curr_token_idx] = prefix + tag
prefix = "I-"
curr_token_idx += 1
assert len(tokens) == len(labels)
results = []
for i in range(len(sentence_boundaries) - 1):
results.append((i + 1, list(zip(
tokens[sentence_boundaries[i]:sentence_boundaries[i + 1]],
labels[sentence_boundaries[i]:sentence_boundaries[i + 1]]))))
return results
def seq2conll2003(list_of_lists_of_pairs: List[List[Tuple[str, str]]]):
result = ""
sentence_number = 1
for docid, sentences in list_of_lists_of_pairs:
for sentid, pairs in sentences:
result += f"# {sentence_number} {docid} {sentid}\n"
result += "\n".join([f"{t}\t-\t-\t{l}" for t, l in pairs])
result += "\n\n"
sentence_number += 1
return result.strip()
if __name__ == "__main__":
import json
from apertium_tokenizer import ApertiumSimpleTokenizer
tokenizer = ApertiumSimpleTokenizer()
custom_tokenize = lambda sentence: list(tokenizer.span_tokenize(sentence))
all_results_with_custom_tokenization = []
for line_idx, line in enumerate(open("Anton.jsonl", "r+", encoding="utf-8"), 1):
if line_idx > 3:
break
ann_data = json.loads(line.strip())
idx, orig_text, label_spans = ann_data["id"], ann_data["text"], ann_data["label"]
annotated_enumerated_sentences = annotation2sequences(orig_text, label_spans,
already_tokenized=False,
excluded_labels={"PERIOD", "MEASURE",
"IDENTIFIER", "ACRONYM"},
tokenize_fn=custom_tokenize)
all_results_with_custom_tokenization.append((line_idx, annotated_enumerated_sentences))
with open("sample.conll2003-formatted.txt", "w+", encoding="utf-8") as wf:
wf.write(seq2conll2003(all_results_with_custom_tokenization))
MIT License
Copyright (c) 2023 Anton Alekseev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment