File size: 11,370 Bytes
9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 242bd10 9040523 a6416c8 9040523 a6416c8 9040523 a6416c8 9040523 a6416c8 9040523 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# #
# This file was created by: Alberto Palomo Alonso #
# Universidad de Alcalá - Escuela Politécnica Superior #
# #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# Import statements:
import tokenizers
import sys
import subprocess
import logging
import spacy
import numpy as np
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import Whitespace
from tokenizers.normalizers import NFKC
from transformers import PreTrainedTokenizerFast
# - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #
class SegmentationTokenizer:
"""
Wrapper class for training and using a BPE-based tokenizer for text segmentation.
This class supports:
- Training a Byte Pair Encoding (BPE) tokenizer from an iterator
- Saving and loading the tokenizer
- Tokenizing text with padding and truncation
- Computing the unknown-token (UNK) rate over a corpus
"""
def __init__(self, vocab_size=32_768, min_frequency=2, max_length=1024):
"""
Initialize the segmentation tokenizer.
Args:
vocab_size (int): Maximum vocabulary size for the BPE tokenizer.
min_frequency (int): Minimum token frequency to be included in the vocabulary.
max_length (int): Maximum sequence length for tokenization.
"""
self.max_length = max_length
# Raw tokenizer used only during training
self.raw_tokenizer = tokenizers.Tokenizer(
BPE(unk_token="[UNK]")
)
self.raw_tokenizer.normalizer = NFKC()
self.raw_tokenizer.pre_tokenizer = Whitespace()
# Trainer configuration for BPE
self.trainer = BpeTrainer(
vocab_size=vocab_size,
min_frequency=min_frequency,
special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]
)
# Hugging Face fast tokenizer (created after loading)
self._hf_tokenizer = None
# ------------------------------------------------------------------
# Training utilities
# ------------------------------------------------------------------
@staticmethod
def build_iterator(dataset, batch_size=1024):
"""
Build a batched text iterator from a dataset.
Each dataset item is expected to contain a "text" field,
which is a list of strings.
Args:
dataset (Iterable[dict]): Dataset containing text entries.
batch_size (int): Number of samples per batch.
Yields:
List[str]: A batch of concatenated text samples.
"""
batch = []
for item in dataset:
batch.append("\n".join(item["text"]).replace("\n\n", "\n"))
if len(batch) == batch_size:
yield batch
batch = []
if batch:
yield batch
def train_from_iterator(self, iterator):
"""
Train the raw tokenizer from an iterator of text batches.
Args:
iterator (Iterable[List[str]]): Iterator yielding batches of text.
"""
self.raw_tokenizer.train_from_iterator(
iterator,
trainer=self.trainer
)
# ------------------------------------------------------------------
# I/O
# ------------------------------------------------------------------
def save(self, path):
"""
Save the trained raw tokenizer to disk.
Args:
path (str): Path where the tokenizer file will be saved.
"""
self.raw_tokenizer.save(path)
def load(self, tokenizer_path):
"""
Load a tokenizer from disk as a Hugging Face fast tokenizer.
Args:
tokenizer_path (str): Path to the saved tokenizer file.
Returns:
SegmentationTokenizer: Self, for chaining.
"""
self._hf_tokenizer = PreTrainedTokenizerFast(
tokenizer_file=tokenizer_path,
unk_token="[UNK]",
pad_token="[PAD]",
cls_token="[CLS]",
sep_token="[SEP]",
mask_token="[MASK]"
)
return self
# ------------------------------------------------------------------
# Tokenization utilities
# ------------------------------------------------------------------
def compute_unk_rate(self, corpus):
"""
Compute the proportion of unknown tokens ([UNK]) in a corpus.
Args:
corpus (Iterable[str]): Collection of input texts.
Returns:
float: UNK token rate in the corpus.
"""
unk_id = self._hf_tokenizer.convert_tokens_to_ids("[UNK]")
total_tokens = 0
unk_tokens = 0
for text in corpus:
enc = self._hf_tokenizer(
text,
add_special_tokens=False
)["input_ids"]
total_tokens += len(enc)
unk_tokens += sum(1 for t in enc if t == unk_id)
return unk_tokens / total_tokens if total_tokens > 0 else 0.0
def __call__(
self,
text,
return_tensors="pt",
padding=True,
truncation=True
):
"""
Tokenize input text.
Args:
text (str or List[str]): Input text or batch of texts.
return_tensors (str): Tensor type to return (e.g., "pt").
padding (bool): Whether to pad sequences to max_length.
truncation (bool): Whether to truncate sequences to max_length.
Returns:
dict: Dictionary containing:
- input_ids (torch.LongTensor)
- attention_mask (torch.LongTensor)
"""
if self._hf_tokenizer is None:
raise RuntimeError("Tokenizer not loaded. Call .load() first.")
enc = self._hf_tokenizer(
text,
padding="max_length" if padding else False,
truncation=truncation,
max_length=self.max_length,
return_tensors=return_tensors
)
return {
"input_ids": enc["input_ids"],
"attention_mask": enc["attention_mask"]
}
# ------------------------------------------------------------------
# Properties and representations
# ------------------------------------------------------------------
@property
def vocab_size(self):
"""
Get the vocabulary size of the loaded tokenizer.
Returns:
int: Vocabulary size.
"""
if self._hf_tokenizer is None:
raise RuntimeError("Tokenizer not loaded.")
return self._hf_tokenizer.vocab_size
def __repr__(self):
"""
String representation of the tokenizer.
"""
return f"<SegmentationTokenizer vocab_size={self.trainer.vocab_size}>"
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# SENTENCE SEG #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
class SentenceSegmenter:
def __init__(
self,
max_sentences: int,
spacy_model: str = "es_core_news_sm",
logger: logging.Logger | None = None
):
self.max_sentences = max_sentences
self.logger = self._get_logger(logger)
self.nlp = self.__build_model__(spacy_model, logger=self.logger)
@staticmethod
def __build_model__(sentence_tokenizer_model: str, logger: logging.Logger) -> spacy.language.Language:
"""
Download the pre-trained sentence tokenizer model.
:param sentence_tokenizer_model: The sentence tokenizer model to download.
:return: The spacy language model.
"""
try:
spacy_model = spacy.load(sentence_tokenizer_model)
except OSError:
result = subprocess.run(
[sys.executable, "-m", "spacy", "download", sentence_tokenizer_model],
capture_output=True,
text=True
)
if result.returncode != 0:
logger.error(f'[BEAST-Tokenizer]: Loading {sentence_tokenizer_model} failed.')
raise RuntimeError(f"[BEAST-Tokenizer]: Error while downloading '{sentence_tokenizer_model}'")
spacy_model = spacy.load(sentence_tokenizer_model)
logger.info('[BEAST-Tokenizer]: Successfully downloaded the pre-trained sentence tokenizer model.')
if 'parser' not in spacy_model.pipe_names:
logger.error(f'[BEAST-Tokenizer]: The SpaCy model needs a parser installed.')
raise RuntimeError(f'[BEAST-Tokenizer]: The SpaCy model needs a parser installed.')
else:
spacy_model.add_pipe("newline_segmenter_keep_exact", before="parser")
return spacy_model
@staticmethod
def _get_logger(logger):
if logger is None:
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
return logger
def __call__(self, texts: list[str]) -> dict:
sentences = list()
sentence_candidates = list()
sentence_boundaries = list()
sentence_masking = list()
for article in texts:
doc = self.nlp(article)
last_was_jump = False
for idx, sent in enumerate(doc.sents):
if idx == 0:
# Article opener
sentence_candidates.append(1)
sentence_boundaries.append(1)
elif last_was_jump:
# Paragraph break candidate
sentence_candidates.append(1)
sentence_boundaries.append(0)
else:
sentence_candidates.append(0)
sentence_boundaries.append(0)
last_was_jump = sent.text.endswith("\n")
sentences.append(sent.text.replace('\n', '').strip())
sentence_masking.append(1)
if len(sentences) >= self.max_sentences:
self.logger.warning(f"Maximum number of sentences reached: {self.max_sentences}")
break
if len(sentences) >= self.max_sentences:
break
# Pad with zeros:
while len(sentences) < self.max_sentences:
sentences.append("")
sentence_candidates.append(0)
sentence_boundaries.append(0)
sentence_masking.append(0)
return {
"sentences": sentences,
"sentence_candidates": np.array(sentence_candidates, dtype=np.int8),
"sentence_boundaries": np.array(sentence_boundaries, dtype=np.int8),
"sentence_mask": np.array(sentence_masking, dtype=np.int8)
}
@spacy.Language.component("newline_segmenter_keep_exact")
def newline_segmenter_keep_exact(doc):
for token in doc[:-1]:
if token.text == "\n":
doc[token.i + 1].is_sent_start = True
return doc
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# END OF FILE #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
|