sentencer_utils.py 2.79 KB
from transformers import AutoTokenizer, AutoModelForTokenClassification

import torch
import numpy as np

class Sentencer(object):

    def __init__(self, pretrained_path : str):
        self.tokenizer = AutoTokenizer.from_pretrained('allegro/herbert-base-cased')
        self.sentencer = AutoModelForTokenClassification.from_pretrained(pretrained_path, device_map='auto', num_labels=2)

    def do_segmentation(self, texts : str | list[str], batch_size : int = 8) -> list[list[str]]:
        if type(texts) == str:
            texts = [texts]
        texts = [self.tokenizer._tokenizer.normalizer.normalize_str(t).strip() for t in texts] # type: ignore[union-attr]
        tokenised = self.tokenizer(
            texts,
            return_offsets_mapping=True,
            padding=True,
            truncation=True,
            return_overflowing_tokens=True,
            max_length=512,
            return_tensors='pt',
        )
        offsets_mapping = tokenised.pop('offset_mapping')
        overflow_mapping = tokenised.pop('overflow_to_sample_mapping')
        
        device = self.sentencer.device
        num_samples = tokenised['input_ids'].shape[0]
        logits_list = []
        with torch.no_grad():
            for i in range(0, num_samples, batch_size):
                batch = {k: v[i:(i + batch_size)].to(device) for k, v in tokenised.items()}
                logits = self.sentencer(**batch).logits.detach().cpu()
                logits_list.append(logits)
        predicted = torch.argmax(torch.cat(logits_list, dim=0), dim=-1)
        
        labeled_paragraphs : list[list[tuple[str, bool, int]]] = []
        for idx, prediction, token_offsets, sample_no in zip(tokenised['input_ids'], predicted, offsets_mapping, overflow_mapping):
            text = texts[sample_no]
            if len(labeled_paragraphs) < sample_no + 1:
                labeled_paragraphs.append([])
            for token, is_eos, (i, j) in zip(self.tokenizer.convert_ids_to_tokens(idx), prediction, token_offsets):
                if token in ('<s>', '</s>', '<pad>'):
                    continue    
                token = text[i:j]#token.replace('</w>', '')
                labeled_paragraphs[-1].append((token, is_eos, i))
        paragraphs : list[list[str]] = []
        sentence = ''
        for labeled_paragraph in labeled_paragraphs:
            paragraphs.append([])
            for token, is_eos, i in labeled_paragraph:
                while len(sentence) < i:
                    sentence += ' '
                sentence += token
                if is_eos:
                    if sentence.strip():
                        paragraphs[-1].append(sentence.strip())
                    sentence = ''
            if sentence.strip():
                paragraphs[-1].append(sentence.strip())
            sentence = ''
        return paragraphs