Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ner): build entities from tags #1327

Merged
merged 2 commits into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 19 additions & 3 deletions src/rubrix/client/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,18 +329,34 @@ def __init__(
def __tags2entities__(self, tags: List[str]) -> List[Tuple[str, int, int]]:
idx = 0
entities = []
entity_starts = False
while idx < len(tags):
tag = tags[idx]
if tag == "O":
entity_starts = False
if tag != "O":
prefix, entity = tag.split("-")
if prefix == "B":
if prefix in ["B", "U"]:
if prefix == "B":
entity_starts = True
char_start, char_end = self.token_span(token_idx=idx)
entities.append(
{"entity": entity, "start": char_start, "end": char_end}
{"entity": entity, "start": char_start, "end": char_end + 1}
)
elif prefix in ["I", "L"]:
if not entity_starts:
_LOGGER.warning(
"Detected non-starting tag and first entity token was not found."
f"Assuming {tag} as first entity token"
)
entity_starts = True
char_start, char_end = self.token_span(token_idx=idx)
entities.append(
{"entity": entity, "start": char_start, "end": char_end + 1}
)

_, char_end = self.token_span(token_idx=idx)
entities[-1]["end"] = char_end
entities[-1]["end"] = char_end + 1
idx += 1
return [(value["entity"], value["start"], value["end"]) for value in entities]

Expand Down
9 changes: 5 additions & 4 deletions tests/client/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,11 @@ def test_token_classification_record(annotation, status, expected_status, expect
@pytest.mark.parametrize(
("tokens", "tags", "annotation"),
[
(["Una", "casa"], ["O", "B-OBJ"], [("OBJ", 4, 7)]),
(["Matias", "Aguado"], ["B-PER", "I-PER"], [("PER", 0, 12)]),
(["Todo", "Todo", "Todo"], ["B-T", "I-T", "L-T"], [("T", 0, 13)]),
(["Una", "casa"], ["O", "U-OBJ"], []),
(["Una", "casa"], ["O", "B-OBJ"], [("OBJ", 4, 8)]),
(["Matias", "Aguado"], ["B-PER", "I-PER"], [("PER", 0, 13)]),
(["Todo", "Todo", "Todo"], ["B-T", "I-T", "L-T"], [("T", 0, 14)]),
(["Una", "casa"], ["O", "U-OBJ"], [("OBJ", 4, 8)]),
(["Todo", "Todo", "Todo"], ["I-T", "I-T", "O"], [("T", 0, 9)]),
],
)
def test_token_classification_with_tokens_and_tags(tokens, tags, annotation):
Expand Down