repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
mmda
|
mmda-main/src/mmda/predictors/d2_predictors/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/predictors/d2_predictors/bibentry_detection_predictor.py
|
from functools import reduce
import itertools
from typing import Any, Dict, Iterator, List, Optional, Union
import layoutparser as lp
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.types.annotation import BoxGroup
from mmda.types.box import Box
from mmda.types.document import Document
from mmda.types.names import PagesField, ImagesField, TokensField
from mmda.types.span import Span
def union(block1, block2):
x11, y11, x12, y12 = block1.coordinates
x21, y21, x22, y22 = block2.coordinates
return lp.Rectangle(min(x11, x21), min(y11, y21), max(x12, x22), max(y12, y22))
def union_blocks(blocks):
return reduce(union, blocks)
def make_rect(box: Box, page_width, page_height):
box = box.get_absolute(page_width, page_height)
rect = lp.elements.Rectangle(x_1=box.l, y_1=box.t, x_2=(box.l + box.w), y_2=(box.t + box.h))
return rect
def tighten_boxes(bib_box_group, page_tokens, page_width, page_height):
page_token_rects = [make_rect(span.box, page_width, page_height) for span in page_tokens]
page_tokens_as_layout = lp.elements.Layout(blocks=page_token_rects)
new_boxes = []
for box in bib_box_group.boxes:
abs_box = box.get_absolute(page_width, page_height)
rect = lp.elements.Rectangle(
abs_box.l,
abs_box.t,
abs_box.l + abs_box.w,
abs_box.t + abs_box.h
)
new_rect = union_blocks(page_tokens_as_layout.filter_by(rect, center=True))
new_boxes.append(
Box(l=new_rect.x_1,
t=new_rect.y_1,
w=new_rect.width,
h=new_rect.height,
page=box.page).get_relative(
page_width=page_width,
page_height=page_height,
)
)
new_box_group = BoxGroup(
boxes=new_boxes,
id=bib_box_group.id
)
new_box_group.metadata.set('type', 'bib_entry')
return new_box_group
class BibEntryDetectionPredictor(BasePredictor):
REQUIRED_BACKENDS = ["layoutparser", "detectron2"]
REQUIRED_DOCUMENT_FIELDS = [PagesField, ImagesField, TokensField]
def __init__(self, artifacts_dir: str, threshold: float = 0.88):
label_map = {0: "bibentry"}
self.model = lp.Detectron2LayoutModel(
config_path=f"{artifacts_dir}/archive/config.yaml",
model_path=f"{artifacts_dir}/archive/model_final.pth",
label_map=label_map,
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", threshold]
)
def postprocess(self,
model_outputs: lp.Layout,
page_tokens: List[Span],
page_index: int,
image: "PIL.Image",
id_counter: Iterator[int]) -> (List[BoxGroup], List[BoxGroup]):
"""Convert the model outputs for a single page image into the mmda format
Args:
model_outputs (lp.Layout):
The layout detection results from the layoutparser model for
a page image
page_tokens (List[Span]):
List of the Document's Token spans for this Page
page_index (int):
The index of the current page, used for creating the
`Box` object
image (PIL.Image):
The image of the current page, used for converting
to relative coordinates for the box objects
Returns:
(List[BoxGroup], List[BoxGroup]):
A tuple of the BoxGroups detected bibentry boxes tightened around
tokens, and the BoxGroups containing the originally detected, unprocessed model output boxes.
"""
original_box_groups: List[BoxGroup] = []
page_width, page_height = image.size
for ele in model_outputs:
model_output_box = Box.from_coordinates(
x1=ele.block.x_1,
y1=ele.block.y_1,
x2=ele.block.x_2,
y2=ele.block.y_2,
page=page_index
).get_relative(
page_width=page_width,
page_height=page_height,
)
current_id = next(id_counter)
box_group = BoxGroup(
boxes=[model_output_box],
id=current_id
)
box_group.metadata.set('type', 'raw_model_prediction')
original_box_groups.append(box_group)
processed_box_groups: List[BoxGroup] = []
for o_box_group in original_box_groups:
tightened_box_group = tighten_boxes(o_box_group, page_tokens, page_width, page_height)
processed_box_groups.append(tightened_box_group)
return processed_box_groups, original_box_groups
def predict(self, doc: Document) -> (List[BoxGroup], List[BoxGroup]):
"""Returns a list of BoxGroups for the detected bibentry boxes for all pages of a document
and second list of BoxGroups for original model output boxes from those same pages.
Args:
doc (Document):
The input document object containing all required annotations
Returns:
(List[BoxGroup], List[BoxGroup]):
A tuple of the BoxGroups containing bibentry boxes tightened around
tokens, and the BoxGroups containing the originally detected, unprocessed model output boxes.
"""
bib_entries: List[BoxGroup] = []
original_model_output: List[BoxGroup] = []
id_counter = itertools.count()
for page_index, image in enumerate(doc.images):
model_outputs: lp.Layout = self.model.detect(image)
page_tokens: List[Span] = list(
itertools.chain.from_iterable(
token_span_group.spans
for token_span_group in doc.pages[page_index].tokens
)
)
bib_entry_box_groups, og_box_groups = self.postprocess(
model_outputs,
page_tokens,
page_index,
image,
id_counter
)
bib_entries.extend(bib_entry_box_groups)
original_model_output.extend(og_box_groups)
return bib_entries, original_model_output
| 6,337 | 35.011364 | 109 |
py
|
mmda
|
mmda-main/src/mmda/predictors/base_predictors/base_predictor.py
|
from dataclasses import dataclass
from abc import abstractmethod
from typing import Union, List, Dict, Any
from mmda.types.annotation import Annotation
from mmda.types.document import Document
class BasePredictor:
###################################################################
##################### Necessary Model Variables ###################
###################################################################
# TODO[Shannon] Add the check for required backends in the future.
# So different models might require different backends:
# For example, LayoutLM only needs transformers, but LayoutLMv2
# needs transformers and Detectron2. It is the model creators'
# responsibility to check the required backends.
@property
@abstractmethod
def REQUIRED_BACKENDS(self):
return None
@property
@abstractmethod
def REQUIRED_DOCUMENT_FIELDS(self):
"""Due to the dynamic nature of the document class as well the
models, we require the model creator to provide a list of required
fields in the document class. If not None, the predictor class
will perform the check to ensure that the document contains all
the specified fields.
"""
return None
###################################################################
######################### Core Methods ############################
###################################################################
def _doc_field_checker(self, document: Document) -> None:
if self.REQUIRED_DOCUMENT_FIELDS is not None:
for field in self.REQUIRED_DOCUMENT_FIELDS:
assert (
field in document.fields
), f"The input Document object {document} doesn't contain the required field {field}"
# TODO[Shannon] Allow for some preprocessed document intput
# representation for better performance?
@abstractmethod
def predict(self, document: Document) -> List[Annotation]:
"""For all the mmda models, the input is a document object, and
the output is a list of annotations.
"""
self._doc_field_checker(document)
| 2,192 | 39.611111 | 101 |
py
|
mmda
|
mmda-main/src/mmda/predictors/base_predictors/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/predictors/base_predictors/base_heuristic_predictor.py
|
from mmda.predictors.base_predictors.base_predictor import BasePredictor
class BaseHeuristicPredictor(BasePredictor):
REQUIRED_BACKENDS = []
| 146 | 28.4 | 72 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/vila_predictor.py
|
# This file rewrites the PDFPredictor classes in
# https://github.com/allenai/VILA/blob/dd242d2fcbc5fdcf05013174acadb2dc896a28c3/src/vila/predictors.py#L1
# to reduce the dependency on the VILA package.
from typing import List, Union, Dict, Any, Tuple
from abc import abstractmethod
from dataclasses import dataclass
import inspect
import itertools
from tqdm import tqdm
import torch
from transformers import AutoTokenizer, AutoConfig, AutoModelForTokenClassification
from vila.models.hierarchical_model import (
HierarchicalModelForTokenClassification,
HierarchicalModelConfig,
)
from vila.dataset.preprocessors import instantiate_dataset_preprocessor
from mmda.types.metadata import Metadata
from mmda.types.names import PagesField, RowsField, TokensField
from mmda.types.annotation import Annotation, Span, SpanGroup
from mmda.types.document import Document
from mmda.predictors.hf_predictors.utils import (
convert_document_page_to_pdf_dict,
convert_sequence_tagging_to_spans,
normalize_bbox,
)
from mmda.predictors.hf_predictors.base_hf_predictor import BaseHFPredictor
# Two constants for the constraining the size of the page for
# inputs to the model.
# TODO: Move this to somewhere else.
MAX_PAGE_WIDTH = 1000
MAX_PAGE_HEIGHT = 1000
def columns_used_in_model_inputs(model):
signature = inspect.signature(model.forward)
signature_columns = list(signature.parameters.keys())
return signature_columns
@dataclass
class VILAPreprocessorConfig:
agg_level: str = "row"
label_all_tokens: bool = False
group_bbox_agg: str = "first"
added_special_sepration_token: str = "[SEP]"
# This is introduced to support the updates in the
# vila 0.4.0 which fixes the typo.
@property
def added_special_separation_token(self):
return self.added_special_sepration_token
class BaseVILAPredictor(BaseHFPredictor):
REQUIRED_BACKENDS = ["transformers", "torch", "vila"]
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField]
def __init__(
self, model: Any, config: Any, tokenizer: Any, preprocessor, device=None
):
self.model = model
self.tokenizer = tokenizer
self.config = config
self.preprocessor = preprocessor
if device is None:
self.device = model.device
else:
self.device = device
model.to(self.device)
self.model.eval()
self._used_cols = columns_used_in_model_inputs(self.model)
# Sometimes the input data might contain certain columns that are
# not used in the model inputs. For example, for a BERT model,
# it won't use the `bbox` column.
@classmethod
def from_pretrained(
cls,
model_name_or_path: str,
preprocessor=None,
device: str = None,
**preprocessor_config
):
config = AutoConfig.from_pretrained(model_name_or_path)
model = AutoModelForTokenClassification.from_pretrained(
model_name_or_path, config=config
)
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
if preprocessor is None:
preprocessor = cls.initialize_preprocessor(
tokenizer, VILAPreprocessorConfig(**preprocessor_config)
)
return cls(model, config, tokenizer, preprocessor, device)
@staticmethod
@abstractmethod
def initialize_preprocessor(tokenizer, config):
# preprocessors defines how to create the actual model inputs
# based on the raw pdf data (characterized by pdf_dict).
# For example, in i-vila models, we can inject a special token
# in the model inputs. This requires additional preprocessing
# of the pdf_dicts, and it is handled by preprocessors in the
# vila module.
pass
def preprocess(
self, pdf_dict: Dict[str, List[Any]], page_width: int, page_height: int
) -> Dict[str, List[Any]]:
_labels = pdf_dict.get("labels")
pdf_dict["labels"] = [0] * len(pdf_dict["words"])
# because the preprocess_sample requires the labels to be
# a numeric value, so we temporarily set the labels to 0.
# (it will set some labels to -100)
# and we will change them back to the original labels later.
model_inputs = self.preprocessor.preprocess_sample(pdf_dict)
model_inputs["bbox"] = [
[
normalize_bbox(
bbox,
page_width,
page_height,
target_width=MAX_PAGE_WIDTH,
target_height=MAX_PAGE_HEIGHT,
)
for bbox in batch
]
for batch in model_inputs["bbox"]
]
pdf_dict["labels"] = _labels
return model_inputs
@abstractmethod
def get_true_token_level_category_prediction(
self, pdf_dict, model_inputs, model_predictions
) -> List[Union[str, int]]:
# Typically BERT-based models will generate categories for each
# word-piece encoded tokens (and also for included special tokens
# like [SEP] and [CLS]). Therefore, we need to clean the predictions
# to get the category predictions for the tokens that are actually
# appeared inside the document.
# The implementation of this method is specific to each model.
pass
def postprocess(
self, document, pdf_dict, model_inputs, model_predictions
) -> List[SpanGroup]:
true_token_prediction = self.get_true_token_level_category_prediction(
pdf_dict, model_inputs, model_predictions
)
token_prediction_spans = convert_sequence_tagging_to_spans(
true_token_prediction
)
prediction_spans = []
for (token_start, token_end, label) in token_prediction_spans:
cur_spans = document.tokens[token_start:token_end]
start = min([ele.start for ele in cur_spans])
end = max([ele.end for ele in cur_spans])
sg = SpanGroup(spans=[Span(start, end)], metadata=Metadata(type=label))
prediction_spans.append(sg)
return prediction_spans
def predict(self, document: Document) -> List[Annotation]:
page_prediction_results = []
for page_id, page in enumerate(tqdm(document.pages)):
if page.tokens:
page_width, page_height = document.images[page_id].size
pdf_dict = convert_document_page_to_pdf_dict(
page, page_width=page_width, page_height=page_height
)
# VILA models trained based on absolute page width rather than the
# size (1000, 1000) in vanilla LayoutLM models
model_inputs = self.preprocess(pdf_dict, page_width, page_height)
model_outputs = self.model(**self.model_input_collator(model_inputs))
model_predictions = self.get_category_prediction(model_outputs)
page_prediction_results.extend(
self.postprocess(page, pdf_dict, model_inputs, model_predictions)
)
return page_prediction_results
############################################
###### Some other auxiliary functions ######
############################################
def get_category_prediction(self, model_outputs):
predictions = model_outputs.logits.argmax(dim=-1).cpu().numpy()
return predictions
def model_input_collator(self, sample):
return {
key: torch.tensor(val, dtype=torch.int64, device=self.device)
for key, val in sample.items()
if key in self._used_cols
}
class SimpleVILAPredictor(BaseVILAPredictor):
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField]
@staticmethod
def initialize_preprocessor(tokenizer, config: VILAPreprocessorConfig):
return instantiate_dataset_preprocessor("base", tokenizer, config)
def get_true_token_level_category_prediction(
self, pdf_dict, model_inputs, model_predictions
):
encoded_labels = model_inputs["labels"]
true_predictions = [
[(p, l) for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(model_predictions, encoded_labels)
]
true_predictions = list(itertools.chain.from_iterable(true_predictions))
preds = [ele[0] for ele in true_predictions]
# right here, the true_prediction has one-to-one correspondence with
# the words in the input document.
return preds
class IVILAPredictor(SimpleVILAPredictor):
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField, RowsField] # , Blocks]
# TODO: Right now we only use the rows, but we should also use the blocks
# in the future.
@staticmethod
def initialize_preprocessor(tokenizer, config):
return instantiate_dataset_preprocessor("layout_indicator", tokenizer, config)
class HVILAPredictor(BaseVILAPredictor):
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField, RowsField] # , Blocks]
# TODO: Right now we only use the rows, but we should also use the blocks
# in the future.
@classmethod
def from_pretrained(
cls,
model_name_or_path: str,
preprocessor=None,
device: str = None,
**preprocessor_config
):
config = HierarchicalModelConfig.from_pretrained(model_name_or_path)
model = HierarchicalModelForTokenClassification.from_pretrained(
model_name_or_path, config=config
)
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
if preprocessor is None:
preprocessor = cls.initialize_preprocessor(
tokenizer, VILAPreprocessorConfig(**preprocessor_config)
)
return cls(model, config, tokenizer, preprocessor, device)
@staticmethod
def initialize_preprocessor(tokenizer, config):
return instantiate_dataset_preprocessor(
"hierarchical_modeling", tokenizer, config
)
@staticmethod
def flatten_line_level_prediction(batched_line_pred, batched_line_word_count):
final_flattend_pred = []
for line_pred, line_word_count in zip(
batched_line_pred, batched_line_word_count
):
assert len(line_pred) == len(line_word_count)
for (pred, label), (line_id, count) in zip(line_pred, line_word_count):
final_flattend_pred.append([[pred, label, line_id]] * count)
return list(itertools.chain.from_iterable(final_flattend_pred))
def get_true_token_level_category_prediction(
self, pdf_dict, model_inputs, model_predictions
):
encoded_labels = model_inputs["labels"]
true_predictions = [
[(p, l) for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(model_predictions, encoded_labels)
]
flatten_predictions = self.flatten_line_level_prediction(
true_predictions, model_inputs["group_word_count"]
)
preds = [ele[0] for ele in flatten_predictions]
return preds
| 11,250 | 35.060897 | 105 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/utils.py
|
from mmda.types.annotation import SpanGroup
from typing import List, Tuple, Dict
import itertools
from mmda.types.document import Document
from mmda.types.names import BlocksField, RowsField
def normalize_bbox(
bbox,
page_width,
page_height,
target_width,
target_height,
):
"""
Normalize bounding box to the target size.
"""
x1, y1, x2, y2 = bbox
# Right now only execute this for only "large" PDFs
# TODO: Change it for all PDFs
if page_width > target_width or page_height > target_height:
x1 = float(x1) / page_width * target_width
x2 = float(x2) / page_width * target_width
y1 = float(y1) / page_height * target_height
y2 = float(y2) / page_height * target_height
return (x1, y1, x2, y2)
def shift_index_sequence_to_zero_start(sequence):
"""
Shift a sequence to start at 0.
"""
sequence_start = min(sequence)
return [i - sequence_start for i in sequence]
def get_visual_group_id(token: SpanGroup, field_name: str, defaults=-1) -> int:
if not hasattr(token, field_name):
return defaults
field_value = getattr(token, field_name)
if len(field_value) == 0 or field_value[0].id is None:
return defaults
return field_value[0].id
def convert_document_page_to_pdf_dict(
document: Document, page_width: int, page_height: int
) -> Dict[str, List]:
"""Convert a document to a dictionary of the form:
{
'words': ['word1', 'word2', ...],
'bbox': [[x1, y1, x2, y2], [x1, y1, x2, y2], ...],
'block_ids': [0, 0, 0, 1 ...],
'line_ids': [0, 1, 1, 2 ...],
'labels': [0, 0, 0, 1 ...], # could be empty
}
Args:
document (Document):
The input document object
page_width (int):
Typically the transformer model requires to use
the absolute coordinates for encoding the coordinates.
Set the correspnding page_width and page_height to convert the
relative coordinates to the absolute coordinates.
page_height (int):
Typically the transformer model requires to use
the absolute coordinates for encoding the coordinates.
Set the correspnding page_width and page_height to convert the
relative coordinates to the absolute coordinates.
Returns:
Dict[str, List]: The pdf_dict object
"""
token_data = [
(
token.symbols[0], # words
token.spans[0]
.box.get_absolute(page_width=page_width, page_height=page_height)
.coordinates, # bbox
get_visual_group_id(token, RowsField, -1), # line_ids
get_visual_group_id(token, BlocksField, -1) # block_ids
) for token in document.tokens
]
words, bbox, line_ids, block_ids = (list(l) for l in zip(*token_data))
line_ids = shift_index_sequence_to_zero_start(line_ids)
block_ids = shift_index_sequence_to_zero_start(block_ids)
labels = [None] * len(words)
# TODO: We provide an empty label list.
return {
"words": words,
"bbox": bbox,
"block_ids": block_ids,
"line_ids": line_ids,
"labels": labels,
}
def convert_sequence_tagging_to_spans(
token_prediction_sequence: List,
) -> List[Tuple[int, int, int]]:
"""For a sequence of token predictions, convert them to spans
of consecutive same predictions.
Args:
token_prediction_sequence (List)
Returns:
List[Tuple[int, int, int]]: A list of (start, end, label)
of consecutive prediction of the same label.
"""
prev_len = 0
spans = []
for gp, seq in itertools.groupby(token_prediction_sequence):
cur_len = len(list(seq))
spans.append((prev_len, prev_len + cur_len, gp))
prev_len = prev_len + cur_len
return spans
| 3,926 | 29.679688 | 81 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/mention_predictor.py
|
import itertools
import os.path
import string
from typing import Dict, Iterator, List, Optional
from optimum.onnxruntime import ORTModelForTokenClassification
import torch
from transformers import AutoModelForTokenClassification, AutoTokenizer, BatchEncoding
from mmda.types.annotation import Annotation, SpanGroup
from mmda.types.document import Document
from mmda.types.span import Span
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
class Labels:
# BILOU https://stackoverflow.com/q/17116446
MENTION_OUTSIDE_ID = 0
MENTION_BEGIN_ID = 1
MENTION_INSIDE_ID = 2
MENTION_LAST_ID = 3
MENTION_UNIT_ID = 4
MENTION_OUTSIDE = "O"
MENTION_BEGIN = "B-MENTION"
MENTION_INSIDE = "I-MENTION"
MENTION_LAST = "E-MENTION" # "end"
MENTION_UNIT = "S-MENTION" # "single"
ID_TO_LABEL: Dict[int, str] = {
MENTION_OUTSIDE_ID: MENTION_OUTSIDE,
MENTION_BEGIN_ID: MENTION_BEGIN,
MENTION_INSIDE_ID: MENTION_INSIDE,
MENTION_LAST_ID: MENTION_LAST,
MENTION_UNIT_ID: MENTION_UNIT
}
LABEL_TO_ID: Dict[str, int] = {
MENTION_OUTSIDE: MENTION_OUTSIDE_ID,
MENTION_BEGIN: MENTION_BEGIN_ID,
MENTION_INSIDE: MENTION_INSIDE_ID,
MENTION_LAST: MENTION_LAST_ID,
MENTION_UNIT: MENTION_UNIT_ID
}
class MentionPredictor:
# This predictor works best on documents generated by a pdfplumber instance
# that is configured to use the following value for `split_at_punctuation`.
PUNCTUATION_TO_SPLIT_AT = PDFPlumberParser.DEFAULT_PUNCTUATION_CHARS
def __init__(self, artifacts_dir: str):
self.tokenizer = AutoTokenizer.from_pretrained(artifacts_dir)
onnx = os.path.exists(os.path.join(artifacts_dir, "model.onnx"))
if onnx:
self.model = ORTModelForTokenClassification.from_pretrained(artifacts_dir, file_name="model.onnx")
else:
self.model = AutoModelForTokenClassification.from_pretrained(artifacts_dir)
# this is a side-effect(y) function
self.model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
if not onnx:
# https://stackoverflow.com/a/60018731
self.model.eval() # for some reason the onnx version doesnt have an eval()
def predict(self, doc: Document, print_warnings: bool = False) -> List[SpanGroup]:
if not hasattr(doc, 'pages'):
return []
spangroups = []
counter = itertools.count()
for page in doc.pages:
spangroups.extend(self.predict_page(page, counter=counter, print_warnings=print_warnings))
return spangroups
def predict_page(self, page: Annotation, counter: Iterator[int], print_warnings: bool = False) -> List[SpanGroup]:
if not hasattr(page, 'tokens'):
return []
ret = []
words: List[str] = ["".join(token.symbols) for token in page.tokens]
word_spans: List[List[Span]] = [[Span.from_json(span_dict=span.to_json()) for span in token.spans] for token in page.tokens]
inputs = self.tokenizer(
[words],
is_split_into_words=True,
max_length=512,
truncation=True,
padding='max_length',
return_overflowing_tokens=True,
return_tensors="pt"
)
with torch.no_grad():
# Control device memory use to predictable levels
# by limiting size of batches sent to it.
prediction_label_ids = []
for index, sequence in enumerate(inputs["input_ids"]):
batch = BatchEncoding(
data=dict(
input_ids=inputs["input_ids"][index:index+1],
token_type_ids=inputs["token_type_ids"][index:index+1],
attention_mask=inputs["attention_mask"][index:index+1],
)
)
batch.to(self.model.device)
batch_outputs = self.model(**batch)
batch_prediction_label_ids = torch.argmax(batch_outputs.logits, dim=-1)[0]
prediction_label_ids.append(batch_prediction_label_ids)
def has_label_id(lbls: List[int], want_label_id: int) -> bool:
return any(lbl == want_label_id for lbl in lbls)
# make list of word ids and list of label ids for each word
word_ids: List[Optional[int]] = []
word_label_ids: List[Optional[List[int]]] = []
for idx1 in range(len(inputs['input_ids'])):
batch_label_ids = prediction_label_ids[idx1]
input_ = inputs[idx1]
# keep track of this loop's word_ids
these_word_ids = [input_.word_ids[0]]
# append to the outer word_ids and word_label_ids lists
if input_.word_ids[0] is not None:
word_ids.append(input_.word_ids[0])
word_label_ids.append(batch_label_ids[0])
else:
# preserve the Nones
word_ids.append(None)
word_label_ids.append(None)
for idx2 in range(1, len(input_.word_ids)):
word_id: int = input_.word_ids[idx2]
# get previous_word_id from this current list of word_ids
previous_word_id: int = input_.word_ids[idx2 - 1]
# if all of these_word_ids are None...
if all([not bool(word_id) for word_id in these_word_ids]):
# ... then try to get previous_word_id from looping through larger word_ids list til not None
for idx3 in range(len(word_ids) - 1, -1, -1):
if word_ids[idx3] is not None:
previous_word_id = word_ids[idx3]
break
if word_id is not None:
label_id: int = batch_label_ids[idx2]
if word_id == previous_word_id:
# add to previous_word_id's word_label_ids by finding its corresponding index in word_ids
for idx3 in range(len(word_ids) - 1, -1, -1):
if word_ids[idx3] == previous_word_id:
word_label_ids[idx3].append(label_id)
break
else:
word_label_ids.append([label_id])
word_ids.append(word_id)
else:
# again, preserve the Nones
word_ids.append(None)
word_label_ids.append(None)
# always
these_word_ids.append(word_id)
acc: List[Span] = []
outside_mention = True
def append_acc():
nonlocal acc
if acc:
ret.append(SpanGroup(spans=acc, id=next(counter)))
acc = []
# now we can zip our lists of word_ids (which correspond to spans) and label_ids (for which there can be
# multiple because of batching), we can decide how to label each span how to accumulate them into SpanGroups
for word_id, label_ids in zip(word_ids, word_label_ids):
if not word_id:
continue
spans = word_spans[word_id]
has_begin = has_label_id(label_ids, Labels.MENTION_BEGIN_ID)
has_last = has_label_id(label_ids, Labels.MENTION_LAST_ID)
has_unit = has_label_id(label_ids, Labels.MENTION_UNIT_ID)
warnings = []
label_id: Optional[int] = None
if sum(1 for cond in [has_begin, has_last, has_unit] if cond) > 1:
warnings.append(
"found multiple labels for the same word: "
f"has_begin={has_begin} has_last={has_last} has_unit={has_unit}, spans = {spans}"
)
for cur_label_id in label_ids:
# prioritize begin, last, unit over the rest
if cur_label_id not in (Labels.MENTION_INSIDE_ID, Labels.MENTION_OUTSIDE_ID):
label_id = cur_label_id
break
if label_id is None:
# prioritize inside over outside
label_id = Labels.MENTION_INSIDE_ID \
if any(lbl == Labels.MENTION_INSIDE_ID for lbl in label_ids) else label_ids[0]
if outside_mention and has_last:
warnings.append(f"found an 'L' while outside mention, spans = {spans}")
if not outside_mention and (has_begin or has_unit):
warnings.append(f"found a 'B' or 'U' while inside mention, spans = {spans}")
if warnings and print_warnings:
print("warnings:")
for warning in warnings:
print(f" - {warning}")
if label_id == Labels.MENTION_UNIT_ID:
append_acc()
acc = spans
append_acc()
outside_mention = True
if label_id == Labels.MENTION_BEGIN_ID:
append_acc()
acc = spans
outside_mention = False
elif label_id == Labels.MENTION_LAST_ID:
acc.extend(spans)
append_acc()
outside_mention = True
elif label_id == Labels.MENTION_INSIDE_ID:
acc.extend(spans)
append_acc()
return ret
| 9,459 | 40.130435 | 132 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/token_classification_predictor.py
|
from typing import List, Union, Dict, Any, Tuple, Optional, Sequence
from abc import abstractmethod
from tqdm import tqdm
from vila.predictors import (
SimplePDFPredictor,
LayoutIndicatorPDFPredictor,
HierarchicalPDFPredictor,
)
from mmda.types.metadata import Metadata
from mmda.types.names import BlocksField, PagesField, RowsField, TokensField
from mmda.types.annotation import Annotation, Span, SpanGroup
from mmda.types.document import Document
from mmda.predictors.hf_predictors.utils import (
convert_document_page_to_pdf_dict,
convert_sequence_tagging_to_spans,
)
from mmda.predictors.hf_predictors.base_hf_predictor import BaseHFPredictor
class BaseSinglePageTokenClassificationPredictor(BaseHFPredictor):
REQUIRED_BACKENDS = ["transformers", "torch", "vila"]
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField]
DEFAULT_SUBPAGE_PER_RUN = 2 # TODO: Might remove this in the future for longformer-like models
@property
@abstractmethod
def VILA_MODEL_CLASS(self):
pass
def __init__(self, predictor, subpage_per_run: Optional[int] = None):
self.predictor = predictor
# TODO: Make this more robust
self.id2label = self.predictor.model.config.id2label
self.label2id = self.predictor.model.config.label2id
self.subpage_per_run = subpage_per_run or self.DEFAULT_SUBPAGE_PER_RUN
@classmethod
def from_pretrained(
cls,
model_name_or_path: str,
preprocessor=None,
device: Optional[str] = None,
subpage_per_run: Optional[int] = None,
**preprocessor_config
):
predictor = cls.VILA_MODEL_CLASS.from_pretrained(
model_path=model_name_or_path,
preprocessor=preprocessor,
device=device,
**preprocessor_config
)
return cls(predictor, subpage_per_run)
def predict(
self, document: Document, subpage_per_run: Optional[int] = None
) -> List[Annotation]:
page_prediction_results = []
for page_id, page in enumerate(tqdm(document.pages)):
if page.tokens:
page_width, page_height = document.images[page_id].size
pdf_dict = self.preprocess(
page, page_width=page_width, page_height=page_height
)
model_predictions = self.predictor.predict(
page_data=pdf_dict,
page_size=(page_width, page_height),
batch_size=subpage_per_run or self.subpage_per_run,
return_type="list",
)
assert len(model_predictions) == len(
page.tokens), f"Model predictions and tokens are not the same length ({len(model_predictions)} != {len(page.tokens)}) for page {page_id}"
page_prediction_results.extend(
self.postprocess(page, model_predictions)
)
return page_prediction_results
def preprocess(self, page: Document, page_width: float, page_height: float) -> Dict:
# In the latest vila implementations (after 0.4.0), the predictor will
# handle all other preprocessing steps given the pdf_dict input format.
return convert_document_page_to_pdf_dict(
page, page_width=page_width, page_height=page_height
)
def postprocess(self, document: Document, model_predictions) -> List[SpanGroup]:
token_prediction_spans = convert_sequence_tagging_to_spans(model_predictions)
prediction_spans = []
for (token_start, token_end, label) in token_prediction_spans:
cur_spans = document.tokens[token_start:token_end]
start = min([ele.start for ele in cur_spans])
end = max([ele.end for ele in cur_spans])
sg = SpanGroup(spans=[Span(start, end)], metadata=Metadata(type=label))
prediction_spans.append(sg)
return prediction_spans
class SinglePageTokenClassificationPredictor(
BaseSinglePageTokenClassificationPredictor
):
VILA_MODEL_CLASS = SimplePDFPredictor
class IVILATokenClassificationPredictor(BaseSinglePageTokenClassificationPredictor):
VILA_MODEL_CLASS = LayoutIndicatorPDFPredictor
@property
def REQUIRED_DOCUMENT_FIELDS(self) -> List:
base_reqs = [PagesField, TokensField]
if self.predictor.preprocessor.config.agg_level == "row":
base_reqs.append(RowsField)
elif self.predictor.preprocessor.config.agg_level == "block":
base_reqs.append(BlocksField)
return base_reqs
class HVILATokenClassificationPredictor(BaseSinglePageTokenClassificationPredictor):
VILA_MODEL_CLASS = HierarchicalPDFPredictor
@property
def REQUIRED_DOCUMENT_FIELDS(self) -> List:
base_reqs = [PagesField, TokensField]
if self.predictor.preprocessor.config.agg_level == "row":
base_reqs.append(RowsField)
elif self.predictor.preprocessor.config.agg_level == "block":
base_reqs.append(BlocksField)
return base_reqs
| 5,137 | 34.191781 | 157 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/span_group_classification_predictor.py
|
"""
@kylel
"""
from typing import List, Any, Tuple, Optional, Sequence
from collections import defaultdict
import numpy as np
import torch
import transformers
from smashed.interfaces.simple import (
TokenizerMapper,
UnpackingMapper,
FixedBatchSizeMapper,
FromTokenizerListCollatorMapper,
Python2TorchMapper,
)
from mmda.types.metadata import Metadata
from mmda.types.annotation import Annotation, Span, SpanGroup
from mmda.types.document import Document
from mmda.predictors.hf_predictors.base_hf_predictor import BaseHFPredictor
class SpanGroupClassificationBatch:
def __init__(
self,
input_ids: List[List[int]],
attention_mask: List[List[int]],
span_group_ids: List[List[Optional[int]]],
context_id: List[int]
):
assert len(input_ids) == len(attention_mask) == len(span_group_ids) == len(context_id), \
f"Inputs to batch arent same length"
self.batch_size = len(input_ids)
assert [len(example) for example in input_ids] == \
[len(example) for example in attention_mask] == \
[len(example) for example in span_group_ids], f"Examples in batch arent same length"
self.input_ids = input_ids
self.attention_mask = attention_mask
self.span_group_ids = span_group_ids
self.context_id = context_id
class SpanGroupClassificationPrediction:
def __init__(self, context_id: int, span_group_id: int, label: str, score: float):
self.context_id = context_id
self.span_group_id = span_group_id
self.label = label
self.score = score
class SpanGroupClassificationPredictor(BaseHFPredictor):
"""
This is a generic wrapper around Huggingface Token Classification models.
First, we need a `span_group_name` which defines the Document field that we will treat as the
target unit of prediction. For example, if `span_group_name` is 'tokens', then we expect
to classify every Document.token. But technically, `span_group_name` could be anything,
such as `words` or `rows` or any SpanGroup.
Second, we need a `context_name` which defines the Document field that we will treat as the
intuitive notion of an "example" that we want to run our model over. For example, if
`context_name` is 'pages', then we'll loop over each page, running our classifier
over all the 'tokens' in each page. If the `context_name` is `bib_entries`, then we'll
loop over each bib entry, running our classifier over the 'tokens' in each page.
The key consequence of defining a `context_name` is, when the model constructs batches
of sequences that fit within the Huggingface transformer's window, it will *not*
mix sequences from different contexts into the same batch.
@kylel
"""
REQUIRED_BACKENDS = ["transformers", "torch", "smashed"]
REQUIRED_DOCUMENT_FIELDS = []
_SPAN_GROUP = 'inputs'
_CONTEXT_ID = 'context_id'
_HF_RESERVED_INPUT_IDS = 'input_ids'
_HF_RESERVED_ATTN_MASK = 'attention_mask'
_HF_RESERVED_WORD_IDS = 'word_ids'
_HF_RESERVED_WORD_PAD_VALUE = -1
def __init__(
self,
model: Any,
config: Any,
tokenizer: Any,
span_group_name: str,
context_name: str,
batch_size: Optional[int] = 2,
device: Optional[str] = 'cpu'
):
super().__init__(model=model, config=config, tokenizer=tokenizer)
self.span_group_name = span_group_name
self.context_name = context_name
self.batch_size = batch_size
self.device = device
# handles tokenization, sliding window, truncation, subword to input word mapping, etc.
self.tokenizer_mapper = TokenizerMapper(
input_field=self._SPAN_GROUP,
tokenizer=tokenizer,
is_split_into_words=True,
add_special_tokens=True,
truncation=True,
max_length=model.config.max_position_embeddings,
return_overflowing_tokens=True,
return_word_ids=True
)
# since input data is automatically chunked into segments (e.g. 512 length),
# each example <dict> actually becomes many input sequences.
# this mapper unpacks all of this into one <dict> per input sequence.
# we set `repeat` because we want other fields (`context_id`) to repeat across sequnces
self.unpacking_mapper = UnpackingMapper(
fields_to_unpack=[
self._HF_RESERVED_INPUT_IDS,
self._HF_RESERVED_ATTN_MASK,
self._HF_RESERVED_WORD_IDS
],
ignored_behavior='repeat'
)
# at the end of this, each <dict> contains <lists> of length `batch_size`
# where each element is variable length within the `max_length` limit.
# `keep_last` controls whether we want partial batches, which we always do
# for token classification (i.e. we dont want to miss anything!)
self.batch_size_mapper = FixedBatchSizeMapper(
batch_size=batch_size,
keep_last=True
)
# this performs padding so all sequences in a batch are of same length
self.list_collator_mapper = FromTokenizerListCollatorMapper(
tokenizer=tokenizer,
pad_to_length=None, # keeping this `None` is best because dynamic padding
fields_pad_ids={
self._HF_RESERVED_WORD_IDS: self._HF_RESERVED_WORD_PAD_VALUE
}
)
# this casts python Dict[List] into tensors. if using GPU, would do `device='gpu'`
self.python_to_torch_mapper = Python2TorchMapper(
device=device
)
# combining everything
self.preprocess_mapper = self.tokenizer_mapper >> \
self.unpacking_mapper >> \
self.batch_size_mapper
@classmethod
def from_pretrained(
cls,
model_name_or_path: str,
span_group_name: str,
context_name: str,
batch_size: Optional[int] = 2,
device: Optional[str] = 'cpu',
*args,
**kwargs
):
"""If `model_name_or_path` is a path, should be a directory
containing `vocab.txt`, `config.json`, and `pytorch_model.bin`
NOTE: slightly annoying, but if loading in this way, the `_name_or_path`
in `model.config` != `config`.
"""
tokenizer = transformers.AutoTokenizer.from_pretrained(
pretrained_model_name_or_path=model_name_or_path, *args, **kwargs
)
config = transformers.AutoConfig.from_pretrained(
pretrained_model_name_or_path=model_name_or_path, *args, **kwargs
)
model = transformers.AutoModelForTokenClassification.from_pretrained(
pretrained_model_name_or_path=model_name_or_path, *args, **kwargs
)
predictor = cls(model=model, config=config, tokenizer=tokenizer,
span_group_name=span_group_name, context_name=context_name,
batch_size=batch_size, device=device)
return predictor
def preprocess(
self,
document: Document,
context_name: str
) -> List[SpanGroupClassificationBatch]:
"""Processes document into whatever makes sense for the Huggingface model"""
# (1) get it into a dictionary format that Smashed expects
dataset = [
{
self._SPAN_GROUP: [sg.text for sg in getattr(context, self.span_group_name)],
self._CONTEXT_ID: i
}
for i, context in enumerate(getattr(document, context_name))
]
# (2) apply Smashed
batch_dicts = self.preprocess_mapper.map(dataset=dataset)
# (3) convert dicts to objects
return [
# slightly annoying, but the names `input_ids`, `attention_mask` and `word_ids` are
# reserved and produced after tokenization, which is why hard-coded here.
SpanGroupClassificationBatch(
input_ids=batch_dict[self._HF_RESERVED_INPUT_IDS],
attention_mask=batch_dict[self._HF_RESERVED_ATTN_MASK],
span_group_ids=batch_dict[self._HF_RESERVED_WORD_IDS],
context_id=batch_dict[self._CONTEXT_ID]
) for batch_dict in batch_dicts
]
def postprocess(
self,
doc: Document,
context_name: str,
preds: List[SpanGroupClassificationPrediction]
) -> List[Annotation]:
"""This function handles a bunch of nonsense that happens with Huggingface models &
how we processed the data. Namely:
Because Huggingface might drop tokens during the course of tokenization
we need to organize our predictions into a Lookup <dict> and cross-reference
with the original input SpanGroups to make sure they all got classified.
"""
# (1) organize predictions into a Lookup at the (Context, SpanGroup) level.
context_id_to_span_group_id_to_pred = defaultdict(dict)
for pred in preds:
context_id_to_span_group_id_to_pred[pred.context_id][pred.span_group_id] = pred
# (2) iterate through original data to check against that Lookup
annotations: List[Annotation] = []
for i, context in enumerate(getattr(doc, context_name)):
for j, span_group in enumerate(getattr(context, self.span_group_name)):
pred = context_id_to_span_group_id_to_pred[i].get(j, None)
# TODO: double-check whether this deepcopy is needed...
new_metadata = Metadata.from_json(span_group.metadata.to_json())
if pred is not None:
new_metadata.label = pred.label
new_metadata.score = pred.score
else:
new_metadata.label = None
new_metadata.score = None
new_span_group = SpanGroup(
spans=span_group.spans,
box_group=span_group.box_group,
metadata=new_metadata
)
annotations.append(new_span_group)
return annotations
def predict(self, document: Document) -> List[Annotation]:
# (0) Check fields
assert self.span_group_name in document.fields, f"Input doc missing {self.span_group_name}"
assert self.context_name in document.fields, f"Input doc missing {self.context_name}"
# (1) Make batches
batches: List[SpanGroupClassificationBatch] = self.preprocess(
document=document, context_name=self.context_name
)
# (2) Predict each batch.
preds: List[SpanGroupClassificationPrediction] = []
for batch in batches:
for pred in self._predict_batch(batch=batch):
preds.append(pred)
# (3) Postprocess into proper Annotations
annotations = self.postprocess(doc=document, context_name=self.context_name, preds=preds)
return annotations
def _predict_batch(
self,
batch: SpanGroupClassificationBatch
) -> List[SpanGroupClassificationPrediction]:
#
# preprocessing!! (padding & tensorification)
#
pytorch_batch = self.python_to_torch_mapper.transform(
data=self.list_collator_mapper.transform(
data={
self._HF_RESERVED_INPUT_IDS: batch.input_ids,
self._HF_RESERVED_ATTN_MASK: batch.attention_mask
}
)
)
#
# inference!! (preferably on gpu)
#
# TODO: add something here for gpu migration
pytorch_output = self.model(**pytorch_batch)
scores_tensor = torch.softmax(pytorch_output.logits, dim=2)
token_scoresss = [
[
token_scores for token_scores, yn in zip(token_scoress, yns)
if yn == 1
]
for token_scoress, yns in zip(scores_tensor.tolist(), batch.attention_mask)
]
#
# postprocessing (map back to original inputs)!!
#
preds = []
for j, (context_id, word_ids, token_scoress) in enumerate(zip(
batch.context_id,
batch.span_group_ids,
token_scoresss)
):
for word_id, token_scores, is_valid_pred in zip(
word_ids,
token_scoress,
self._token_pooling_strategy_mask(word_ids=word_ids)
):
if word_id is None or is_valid_pred is False:
continue
else:
label_id = np.argmax(token_scores)
pred = SpanGroupClassificationPrediction(
context_id=context_id,
span_group_id=word_id,
label=self.config.id2label[label_id],
score=token_scores[label_id]
)
preds.append(pred)
return preds
def _token_pooling_strategy_mask(
self,
token_ids: Optional[List[int]] = None,
word_ids: Optional[List[int]] = None,
token_scores: Optional[List[Tuple[float, float]]] = None,
strategy: str = 'first'
) -> List[bool]:
"""
words are split into multiple tokens, each of which has a prediction.
there are multiple strategies to decide the model prediction at a word-level:
1) 'first': take only the first token prediction for whole word
2) 'max': take the highest scoring token prediction for whole word
3) ...
"""
if strategy == 'first':
mask = [True]
prev_word_id = word_ids[0]
for current_word_id in word_ids[1:]:
if current_word_id == prev_word_id:
mask.append(False)
else:
mask.append(True)
prev_word_id = current_word_id
else:
raise NotImplementedError(f"mode {strategy} not implemented yet")
# if no word ID (e.g. [cls], [sep]), always mask
mask = [
is_word if word_id is not None else False
for is_word, word_id in zip(mask, word_ids)
]
return mask
| 14,554 | 39.543175 | 99 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/base_hf_predictor.py
|
from abc import abstractmethod
from typing import Union, List, Dict, Any
from transformers import AutoTokenizer, AutoConfig, AutoModel
from mmda.types.document import Document
from mmda.predictors.base_predictors.base_predictor import BasePredictor
class BaseHFPredictor(BasePredictor):
REQUIRED_BACKENDS = ["transformers", "torch"]
def __init__(self, model: Any, config: Any, tokenizer: Any):
self.model = model
self.config = config
self.tokenizer = tokenizer
@classmethod
def from_pretrained(cls, model_name_or_path: str, *args, **kwargs):
config = AutoConfig.from_pretrained(model_name_or_path)
model = AutoModel.from_pretrained(
model_name_or_path, config=config, *args, **kwargs
)
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
return cls(model, config, tokenizer)
@abstractmethod
def preprocess(self, document: Document) -> Dict:
"""Convert the input document into the format that is required
by the model.
"""
@abstractmethod
def postprocess(self, model_outputs: Any) -> Dict:
"""Convert the model outputs into the Annotation format"""
| 1,206 | 32.527778 | 72 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/bibentry_predictor/predictor.py
|
import os
import re
from typing import Dict, List, Optional, Tuple
from optimum.onnxruntime import ORTModelForTokenClassification
import torch
from transformers import AutoConfig, AutoTokenizer, AutoModelForTokenClassification
from unidecode import unidecode
from mmda.predictors.hf_predictors.base_hf_predictor import BasePredictor
from mmda.predictors.hf_predictors.bibentry_predictor import utils
from mmda.predictors.hf_predictors.bibentry_predictor.types import (
BibEntryLabel,
BibEntryPredictionWithSpan,
BibEntryStructureSpanGroups,
StringWithSpan
)
from mmda.types.document import Document
class BibEntryPredictor(BasePredictor):
REQUIRED_BACKENDS = ["transformers", "torch"]
REQUIRED_DOCUMENT_FIELDS = ["tokens", "pages", "bib_entries"]
def __init__(self, model_name_or_path: str):
self.config = AutoConfig.from_pretrained(model_name_or_path)
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
onnx = os.path.exists(os.path.join(model_name_or_path, "model.onnx"))
if onnx:
self.model = ORTModelForTokenClassification.from_pretrained(model_name_or_path, file_name="model.onnx")
else:
self.model = AutoModelForTokenClassification.from_pretrained(model_name_or_path)
self.model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
if not onnx:
# https://stackoverflow.com/a/60018731
self.model.eval() # for some reason the onnx version doesnt have an eval()
def predict(self, document: Document, bibentries_per_run: int = 5) -> BibEntryStructureSpanGroups:
# Recover the (approximate) raw bibentry strings from mmda document
bib_entry_strings = utils.mk_bib_entry_strings(document)
raw_predictions = []
# Do inference in batches to not blow out vram
for i in range(0, len(bib_entry_strings), bibentries_per_run):
batch_strings = bib_entry_strings[i:i+bibentries_per_run]
batch_raw_predictions = self.predict_raw(batch_strings)
raw_predictions += batch_raw_predictions
# Map raw predictions back into valid annotations for passed document
prediction = utils.map_raw_predictions_to_mmda(document.bib_entries, raw_predictions)
return prediction
def predict_raw(self, bib_entries: List[str]) -> List[BibEntryPredictionWithSpan]:
if not bib_entries:
return []
res = []
tokenized_inputs = self.tokenizer(bib_entries, padding=True, truncation=True, return_tensors="pt")
# put the data on the same device of the model.
tokenized_inputs = tokenized_inputs.to(self.model.device)
predictions = self.model(**tokenized_inputs)
pred_ids = predictions.logits.argmax(2).tolist()
num_items = len(bib_entries)
for i in range(num_items):
# Combine token-level prediction into word-level prediction
label_ids = BibEntryPredictor._get_word_level_prediction(tokenized_inputs.word_ids(i), pred_ids[i])
word_ids = [id for id in tokenized_inputs.word_ids(i) if id is not None]
num_words = word_ids[-1] + 1 if word_ids else 0
spans = [tokenized_inputs.word_to_chars(i, word_index) for word_index in range(num_words)]
# Extract output fields from word predictions
res.append(BibEntryPredictor._aggregate_token_level_prediction(bib_entries[i], spans, label_ids))
return res
@staticmethod
def postprocess(pred: BibEntryPredictionWithSpan) -> Dict:
citation_number = pred.citation_number.content if pred.citation_number else None
title = BibEntryPredictor._clean_str(pred.title.content) if pred.title else None
doi = BibEntryPredictor._clean_doi(pred.doi.content) if pred.doi else None
return dict(
citation_number=citation_number,
title=title,
doi=doi
)
@staticmethod
def _get_word_level_prediction(word_ids: List[Optional[int]], predictions: List[int]) -> List[int]:
"""
If a word is split into 2 or more tokens, only take prediction for the first token.
"""
res = []
prev_word_id = None
for word_id, pred in zip(word_ids, predictions):
if word_id is not None and word_id != prev_word_id:
# Tokenization process removes empty string and skips word id, so we're adding it back here
# For example:
# input string list: [' Anon ', '1934', ' ', 'University and Educational Intelligence', ' ', 'Nature', ' ', '133', ' ', '805–805']
# tokenization removes empty string: ['[CLS]', 'an', '##on', '1934', 'university', 'and', 'educational', 'intelligence', 'nature', '133', '80', '##5', '–', '80', '##5', '[SEP]']
# skipping empty string results in skipping word id: [None, 0, 0, 1, 3, 3, 3, 3, 5, 7, 9, 9, 9, 9, 9, None]
# predictions: [0, 9, 9, 0, 8, 9, 8, 8, 9, 0, 13, 13, 13, 13, 13, 4]
if prev_word_id is not None:
for i in range(word_id - (prev_word_id + 1)):
res.append(BibEntryLabel.MISC.value)
res.append(pred)
prev_word_id = word_id
return res
@staticmethod
def _aggregate_token_level_prediction(input: str, spans, label_ids: List[int]) -> BibEntryPredictionWithSpan:
citation_number = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids,
BibEntryLabel.CITATION_NUMBER)
authors = BibEntryPredictor._extract_author_token(input, spans, label_ids)
title = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids, BibEntryLabel.TITLE)
journal = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids,
BibEntryLabel.JOURNAL)
event = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids, BibEntryLabel.EVENT)
journal_venue_or_event = journal if journal else event
year = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids,
BibEntryLabel.ISSUED_YEAR)
doi = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids, BibEntryLabel.DOI)
url = BibEntryPredictor._extract_first_contiguous_label_group_token_level(input, spans, label_ids, BibEntryLabel.URL)
return BibEntryPredictionWithSpan(
citation_number=citation_number,
authors=authors,
title=title,
journal_venue_or_event=journal_venue_or_event,
year=year,
doi=doi,
url=url
)
@staticmethod
def _extract_author_token(input: str, spans, label_ids: List[int]) -> Optional[List[StringWithSpan]]:
res = []
author_span = None
for word_index, label_id in enumerate(label_ids):
# Beginning of new author
if label_id == BibEntryLabel.AUTHOR_START.value and not author_span:
author_span = spans[word_index]
# Middle of current author
elif (
label_id == BibEntryLabel.AUTHOR_START.value or label_id == BibEntryLabel.AUTHOR_MIDDLE.value or label_id == BibEntryLabel.AUTHOR_END.value) and author_span:
current_span = spans[word_index]
author_span = author_span._replace(end=current_span.end)
# End of current author. Close current author span and reset.
elif (
label_id != BibEntryLabel.AUTHOR_START.value and label_id != BibEntryLabel.AUTHOR_MIDDLE.value and label_id != BibEntryLabel.AUTHOR_END.value) and author_span:
res.append(StringWithSpan(
content=input[author_span.start:author_span.end],
start=author_span.start,
end=author_span.end,
))
author_span = None
return res if res else None
@staticmethod
def _extract_first_contiguous_label_group_token_level(
input: str,
spans,
label_ids: List[int],
target_label: BibEntryLabel
) -> Optional[StringWithSpan]:
res = None
existing_span = None
for word_index, label_id in enumerate(label_ids):
if label_id == target_label.value:
# Middle of label span
if existing_span:
current_span = spans[word_index]
existing_span = existing_span._replace(end=current_span.end)
# First label encounter
else:
existing_span = spans[word_index]
# End of label span
elif existing_span:
break
if existing_span:
res = StringWithSpan(
content=input[existing_span.start:existing_span.end],
start=existing_span.start,
end=existing_span.end,
)
return res
@staticmethod
def _clean_str(s: str) -> Optional[str]:
without_diacritics = unidecode(s.strip())
subbed = re.sub("-\s+", "", without_diacritics)
if subbed:
return subbed
else:
return None
@staticmethod
def _clean_doi(doi: str) -> Optional[str]:
lower_trimmed = doi.strip().lower()
if lower_trimmed.startswith("10."):
return re.sub("\s", "", lower_trimmed)
else:
return None
| 9,946 | 43.806306 | 193 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/bibentry_predictor/utils.py
|
from typing import List
from mmda.types.annotation import SpanGroup
from mmda.types.document import Document
from mmda.types.span import Span
from mmda.predictors.hf_predictors.bibentry_predictor.types import BibEntryPredictionWithSpan, BibEntryStructureSpanGroups
_SPAN_JOINER = " "
def mk_bib_entry_strings(document: Document) -> List[str]:
return [_SPAN_JOINER.join(bib_entry.symbols) for bib_entry in document.bib_entries]
def map_raw_predictions_to_mmda(
bib_entries: List[SpanGroup],
raw_preds: List[BibEntryPredictionWithSpan]
) -> BibEntryStructureSpanGroups:
"""
Fussy, and hopefully short-lived logic that can map the spans predicted for a given
bib entry string back into its corresponding MMDA Document.
Underlying predictor operates over bib entry strings, requiring us to:
1. build each string from one or more mmda spans (which may not be contiguous [or even nearby])
2. map the span for each inferred bib entry component back into original document, using
one or more `mmda.types.span.Span`s
"""
prediction = BibEntryStructureSpanGroups()
for i in range(len(bib_entries)):
sg = bib_entries[i]
raw_pred = raw_preds[i]
# Build up relative positions for each SG span within the SG text
intervals = []
curr_total = 0
for span in sg.spans:
i_start = curr_total
curr_total += span.end - span.start
intervals.append((i_start, curr_total))
curr_total += len(_SPAN_JOINER)
def map_raw_span(target, raw_span):
if not raw_span:
return
new_spans = []
cur_pos = raw_span.start
end = raw_span.end
for index, (interval_start, interval_end) in enumerate(intervals):
sg_span = sg.spans[index]
if interval_start <= cur_pos < interval_end:
new_sg_span_start = sg_span.start + (cur_pos - interval_start)
if end >= interval_end:
# Continues into next span, or ends at exact end of this one.
new_sg_span_end = sg_span.end
else:
# Ends in the middle of this span.
new_sg_span_end = new_sg_span_start + end - cur_pos
new_spans.append(Span(start=new_sg_span_start, end=new_sg_span_end))
# Advance our current position, accounting for whitespace before beginning of next span.
cur_pos = interval_end + len(_SPAN_JOINER)
if cur_pos >= end:
break
target.append(SpanGroup(spans=new_spans))
map_raw_span(prediction.bib_entry_number, raw_pred.citation_number)
for author in (raw_pred.authors or []):
map_raw_span(prediction.bib_entry_authors, author)
map_raw_span(prediction.bib_entry_title, raw_pred.title)
map_raw_span(prediction.bib_entry_venue_or_event, raw_pred.journal_venue_or_event)
map_raw_span(prediction.bib_entry_year, raw_pred.year)
map_raw_span(prediction.bib_entry_doi, raw_pred.doi)
map_raw_span(prediction.bib_entry_url, raw_pred.url)
return prediction
| 3,298 | 36.91954 | 122 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/bibentry_predictor/types.py
|
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
from pydantic import BaseModel
from mmda.types.annotation import SpanGroup
class BibEntryLabel(Enum):
MISC = 0
CITATION_NUMBER = 1
AUTHOR_START = 2
AUTHOR_MIDDLE = 3
AUTHOR_END = 4
ISSUED_DAY = 5
ISSUED_MONTH = 6
ISSUED_YEAR = 7
TITLE = 8
JOURNAL = 9
PUBLISHER = 10
VOLUME = 11
ISSUE = 12
PAGE = 13
URL = 14
DOI = 15
EVENT = 16
ISBN = 17
class StringWithSpan(BaseModel):
content: str
start: int # inclusive
end: int # exclusive
class BibEntryPredictionWithSpan(BaseModel):
citation_number: Optional[StringWithSpan]
authors: Optional[List[StringWithSpan]]
title: Optional[StringWithSpan]
journal_venue_or_event: Optional[StringWithSpan]
year: Optional[StringWithSpan]
doi: Optional[StringWithSpan]
url: Optional[StringWithSpan]
@dataclass
class BibEntryStructureSpanGroups:
bib_entry_number: List[SpanGroup] = field(default_factory=list)
bib_entry_authors: List[SpanGroup] = field(default_factory=list)
bib_entry_title: List[SpanGroup] = field(default_factory=list)
bib_entry_venue_or_event: List[SpanGroup] = field(default_factory=list)
bib_entry_year: List[SpanGroup] = field(default_factory=list)
bib_entry_doi: List[SpanGroup] = field(default_factory=list)
bib_entry_url: List[SpanGroup] = field(default_factory=list)
| 1,474 | 23.583333 | 75 |
py
|
mmda
|
mmda-main/src/mmda/predictors/hf_predictors/bibentry_predictor/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/figure_table_predictors.py
|
from collections import defaultdict
from typing import List, Dict, Tuple, Union
import numpy as np
from scipy.optimize import linear_sum_assignment
from tqdm import tqdm
from ai2_internal import api
from mmda.predictors.base_predictors.base_heuristic_predictor import BaseHeuristicPredictor
from mmda.types import SpanGroup, BoxGroup
from mmda.types.document import Document
from mmda.types.span import Span
from mmda.utils.tools import MergeSpans
from ai2_internal.api import Relation
class FigureTablePredictions(BaseHeuristicPredictor):
"""Class for creating a map of figure boxes to figure captions
"""
REQUIRED_DOCUMENT_FIELDS = ['pages', 'tokens', 'vila_span_groups', 'blocks', ]
def __init__(self, document: Document) -> None:
self.doc = document
self.vila_caption_dict = None
self.vila_spans_all_dict = None
self.width_heights_dict = None
self.w_avg, self.h_avg = FigureTablePredictions.get_avg_w_h_of_tokens(self.doc.tokens)
# Parameteer for the fraction of the tokens classified as non-caption that are probably caption in same
# Layoutparser span group
self.FRACTION_OF_MISCLASSIFIED_VILA_CAPTION_TOKENS = 0.3
@staticmethod
def _create_dict_of_pages_spans_vila(span_groups=None) -> Dict[int, List[Span]]:
"""
Create a dictionary of page number to list of spans
Returns: Dict[int, List[Span]] dictionary of page number to list of spans
"""
vila_dict = defaultdict(list)
for entry_caption in span_groups:
for token in entry_caption.tokens:
for span in token.spans:
span.span_id = token.id
span.type = entry_caption.type
vila_dict[span.box.page].append(span)
return vila_dict
@staticmethod
def get_avg_w_h_of_tokens(tokens) -> Tuple[float, float]:
"""
Get the average width and height of tokens
"""
return np.average([[span.box.w, span.box.h] for token in tokens
for span in token.spans], axis=0)
@staticmethod
def _create_dict_of_pages_spans_layoutparser(layoutparser_span_groups, types: List[str] = [], starts_with: str = '',
negation: bool = False) -> Dict[int, List[SpanGroup]]:
"""
Create a dictionary of page number to list of spans, filtering or negating to the types and starts_with
"""
span_map = defaultdict(list)
for span_group in layoutparser_span_groups:
if not types or span_group.box_group.type in types:
if negation:
starts_with_bool = not span_group.text.lower().startswith(starts_with)
else:
starts_with_bool = span_group.text.lower().startswith(starts_with)
if starts_with_bool:
for box in span_group.box_group.boxes:
# Creating unique start, end of spans used as a key for merging boxes
box_api = api.Box.from_mmda(box)
if span_group.spans and len(span_group.spans) == 1:
start, end = span_group.spans[0].start, span_group.spans[0].end
else:
start, end = -9999, -9999
created_span = api.Span(start=start,
end=end,
box=box_api).to_mmda()
created_span.span_id = span_group.id
created_span.box_group_type = span_group.box_group.type
span_map[box.page].append(created_span)
# Bring in the boxes from the span groups
for span in span_group.spans:
box_api = api.Box.from_mmda(span.box)
created_span = api.Span(start=span.start,
end=span.end,
box=box_api).to_mmda()
# Note that hash output is changing everytime it is called
created_span.span_id = f'LP_span_group_{span.box.page}_{len(span_map[span.box.page])}'
created_span.box_group_type = span_group.box_group.type
span_map[span.box.page].append(created_span)
return span_map
@staticmethod
def generate_map_of_layout_to_tokens(
vila_dict, layout_parser_overlap, dict_of_pages_layoutparser,
key='caption') -> Dict[int, Dict]:
"""
Generate a map of layoutparser entries to the list of vila tokens with the type = key vs type != key
"""
for page in vila_dict.keys():
for span in vila_dict[page]:
for layout_span in dict_of_pages_layoutparser.get(page, []):
if span.box.is_overlap(layout_span.box):
id_dict = layout_parser_overlap.get(layout_span.span_id, {'caption': [], 'non_caption': []})
id_dict[key].append(span.span_id)
layout_parser_overlap[layout_span.span_id] = id_dict
return layout_parser_overlap
@staticmethod
def generate_map_of_layout_to_tokens_for_page(
vila_list: List, layout_parser_list: List, key='caption') -> Dict[int, Dict]:
"""
Generate a map of layoutparser tokens ids to the count of vila tokens with the type = key
"""
layout_parser_overlap = dict()
for span in vila_list:
for layout_span in layout_parser_list:
if span.box.is_overlap(layout_span.box):
id_dict = layout_parser_overlap.get(layout_span.span_id, {'caption': [], 'non_caption': []})
if span.type.lower() == key:
id_dict[key].append(span.span_id)
else:
id_dict['non_caption'].append(span.span_id)
layout_parser_overlap[layout_span.span_id] = id_dict
return layout_parser_overlap
def update_vila_caption_dict(self, vila_caption_dict: Dict[int, List[Span]],
vila_non_caption_dict: Dict[int, List[Span]]) -> Dict[int, List[Span]]:
"""
Update the vila caption dict to cast tokens that are misclassified as no captions in ths same LayoutParser
region
"""
layout_parser_overlap = defaultdict(dict)
# Build overlap map between layoutparser and caption tokens
span_map = FigureTablePredictions._create_dict_of_pages_spans_layoutparser(
self.doc.blocks)
layout_parser_overlap = FigureTablePredictions.generate_map_of_layout_to_tokens(
vila_caption_dict, layout_parser_overlap, span_map)
# Build overlap map between layoutparser and non-caption tokens
layout_parser_overlap = FigureTablePredictions.generate_map_of_layout_to_tokens(
vila_non_caption_dict, layout_parser_overlap, span_map, key='non_caption')
for key, value in layout_parser_overlap.items():
caption_token_fraction = len(value['caption']) / (len(value['caption']) + len(value['non_caption']))
if ((1.0 > caption_token_fraction) and
(caption_token_fraction > self.FRACTION_OF_MISCLASSIFIED_VILA_CAPTION_TOKENS)):
for span_id in layout_parser_overlap[key]['non_caption']:
for page, vila_span in vila_non_caption_dict.items():
for entry in vila_span:
if entry.span_id == span_id:
vila_caption_dict[entry.box.page].append(entry)
return vila_caption_dict
@staticmethod
def _filter_span_group(vila_span_groups: List[api.SpanGroup], caption_content: str, span_group_types: List[str],
negation=False) -> List[api.SpanGroup]:
"""
Helper function which filters out span groups based on the caption content and span group type
"""
result = []
for span_group in vila_span_groups:
if span_group.text.replace(' ', '').lower().startswith(caption_content):
if span_group.type in span_group_types and not negation:
result.append(span_group)
elif negation and span_group.type not in span_group_types:
result.append(span_group)
return result
def merge_vila_token_spans(
self, caption_content: str = 'fig', span_group_type: List[str] = ['Caption']) -> Dict[int, List[api.Box]]:
"""
Merging spanGroups
Args:
vila_span_groups (List[api.SpanGroup]): list of span groups from vila to merge
caption_content (str): Caption should contain caption_content value
Returns: Dictionary page -> List of merged boxes
"""
vila_span_groups_filtered = FigureTablePredictions._filter_span_group(
self.doc.vila_span_groups, caption_content=caption_content, span_group_types=span_group_type)
vila_caption_dict = defaultdict(list)
for entry_caption in vila_span_groups_filtered:
for span_group in entry_caption.tokens:
for span in span_group.spans:
vila_caption_dict[span.box.page].append(span)
merged_boxes_list = defaultdict(list)
for page, list_of_boxes in vila_caption_dict.items():
# Merge spans if they are sufficiently close to each other
merged_boxes_list[page] = MergeSpans(list_of_spans=list_of_boxes, w=self.w_avg * 1.5,
h=self.h_avg * 1).merge_neighbor_spans_by_box_coordinate()
return merged_boxes_list
def _cast_to_caption_vila_tokens(self, caption_content='fig'):
"""
Heuristic logic for fixing miss classified tokens as non caption. By checking layoutparser box predictions and
tokens which belong to them, I cast the rest of the tokens to caption category.
Args:
layoutparser_span_groups (List[api.SpanGroup]): list of span groups from layoutparser
vila_span_groups (List[api.SpanGroup]): list of span groups from vila to merge
Returns (List[List[api.SpanGroup]]) list of lists of spangroups which are cast to
"""
# First let's go over all the tokens which are labeled as caption and find the LayoutParser SpanGroups which
# they overlap with
vila_caption = FigureTablePredictions._filter_span_group(
self.doc.vila_span_groups, caption_content=caption_content, span_group_types=['Caption'])
self.vila_caption_dict = FigureTablePredictions._create_dict_of_pages_spans_vila(vila_caption)
vila_non_caption = FigureTablePredictions._filter_span_group(
self.doc.vila_span_groups, caption_content='', span_group_types=['Caption'], negation=True)
vila_non_caption_dict = FigureTablePredictions._create_dict_of_pages_spans_vila(vila_non_caption)
return self.update_vila_caption_dict(self.vila_caption_dict, vila_non_caption_dict)
def merge_boxes(self, layoutparser_span_groups: List[api.SpanGroup],
merged_boxes_vila_dict: Dict[int, List[api.Box]] = None,
types: List[str] = ['Figure']) -> Dict[int, List[api.Box]]:
"""
Merges overlapping boxes. Vila caption predictions is more consistent than layout parser prediction, thus
we check the number of items after the merge with the number of caption boxes.
Args:
layoutparser_span_groups (List[api.SpanGroup]): list of span groups from layoutparser
merged_boxes_vila_dict (List[api.SpanGroup]): list of span groups for the merged vila tokens assigned to
the class caption
types (List[str]): List of types of the spangroups to merge
Returns: Dictionary of the merged figure boxes.
"""
if merged_boxes_vila_dict is None:
merged_boxes_vila_dict = defaultdict(list)
merged_boxes_vila_dict_left = defaultdict(list)
merged_boxes_map = defaultdict(list)
span_map = FigureTablePredictions._create_dict_of_pages_spans_layoutparser(
layoutparser_span_groups, types=types)
for page, span_list in span_map.items():
# Adding vila spans to the layout parser list of the spans
if merged_boxes_vila_dict[page]:
span_list.extend(merged_boxes_vila_dict_left[page])
merged_spans = (MergeSpans(span_list, w=self.w_avg * 0.5, h=self.h_avg * 1.0)
.merge_neighbor_spans_by_box_coordinate())
# Filtering out vila spans (not merged)
if len(span_list) != len(merged_spans) and merged_boxes_vila_dict and merged_boxes_vila_dict[page]:
merged_spans = [merged_span for merged_span in merged_spans if not any(
vila_span.box.to_json() == merged_span.box.to_json() for vila_span in merged_boxes_vila_dict[page])]
merged_boxes_vila_dict_left[page] = [vila_span for vila_span in merged_boxes_vila_dict[page] if any(
vila_span.box.to_json() == merged_span.box.to_json() for merged_span in merged_spans)]
if merged_boxes_vila_dict_left[page]:
merged_boxes_vila_dict[page] = merged_boxes_vila_dict_left[page]
merged_boxes_map[page] = merged_spans
return merged_boxes_map, merged_boxes_vila_dict
@staticmethod
def _get_object_caption_distance(figure_box: api.Box, caption_box: api.Box) -> float:
"""
Return 900.0 if left point of figure, caption is offset more than 10%
Otherwise returns distance middle of the figure box and caption box
Args:
figure_box (api.Box): Box corresponding to figure
caption_box (api.Box): Box corresponding to caption
Returns: Distance between center of the box and caption location
"""
l_fig, t_fig = figure_box.l + figure_box.w / 2, figure_box.t + figure_box.h / 2
l_cap, t_cap = caption_box.l + caption_box.w / 2, caption_box.t + caption_box.h
if abs(l_fig - l_cap) / l_fig > 0.1:
return 900.0
return t_cap - t_fig
def get_layout_span_groups_starts_with(self, caption_content: str = 'fig', vila_spans: dict = None):
"""
"""
spans_to_merge_dict = defaultdict(list)
self.vila_caption_dict = self._cast_to_caption_vila_tokens(caption_content=caption_content)
if vila_spans:
for page_idx, vila_span in vila_spans.items():
spans_to_merge_dict[page_idx].extend(
vila_span)
layout_parser_span_groups_dict = defaultdict(list)
if vila_spans:
for page_idx, vila_span in vila_spans.items():
layout_parser_span_groups_dict[page_idx].extend(
vila_span)
return layout_parser_span_groups_dict
def generate_candidates(self) -> Tuple[Union[SpanGroup, BoxGroup]]:
"""
Generates candidates for the figure and table captions
"""
assert self.doc.vila_span_groups
merged_boxes_caption_fig_tab_dict = {}
for caption_content in ['fig', 'tab']:
# Merge vila tokens which start with caption_content
merged_boxes_caption_fig_tab_dict[caption_content] = self.merge_vila_token_spans(
caption_content=caption_content)
merged_boxes_caption_fig_tab_dict[caption_content] = self.get_layout_span_groups_starts_with(
caption_content=caption_content, vila_spans=merged_boxes_caption_fig_tab_dict[caption_content])
# Final check that the defined captions are starting with tab and fig
for page_idx, list_of_spans in merged_boxes_caption_fig_tab_dict[caption_content].items():
for span in list_of_spans:
if not self.doc.symbols[span.start:span.end].lower().startswith(caption_content):
list_of_spans.remove(span)
merged_boxes_caption_fig_tab_dict[caption_content][page_idx] = list_of_spans
# merged_boxes_vila_dict is used in figure, table boxes derivation
merged_boxes_vila_dict = self.merge_vila_token_spans(
caption_content='', span_group_type=['Text', 'Paragraph', 'Table', 'Figure'])
# Create dictionary of layoutparser span groups merging boxgroups and boxes
merged_boxes_vila_dict_left = None
merged_boxes_fig_tab_dict = {}
# List of types to be merged from layoutparser, note that sometimes figures are marked as Equations
for layout_parser_box_type in ([['Figure'], ['Table']]):
merged_boxes_vila_dict = (merged_boxes_vila_dict_left
if merged_boxes_vila_dict_left is not None else merged_boxes_vila_dict)
merged_boxes_fig_tab_dict[layout_parser_box_type[0]], merged_boxes_vila_dict_left = self.merge_boxes(
layoutparser_span_groups=self.doc.blocks,
types=layout_parser_box_type,
merged_boxes_vila_dict=merged_boxes_vila_dict)
return (merged_boxes_caption_fig_tab_dict['fig'], merged_boxes_fig_tab_dict['Figure'],
merged_boxes_caption_fig_tab_dict['tab'], merged_boxes_fig_tab_dict['Table'])
def _predict(
self, merged_boxes_caption_dict, merged_boxes_fig_tab_dict, caption_type
) -> Dict[str, Union[SpanGroup, BoxGroup, Relation]]:
"""
Merges boxes corresponding to tokens of table, figure captions. For each page each caption/object create cost
matrix which is distance based on get_object_caption_distance. Using linear_sum_assignment find corresponding
pairs, caption-object
Args:
doc (Document): document to make predictions on, it has to have fields layoutparser_span_groups and
vila_span_groups
caption_type (str): caption type to make prediction for can be Figure or Table
Returns: Returns dictionary with keys 'predictions', 'predictions_captions', 'predictions_relations'
"""
predictions = []
predictions_captions = []
predictions_relations = []
for page in range(len(tqdm(self.doc.pages))):
if merged_boxes_caption_dict.get(page) and merged_boxes_fig_tab_dict.get(page):
cost_matrix = np.zeros(
(len(merged_boxes_fig_tab_dict[page]),
len(merged_boxes_caption_dict[page])))
for j, fig_box in enumerate(merged_boxes_fig_tab_dict[page]):
for i, span_group in enumerate(merged_boxes_caption_dict[page]):
caption_box = span_group.box
assert hasattr(fig_box, 'box')
distance = FigureTablePredictions._get_object_caption_distance(
fig_box.box, caption_box)
cost_matrix[j][i] = distance
if caption_type == 'Figure':
cost_matrix[j][i] = distance if distance > 0 else 900
row_ind, col_ind = linear_sum_assignment(cost_matrix)
for row, col in zip(row_ind, col_ind):
# Check that caption starts with tab or fig
if self.doc.symbols[
merged_boxes_caption_dict[page][col].start:
merged_boxes_caption_dict[page][col].end].lower().startswith(caption_type.lower()[:3]):
span_group = SpanGroup(spans=[Span(
start=merged_boxes_caption_dict[page][col].start,
end=merged_boxes_caption_dict[page][col].end)],
id=len(predictions_captions)
)
box_group = BoxGroup(boxes=[merged_boxes_fig_tab_dict[page][row].box], id=len(predictions))
predictions.append(box_group)
predictions_captions.append(span_group)
predictions_relations.append(Relation(from_id=box_group.id, to_id=span_group.id))
return {f'{caption_type.lower()}s': predictions, f'{caption_type.lower()}_captions': predictions_captions,
f'{caption_type.lower()}_to_{caption_type.lower()}_captions': predictions_relations}
def predict(self) -> Dict[str, Union[SpanGroup, BoxGroup, Relation]]:
"""
Returns: Dictionary List[SpanGroup], SpanGroup has start, end corresponding to caption start, end indexes and box
corresponding to merged boxes of the tokens of the caption. Type is one of ['Figure', 'Table']. BoxGroup stores
information about the boundaries of figure or table. Relation stores information about the relation between
caption and the object it corresponds to
"""
(merged_boxes_caption_fig_dict,
merged_boxes_fig_dict, merged_boxes_caption_tab_dict, merged_boxes_tab_dict) = self.generate_candidates()
result_dict = {}
result_dict.update(self._predict(merged_boxes_caption_fig_dict, merged_boxes_fig_dict, caption_type='Figure'))
result_dict.update(self._predict(merged_boxes_caption_tab_dict, merged_boxes_tab_dict, caption_type='Table'))
return result_dict
| 21,673 | 51.992665 | 121 |
py
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/dictionary_word_predictor.py
|
"""
DictionaryWordPredictor -- Reads `tokens` and converts them into whole `words`.
Let's consider 4 consecutive rows:
This is a few-shot learn-
ing paper. We try few-
shot techniques. These
methods are useful.
This predictor tries to:
1. merge tokens ["learn", "-", "ing"] into "learning"
2. merge tokens ["few", "-", "shot"] into "few-shot"
3. keep tokens ["These", "methods"] separate
4. keep tokens ["useful", "."] separate
This technique requires 2 passes through the data:
1. Build a dictionary of valid words, e.g. if "learning" was ever used, then we can merge
["learn", "-", "ing"].
2. Classify every pair of tokens as belonging to the *same* or *different* words.
@kylel, @rauthur
"""
import os
from typing import Optional, Set, List, Tuple, Iterable, Dict
from collections import defaultdict
from mmda.parsers import PDFPlumberParser
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.predictors.heuristic_predictors.whitespace_predictor import WhitespacePredictor
from mmda.types import Metadata, Document, Span, SpanGroup
from mmda.types.names import RowsField, TokensField
class Dictionary:
def __init__(self, words: Iterable[str], punct: str):
self.words = set()
self.punct = punct
for word in words:
self.add(word)
def add(self, text: str) -> None:
self.words.add(self.strip_punct(text=text.strip().lower()))
def is_in(self, text: str, strip_punct=True) -> bool:
if strip_punct:
return self.strip_punct(text=text.strip().lower()) in self.words
else:
return text.strip().lower() in self.words
def strip_punct(self, text: str) -> str:
start = 0
while start < len(text) and text[start] in self.punct:
start += 1
end = len(text) - 1
while text[end] in self.punct and end > 0:
end -= 1
return text[start: end + 1]
class DictionaryWordPredictor(BasePredictor):
REQUIRED_BACKENDS = None
REQUIRED_DOCUMENT_FIELDS = [RowsField, TokensField]
def __init__(
self,
dictionary_file_path: Optional[str] = None,
punct: Optional[str] = PDFPlumberParser.DEFAULT_PUNCTUATION_CHARS
) -> None:
"""Build a predictor that indexes the given dictionary file.
A dictionary is simply a case-sensitive list of words as a text file.
Words should be lower-case in the dictionary unless they are invalid
as a lower-case word (e.g., a person's name).
For an example see https://github.com/dwyl/english-words (words_alpha.txt) or
check the `tests/fixtures/example-dictionary.txt` file.
The above example file contains base words, plurals, past-tense versions, etc.
Thus the heuristics here do not do any changes to word structure other than
basics:
- Combine hyphenated words and see if they are in the dictionary
- Strip plural endings "(s)" and punctuation
Args:
dictionary_file_path (str): [description]
punct (str): [description]
"""
self.dictionary_file_path = dictionary_file_path
self.punct = punct
self._dictionary = Dictionary(words=[], punct=punct)
if self.dictionary_file_path:
if os.path.exists(self.dictionary_file_path):
with open(self.dictionary_file_path, 'r') as f_in:
for line in f_in:
self._dictionary.add(line)
else:
raise FileNotFoundError(f'{self.dictionary_file_path}')
self.whitespace_predictor = WhitespacePredictor()
def predict(self, document: Document) -> List[SpanGroup]:
"""Get words from a document as a list of SpanGroup.
Args:
document (Document): The document to process
Raises:
ValueError: If rows are found that do not contain any tokens
Returns:
list[SpanGroup]: SpanGroups where hyphenated words are joined.
Casing and punctuation are preserved. Hyphenated words are
only joined across row boundaries.
Usage:
>>> doc = # a Document with rows ("Please provide cus-", "tom models.")
>>> predictor = DictionaryWordPredictor(dictionary_file_path="/some/file.txt")
>>> words = predictor.predict(doc)
>>> [w.text for w in words]
"Please provide custom models."
"""
self._doc_field_checker(document)
# 1) whitespace tokenize document & compute 'adjacent' token_ids
token_id_to_token_ids = self._precompute_whitespace_tokens(document=document)
# 2) precompute features about each token specific to whether it's
# start/end of a row, or whether it corresponds to punctuation
row_start_after_hyphen_token_ids, row_end_with_hyphen_token_ids, \
max_row_end_token_id_to_min_row_start_token_id, punct_r_strip_candidate_token_ids, \
punct_l_strip_candidate_token_ids = \
self._precompute_token_features(
document=document,
token_id_to_token_ids=token_id_to_token_ids
)
# 3) build dictionary
internal_dictionary = self._build_internal_dictionary(
document=document,
token_id_to_token_ids=token_id_to_token_ids,
row_start_after_hyphen_token_ids=row_start_after_hyphen_token_ids,
row_end_with_hyphen_token_ids=row_end_with_hyphen_token_ids
)
# 4) predict words for using token features
token_id_to_word_id, word_id_to_text = self._predict_tokens(
document=document,
internal_dictionary=internal_dictionary,
token_id_to_token_ids=token_id_to_token_ids,
row_start_after_hyphen_token_ids=row_start_after_hyphen_token_ids,
row_end_with_hyphen_token_ids=row_end_with_hyphen_token_ids,
max_row_end_token_id_to_min_row_start_token_id=max_row_end_token_id_to_min_row_start_token_id,
punct_r_strip_candidate_token_ids=punct_r_strip_candidate_token_ids,
punct_l_strip_candidate_token_ids=punct_l_strip_candidate_token_ids
)
# 5) transformation
words: List[SpanGroup] = self._convert_to_words(
document=document,
token_id_to_word_id=token_id_to_word_id,
word_id_to_text=word_id_to_text
)
# 6) cleanup
document.remove(field_name='_ws_tokens')
return words
def _precompute_whitespace_tokens(self, document: Document) -> Dict:
"""
`whitespace_tokenization` is necessary because lack of whitespace is an indicator that
adjacent tokens belong in a word together.
"""
_ws_tokens: List[SpanGroup] = self.whitespace_predictor.predict(document=document)
document.annotate(_ws_tokens=_ws_tokens)
# token -> ws_tokens
token_id_to_ws_token_id = {}
for token in document.tokens:
token_id_to_ws_token_id[token.id] = token._ws_tokens[0].id
# ws_token -> tokens
ws_token_id_to_tokens = defaultdict(list)
for token_id, ws_token_id in token_id_to_ws_token_id.items():
ws_token_id_to_tokens[ws_token_id].append(token_id)
# token -> all cluster tokens
token_id_to_token_ids = {}
for token_id, ws_token_id in token_id_to_ws_token_id.items():
candidate_token_ids = [i for i in ws_token_id_to_tokens[ws_token_id]]
token_id_to_token_ids[token_id] = candidate_token_ids
return token_id_to_token_ids
def _precompute_token_features(
self,
document: Document,
token_id_to_token_ids
) -> Tuple:
"""
Compute stuff necessary for dictionary-building and/or merging tokens into words.
1. `beginning|end_of_row|page` is necessary because row transitions are often where tokens
should be merged into a word. Knowing this also helps with determining what are "safe"
words to add to dictionary.
2. `punctuation` in `start_of_row` tokens is necessary because we may need to keep them
as separate tokens even if there is a word merge (e.g. the semicolon "fine-tuning;")
"""
# beginning/end of row w/ hyphen
# TODO: add pages too
row_end_with_hyphen_token_ids = set()
row_start_after_hyphen_token_ids = set()
max_row_end_token_id_to_min_row_start_token_id = {}
for i in range(0, len(document.tokens) - 1):
current = document.tokens[i]
next = document.tokens[i + 1]
is_transition = current.rows[0].id != next.rows[0].id
has_hyphen = current._ws_tokens[0].text.endswith('-')
has_prefix = current._ws_tokens[0].text != '-' # avoids cases where "-" by itself
if is_transition and has_hyphen and has_prefix:
row_end_token_ids = sorted([token.id for token in current._ws_tokens[0].tokens])
row_start_token_ids = sorted([token.id for token in next._ws_tokens[0].tokens])
for i in row_end_token_ids:
row_end_with_hyphen_token_ids.add(i)
for j in row_start_token_ids:
row_start_after_hyphen_token_ids.add(j)
max_row_end_token_id_to_min_row_start_token_id[
max(row_end_token_ids)
] = min(row_start_token_ids)
# also, keep track of potential punct token_ids to right-strip (e.g. ',' in 'models,')
# should apply to all tokens except those at end of a row
punct_r_strip_candidate_token_ids = set()
for token in document.tokens:
candidate_token_ids = token_id_to_token_ids[token.id]
if len(candidate_token_ids) > 1:
# r-strip logic. keep checking trailing tokens for punct; stop as soon as not
if token.id not in row_end_with_hyphen_token_ids:
for k in candidate_token_ids[::-1]:
if document.tokens[k].text in self._dictionary.punct:
punct_r_strip_candidate_token_ids.add(k)
else:
break
# also track of potential punct token_ids to left-strip (e.g. '(' in '(BERT)')
# should apply to all tokens.
# avoid tracking cases where it's all punctuation (e.g. '...')
punct_l_strip_candidate_token_ids = set()
for token in document.tokens:
candidate_token_ids = token_id_to_token_ids[token.id]
is_multiple_tokens_wout_whitespace = len(candidate_token_ids) > 1
is_entirely_punctuation = all([
document.tokens[i].text in self._dictionary.punct for i in candidate_token_ids
])
if is_multiple_tokens_wout_whitespace and not is_entirely_punctuation:
# l-strip logic. keep checking prefix tokens for punct; stop as soon as not
for k in candidate_token_ids:
if document.tokens[k].text in self._dictionary.punct:
punct_l_strip_candidate_token_ids.add(k)
else:
break
return row_start_after_hyphen_token_ids, \
row_end_with_hyphen_token_ids, \
max_row_end_token_id_to_min_row_start_token_id, \
punct_r_strip_candidate_token_ids, \
punct_l_strip_candidate_token_ids
def _build_internal_dictionary(
self,
document: Document,
token_id_to_token_ids,
row_start_after_hyphen_token_ids,
row_end_with_hyphen_token_ids
) -> Dictionary:
"""dictionary of possible words"""
internal_dictionary = Dictionary(words=self._dictionary.words, punct=self.punct)
for token in document.tokens:
if token.id in row_end_with_hyphen_token_ids:
continue
if token.id in row_start_after_hyphen_token_ids:
continue
candidate_text = ''.join(
[document.tokens[i].text for i in token_id_to_token_ids[token.id]]
)
internal_dictionary.add(candidate_text)
return internal_dictionary
def _predict_tokens(
self,
document: Document,
internal_dictionary: Dictionary,
token_id_to_token_ids,
row_start_after_hyphen_token_ids,
row_end_with_hyphen_token_ids,
max_row_end_token_id_to_min_row_start_token_id,
punct_r_strip_candidate_token_ids,
punct_l_strip_candidate_token_ids
) -> Tuple[Dict, Dict]:
token_id_to_word_id = {token.id: None for token in document.tokens}
word_id_to_token_ids = defaultdict(list)
word_id_to_text = {}
# easy case first! most words aren't split & are their own tokens
for token in document.tokens:
clustered_token_ids = token_id_to_token_ids[token.id]
if (
not token.id in row_end_with_hyphen_token_ids and
not token.id in row_start_after_hyphen_token_ids and
len(clustered_token_ids) == 1
):
token_id_to_word_id[token.id] = token.id
word_id_to_token_ids[token.id].append(token.id)
word_id_to_text[token.id] = token.text
else:
pass
# loop through remaining tokens. start with ones without row split, as that's easier.
for token in document.tokens:
if (
not token.id in row_end_with_hyphen_token_ids and
not token.id in row_start_after_hyphen_token_ids and
token_id_to_word_id[token.id] is None
):
# calculate 2 versions of the text to check against dictionary:
# one version is raw concatenate all adjacent tokens
# another version right-strips punctuation after concatenating
clustered_token_ids = token_id_to_token_ids[token.id]
first_token_id = min(clustered_token_ids)
candidate_text = ''.join([document.tokens[i].text for i in clustered_token_ids])
clustered_token_ids_r_strip_punct = [
i for i in clustered_token_ids
if i not in punct_r_strip_candidate_token_ids
]
candidate_text_strip_punct = ''.join([
document.tokens[i].text for i in clustered_token_ids_r_strip_punct
])
# if concatenated tokens are in dictionary as-is, take them as a single word
if internal_dictionary.is_in(text=candidate_text, strip_punct=False):
for i in clustered_token_ids:
token_id_to_word_id[i] = first_token_id
word_id_to_token_ids[first_token_id].append(i)
word_id_to_text[first_token_id] = candidate_text
# otherwise, default is to take all adjacent tokens (w/out whitespace between them)
# as a single word & strip punctuation
else:
for i in clustered_token_ids_r_strip_punct:
token_id_to_word_id[i] = first_token_id
word_id_to_token_ids[first_token_id].append(i)
word_id_to_text[first_token_id] = candidate_text_strip_punct
for i in clustered_token_ids:
if i in punct_r_strip_candidate_token_ids:
token_id_to_word_id[i] = i
word_id_to_token_ids[i].append(i)
word_id_to_text[i] = document.tokens[i].text
else:
pass
# finally, handle tokens that are split across rows
for token in document.tokens:
if (
token.id in max_row_end_token_id_to_min_row_start_token_id and
token_id_to_word_id[token.id] is None
):
# calculate 4 versions of the text to check against dictionary:
# 1. one version is raw concatenate all adjacent tokens
# 2. another version right-strips punctuation after concatenating
# 3. you can also do a raw concatenation *after* removing bridging '-' character
# 4. and you can remove the '-' as well as perform a right-strip of punctuation
start_token_ids = token_id_to_token_ids[token.id]
first_token_id = min(start_token_ids)
end_token_ids = token_id_to_token_ids[
max_row_end_token_id_to_min_row_start_token_id[token.id]
]
end_token_ids_strip_punct = [
i for i in end_token_ids if i not in punct_r_strip_candidate_token_ids
]
start_text = ''.join([document.tokens[i].text for i in start_token_ids])
end_text = ''.join([document.tokens[i].text for i in end_token_ids])
end_text_strip_punct = ''.join([
document.tokens[i].text for i in end_token_ids_strip_punct
])
assert start_text[-1] == '-'
candidate_text = start_text + end_text
candidate_text_strip_punct = start_text + end_text_strip_punct
candidate_text_no_hyphen = start_text[:-1] + end_text
candidate_text_strip_punct_no_hyphen = start_text[:-1] + end_text_strip_punct
# if concatenated tokens are in dictionary as-is, take them as a single word
if internal_dictionary.is_in(text=candidate_text, strip_punct=False):
for i in start_token_ids + end_token_ids:
token_id_to_word_id[i] = first_token_id
word_id_to_token_ids[first_token_id].append(i)
word_id_to_text[first_token_id] = candidate_text
# if concatenated tokens wout hyphen are in dictionary
elif internal_dictionary.is_in(text=candidate_text_no_hyphen, strip_punct=False):
for i in start_token_ids + end_token_ids:
token_id_to_word_id[i] = first_token_id
word_id_to_token_ids[first_token_id].append(i)
word_id_to_text[first_token_id] = candidate_text_no_hyphen
# if concatenated tokens wout hyphen *AND* right-strip punct are in dict..
elif internal_dictionary.is_in(text=candidate_text_strip_punct_no_hyphen,
strip_punct=False):
for i in start_token_ids + end_token_ids_strip_punct:
token_id_to_word_id[i] = first_token_id
word_id_to_token_ids[first_token_id].append(i)
word_id_to_text[first_token_id] = candidate_text_strip_punct_no_hyphen
for i in end_token_ids:
if i in punct_r_strip_candidate_token_ids:
token_id_to_word_id[i] = i
word_id_to_token_ids[i].append(i)
word_id_to_text[i] = document.tokens[i].text
# if concatenated tokens are *NOT* in dictionary, default behavior is
# to concatenate anyways, keeping hyphen, and stripping punctuation as
# separate tokens
else:
for i in start_token_ids + end_token_ids_strip_punct:
token_id_to_word_id[i] = first_token_id
word_id_to_token_ids[first_token_id].append(i)
word_id_to_text[first_token_id] = candidate_text_strip_punct
for i in end_token_ids:
if i in punct_r_strip_candidate_token_ids:
token_id_to_word_id[i] = i
word_id_to_token_ids[i].append(i)
word_id_to_text[i] = document.tokens[i].text
else:
pass
# 2022-12; we need to handle cases like '(CS)' where the word starts with a punct "("
# we actually do want this as a separate word. but under the above logic, we would've
# assigned "(" and "CS" the same word ID.
# this part identifies words that begin with punctuation, and splits them.
for token in document.tokens:
if token.id in punct_l_strip_candidate_token_ids:
# capture current state, before fixing
word_id = token_id_to_word_id[token.id]
word_text = word_id_to_text[word_id]
other_same_word_token_ids = [
i for i in word_id_to_token_ids[token_id_to_word_id[token.id]]
if token_id_to_word_id[i] == word_id and i != token.id
]
new_first_token_id = min(other_same_word_token_ids)
# update this punctuation token to be its own word
word_id_to_text[word_id] = token.text
word_id_to_token_ids[word_id] = [token.id]
# update subsequent tokens that were implicated. fix their word_id. fix the text.
for other_token_id in other_same_word_token_ids:
token_id_to_word_id[other_token_id] = new_first_token_id
word_id_to_token_ids[new_first_token_id] = other_same_word_token_ids
word_id_to_text[new_first_token_id] = word_text.lstrip(token.text)
# this data structure has served its purpose by this point
del word_id_to_token_ids
# edge case handling. there are cases (e.g. tables) where each cell is detected as its own
# row. This is super annoying but *shrug*. In these cases, a cell "-" followed by another
# cell "48.9" can be represented as 2 adjacent rows. This can cause the token for "48"
# to be implicated in `row_start_after_hyphen_token_ids`, and thus the tokens "48.9"
# wouldn't be processed under the Second module above... But it also wouldnt be processed
# under the Third module above because the preceding hyphen "-" wouldn't have made it to
# `row_end_with_hyphen_token_ids` (as it's by itself).
# Anyways... this case is soooooo specific that for now, the easiest thing is to just
# do a final layer of passing over unclassified tokens & assigning word_id based on
# whitespace.
#
# 2022-12: actually this may not be needed anymore after modifying featurization function
# to avoid considering cases where a row only contains a single hyphen.
# commented out for now.
#
# for token in document.tokens:
# if token_id_to_word_id[token.id] is None:
# clustered_token_ids = token_id_to_token_ids[token.id]
# first_token_id = min(clustered_token_ids)
# candidate_text = ''.join([document.tokens[i].text for i in clustered_token_ids])
# for i in clustered_token_ids:
# token_id_to_word_id[i] = first_token_id
# word_id_to_text[first_token_id] = candidate_text
# are there any unclassified tokens?
assert None not in token_id_to_word_id.values()
return token_id_to_word_id, word_id_to_text
def _convert_to_words(
self,
document: Document,
token_id_to_word_id,
word_id_to_text
) -> List[SpanGroup]:
words = []
tokens_in_word = [document.tokens[0]]
current_word_id = 0
for token_id in range(1, len(token_id_to_word_id)):
token = document.tokens[token_id]
word_id = token_id_to_word_id[token_id]
if word_id == current_word_id:
tokens_in_word.append(token)
else:
word = SpanGroup(
spans=[span for token in tokens_in_word for span in token.spans],
id=current_word_id,
metadata=Metadata(text=word_id_to_text[current_word_id])
)
words.append(word)
tokens_in_word = [token]
current_word_id = word_id
# last bit
word = SpanGroup(
spans=[span for token in tokens_in_word for span in token.spans],
id=current_word_id,
metadata=Metadata(text=word_id_to_text[current_word_id])
)
words.append(word)
return words
| 24,983 | 46.953935 | 106 |
py
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/section_header_predictor.py
|
"""
SectionHeaderPredictor -- Use PDF outline metadata to predict section headers and
levels. This predictor is entirely heuristic and only applies to PDFs that have ToC
information in the sidebar. See SectionNestingPredictor for a related class that
operates over token predictions to yield an outline of sections.
Adapted from https://github.com/rauthur/pdf-outlines-extraction
@rauthur
"""
from collections import defaultdict
from dataclasses import dataclass
from functools import partial
from typing import Dict, List
from layoutparser.tools.shape_operations import (
generalized_connected_component_analysis_1d,
)
from mmda.eval.metrics import levenshtein
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.types.annotation import Span, SpanGroup
from mmda.types.box import Box
from mmda.types.document import Document
from mmda.types.metadata import Metadata
from mmda.types.names import PagesField, TokensField
from mmda.utils.outline_metadata import Outline, OutlineItem
@dataclass
class _BoxWithText:
span: Span
box: Box
text: str
def _doc_has_no_outlines(doc: Document) -> bool:
return "outline" not in doc.metadata or len(doc.metadata.outline) == 0
def _parse_outline_metadata(doc: Document) -> Outline:
return Outline.from_metadata_dict(doc.metadata)
def _outlines_to_page_index(outline: Outline) -> Dict[int, List[OutlineItem]]:
results = defaultdict(list)
for item in outline.items:
results[item.page].append(item)
return results
def _guess_box_dimensions(spans: List[Span], index: int, outline: OutlineItem) -> Box:
"""Use this method to expand a pointer to a location in a PDF to a guesstimate box
that represents a full target location for a Box after clicking a ToC entry. In
other words, this box is roughly on the PDF page where PDF software would scroll to
if clicking the sidebar entry. It makes use of the surrounding token boxes to try to
capture a reasonable area.
Args:
page (SpanGroup): The page object from a PDF parser
index (int): The page index from 0
outline (OutlineMetadata): Rehydrated OutlineMetadata object from querier
Returns:
Box: A box that approximately points to the ToC location of interest
"""
box = Box(
l=outline.l,
t=outline.t,
w=0.25 if outline.l > 0 else 1.0, # 25% to the right if left else 100% of page
h=0.10, # 10% to the bottom
page=index,
)
boxes: List[Box] = [s.box for s in spans]
# Consider tokens below the top of the box
# Consider tokens within left/right boundaries
# Take the closest top here and use as bottom
borderline = min(
*[
b.t
for b in boxes
if b.t + 0.01 > box.t and b.l + 0.01 > box.l and b.l < box.l + box.w
]
)
# Add a small fudge factor and shrink the top since we have a better box
box.t = borderline - 0.005
box.h = 0.01
return box
def _x_in_thresh(a: Box, b: Box, thresh) -> bool:
if a.is_overlap(b):
return True
items = sorted([a, b], key=lambda x: x.l)
return items[1].l - (items[0].l + items[0].w) <= thresh
def _y_in_thresh(a: Box, b: Box, thresh) -> bool:
if a.is_overlap(b):
return True
items = sorted([a, b], key=lambda x: x.t)
return items[1].t - (items[0].t + items[0].h) <= thresh
def _edge_threshold(
a: _BoxWithText, b: _BoxWithText, x_thresh: float, y_thresh: float
) -> int:
return int(
_x_in_thresh(a.box, b.box, x_thresh) and _y_in_thresh(a.box, b.box, y_thresh)
)
_lscore = partial(levenshtein, case_sensitive=False, strip_spaces=True, normalize=True)
def _find_best_candidate(
candidates: List[List[_BoxWithText]], outline: OutlineItem
) -> List[_BoxWithText]:
best_candidate = candidates[0]
best_text = "".join([x.text for x in best_candidate])
best_score = _lscore(outline.title, best_text)
if len(candidates) == 1:
return best_candidate
for other_candidate in candidates[1:]:
other_text = "".join(x.text for x in other_candidate)
other_score = _lscore(outline.title, other_text)
if other_score < best_score:
best_candidate = other_candidate
best_score = other_score
best_text = other_text
return best_candidate
MAGIC_TOKEN = "[^^ SHP_TARGET ^^]"
class SectionHeaderPredictor(BasePredictor):
REQUIRED_BACKENDS = None
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField]
_x_threshold: float
_y_threshold: float
def __init__(
self,
_x_threshold: float = 0.015,
_y_threshold: float = 0.005,
) -> None:
self._x_threshold = _x_threshold
self._y_threshold = _y_threshold
def predict(self, document: Document) -> List[SpanGroup]:
"""Get section headers in a Document as a list of SpanGroup.
Args:
doc (Document): The document to process
Returns:
list[SpanGroup]: SpanGroups that appear to be headers based on outline
metadata in the PDF (i.e., ToC or sidebar headers).
"""
if _doc_has_no_outlines(document):
return []
self._doc_field_checker(document)
outlines = _parse_outline_metadata(document)
page_to_outlines = _outlines_to_page_index(outlines)
predictions: List[SpanGroup] = []
for i, page in enumerate(document.pages):
tokens: List[SpanGroup] = page.tokens
spans: List[Span] = [s for t in tokens for s in t.spans]
for outline in page_to_outlines[i]:
box: Box = _guess_box_dimensions(spans, i, outline)
text_boxes: List[_BoxWithText] = [
_BoxWithText(
span=span,
box=span.box,
text=document.symbols[span.start : span.end],
)
for span in spans
if (
span.box.t + 0.005 > box.t
and span.box.t + span.box.h < box.t + 0.25
)
]
text_boxes.append(_BoxWithText(span=None, box=box, text=MAGIC_TOKEN))
components: List[
List[_BoxWithText]
] = generalized_connected_component_analysis_1d(
text_boxes,
partial(
_edge_threshold,
x_thresh=self._x_threshold,
y_thresh=self._y_threshold,
),
)
for component in components:
component_texts = [x.text for x in component]
if MAGIC_TOKEN not in component_texts:
continue
magic_token = component[-1]
# Filter out chars that start above the target token
filtered = [x for x in component if x.box.t >= magic_token.box.t]
# Prune target since we no longer need this
filtered = [x for x in filtered if x.text != MAGIC_TOKEN]
# Try to find the best of a few different filters
# Initial candidate is simply all linked tokens
# Additional candidates could use things like font name and size
candidates = [
[x for x in filtered],
]
# Add candidate that drops tokens to the left if non-zero left
if magic_token.box.l > 0:
candidates.append(
[x for x in filtered if x.box.l + 0.01 > magic_token.box.l]
)
# If all tokens are filtered out then we did not find a match
if len(candidates) == 0:
continue
best_candidate = _find_best_candidate(candidates, outline)
metadata = Metadata(level=outline.level, title=outline.title)
predictions.append(
SpanGroup(
spans=[x.span for x in best_candidate], metadata=metadata
)
)
return predictions
| 8,439 | 31.337165 | 88 |
py
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/grobid_citation_predictor.py
|
"""
@rauthur
"""
import io
import xml.etree.ElementTree as et
from typing import Optional
import requests
# processCitationList available in Grobid 0.7.1-SNAPSHOT and later
DEFAULT_API = "http://localhost:8070/api/processCitation"
NS = {"tei": "http://www.tei-c.org/ns/1.0"}
def _post_document(citations: str, url: str = DEFAULT_API) -> str:
req = requests.post(url, data={"citations": citations, "includeRawCitations": "1"})
if req.status_code != 200:
raise RuntimeError(f"Unable to process citations. Received {req.status_code}!")
return req.text
def get_title(citations: str, url: str = DEFAULT_API) -> Optional[str]:
xml = _post_document(citations, url)
root = et.parse(io.StringIO(xml)).getroot()
matches = root.findall(".//title")
if len(matches) == 0:
return None
if not matches[0].text:
return None
return matches[0].text.strip()
| 912 | 22.410256 | 87 |
py
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/sentence_boundary_predictor.py
|
from typing import List, Tuple
import itertools
import pysbd
import numpy as np
from mmda.types.annotation import SpanGroup
from mmda.types.span import Span
from mmda.types.document import Document
from mmda.types.names import PagesField, TokensField, WordsField
from mmda.predictors.base_predictors.base_heuristic_predictor import (
BaseHeuristicPredictor,
)
def merge_neighbor_spans(spans: List[Span], distance=1) -> List[Span]:
"""Merge neighboring spans in a list of un-overlapped spans:
when the gaps between neighboring spans is not larger than the
specified distance, they are considered as the neighbors.
Args:
spans (List[Span]): The input list of spans.
distance (int, optional):
The upper bound of interval gaps between two neighboring spans.
Defaults to 1.
Returns:
List[Span]: A list of merged spans
"""
is_neighboring_spans = (
lambda span1, span2: min(
abs(span1.start - span2.end), abs(span1.end - span2.start)
)
<= distance
)
# It assumes non-overlapped intervals within the list
def merge_neighboring_spans(span1, span2):
return Span(min(span1.start, span2.start), max(span1.end, span2.end))
spans = sorted(spans, key=lambda ele: ele.start)
# When sorted, only one iteration round is needed.
if len(spans) == 0:
return []
if len(spans) == 1:
return spans
cur_merged_spans = [spans[0]]
for cur_span in spans[1:]:
prev_span = cur_merged_spans.pop()
if is_neighboring_spans(cur_span, prev_span):
cur_merged_spans.append(
merge_neighboring_spans(prev_span, cur_span))
else:
# In this case, the prev_span should be moved to the
# bottom of the stack
cur_merged_spans.extend([prev_span, cur_span])
return cur_merged_spans
class PysbdSentenceBoundaryPredictor(BaseHeuristicPredictor):
"""Sentence Boundary based on Pysbd
Examples:
>>> doc: Document = parser.parse("path/to/pdf")
>>> predictor = PysbdSentenceBoundaryPredictor()
>>> sentence_spans = predictor.predict(doc)
>>> doc.annotate(sentences=sentence_spans)
"""
REQUIRED_BACKENDS = ["pysbd"]
REQUIRED_DOCUMENT_FIELDS = [PagesField, TokensField] # type: ignore
def __init__(self) -> None:
self._segmenter = pysbd.Segmenter(
language="en", clean=False, char_span=True)
def split_token_based_on_sentences_boundary(
self, words: List[str]
) -> List[Tuple[int, int]]:
"""
Split a list of words into a list of (start, end) indices, indicating
the start and end of each sentence.
Duplicate of https://github.com/allenai/VILA/\blob/dd242d2fcbc5fdcf05013174acadb2dc896a28c3/src/vila/dataset/preprocessors/layout_indicator.py#L14 # noqa: E501
Returns: List[Tuple(int, int)]
a list of (start, end) for token indices within each sentence
"""
if len(words) == 0:
return [(0, 0)]
combined_words = " ".join(words)
char2token_mask = np.zeros(len(combined_words), dtype=np.int64)
acc_word_len = 0
for idx, word in enumerate(words):
word_len = len(word) + 1
char2token_mask[acc_word_len: acc_word_len + word_len] = idx
acc_word_len += word_len
segmented_sentences = self._segmenter.segment(combined_words)
sent_boundary = [(ele.start, ele.end) for ele in segmented_sentences]
split = []
token_id_start = 0
for (start, end) in sent_boundary:
token_id_end = char2token_mask[start:end].max()
if (
end + 1 >= len(char2token_mask)
or char2token_mask[end + 1] != token_id_end
):
token_id_end += 1 # (Including the end)
split.append((token_id_start, token_id_end))
token_id_start = token_id_end
return split
def predict(self, doc: Document) -> List[SpanGroup]:
if hasattr(doc, WordsField):
words = [
word.text for word in getattr(doc, WordsField)
]
attr_name = WordsField
# `words` is preferred as it should has better reading
# orders and text representation
else:
words = [token.text for token in doc.tokens]
attr_name = TokensField
split = self.split_token_based_on_sentences_boundary(words)
sentence_spans = []
for (start, end) in split:
if end - start == 0:
continue
if end - start < 0:
raise ValueError
cur_spans = getattr(doc, attr_name)[start:end]
all_token_spans = list(
itertools.chain.from_iterable([ele.spans for ele in cur_spans])
)
sentence_spans.append(
SpanGroup(spans=merge_neighbor_spans(all_token_spans))
)
return sentence_spans
| 5,096 | 31.673077 | 172 |
py
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/whitespace_predictor.py
|
"""
Uses a whitespace tokenizer on Document.symbols to predict which `tokens` were originally
part of the same segment/chunk (e.g. "few-shot" if tokenized as ["few", "-", "shot"]).
@kylel
"""
from typing import Optional, Set, List, Tuple
import tokenizers
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.types import Metadata, Document, SpanGroup, Span, BoxGroup
from mmda.types.names import TokensField
class WhitespacePredictor(BasePredictor):
REQUIRED_BACKENDS = None
REQUIRED_DOCUMENT_FIELDS = [TokensField]
_dictionary: Optional[Set[str]] = None
def __init__(self) -> None:
self.whitespace_tokenizer = tokenizers.pre_tokenizers.WhitespaceSplit()
def predict(self, document: Document) -> List[SpanGroup]:
self._doc_field_checker(document)
# 1) whitespace tokenization on symbols. each token is a nested tuple ('text', (start, end))
ws_tokens: List[Tuple] = self.whitespace_tokenizer.pre_tokenize_str(document.symbols)
# 2) filter to just the chunks that are greater than 1 token. Reformat.
# chunks = []
# for text, (start, end) in ws_tokens:
# overlapping_tokens = document.find_overlapping(
# query=SpanGroup(spans=[Span(start=start, end=end)]),
# field_name=Tokens
# )
# if len(overlapping_tokens) > 1:
# chunk = SpanGroup(spans=[Span(start=start, end=end)], metadata=Metadata(text=text))
# chunks.append(chunk)
chunks = []
for i, (text, (start, end)) in enumerate(ws_tokens):
chunk = SpanGroup(spans=[Span(start=start, end=end)],
metadata=Metadata(text=text),
id=i)
chunks.append(chunk)
return chunks
| 1,840 | 35.82 | 101 |
py
|
mmda
|
mmda-main/src/mmda/predictors/heuristic_predictors/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/recipes/core_recipe.py
|
"""
@kylel
"""
import logging
logger = logging.getLogger(__name__)
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.hf_predictors.token_classification_predictor import (
IVILATokenClassificationPredictor,
)
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.predictors.sklearn_predictors.svm_word_predictor import SVMWordPredictor
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.recipes.recipe import Recipe
from mmda.types import *
class CoreRecipe(Recipe):
def __init__(
self,
effdet_publaynet_predictor_path: str = "lp://efficientdet/PubLayNet",
effdet_mfd_predictor_path: str = "lp://efficientdet/MFD",
vila_predictor_path: str = "allenai/ivila-row-layoutlm-finetuned-s2vl-v2",
svm_word_predictor_path: str = "https://ai2-s2-research-public.s3.us-west-2.amazonaws.com/mmda/models/svm_word_predictor.tar.gz",
):
logger.info("Instantiating recipe...")
self.parser = PDFPlumberParser()
self.rasterizer = PDF2ImageRasterizer()
self.word_predictor = SVMWordPredictor.from_path(svm_word_predictor_path)
self.effdet_publaynet_predictor = LayoutParserPredictor.from_pretrained(
effdet_publaynet_predictor_path
)
self.effdet_mfd_predictor = LayoutParserPredictor.from_pretrained(
effdet_mfd_predictor_path
)
self.vila_predictor = IVILATokenClassificationPredictor.from_pretrained(
vila_predictor_path
)
logger.info("Finished instantiating recipe")
def from_path(self, pdfpath: str) -> Document:
logger.info("Parsing document...")
doc = self.parser.parse(input_pdf_path=pdfpath)
logger.info("Rasterizing document...")
images = self.rasterizer.rasterize(input_pdf_path=pdfpath, dpi=72)
doc.annotate_images(images=images)
logger.info("Predicting words...")
words = self.word_predictor.predict(document=doc)
doc.annotate(words=words)
logger.info("Predicting blocks...")
layout = self.effdet_publaynet_predictor.predict(document=doc)
equations = self.effdet_mfd_predictor.predict(document=doc)
# we annotate layout info in the document
doc.annotate(layout=layout)
# list annotations separately
doc.annotate(equations=equations)
# blocks are used by IVILA, so we need to annotate them as well
doc.annotate(blocks=layout + equations)
logger.info("Predicting vila...")
vila_span_groups = self.vila_predictor.predict(document=doc)
doc.annotate(vila_span_groups=vila_span_groups)
return doc
| 2,718 | 34.776316 | 137 |
py
|
mmda
|
mmda-main/src/mmda/recipes/__init__.py
|
from mmda.recipes.core_recipe import CoreRecipe
__all__ = [
'CoreRecipe'
]
| 79 | 15 | 47 |
py
|
mmda
|
mmda-main/src/mmda/recipes/recipe.py
|
"""
@kylel
"""
from mmda.types import *
from abc import abstractmethod
class Recipe:
@abstractmethod
def from_path(self, pdfpath: str) -> Document:
raise NotImplementedError
@abstractmethod
def from_doc(self, doc: Document) -> Document:
raise NotImplementedError
| 303 | 13.47619 | 50 |
py
|
mmda
|
mmda-main/src/mmda/featurizers/citation_link_featurizers.py
|
import numpy as np
import pandas as pd
from pydantic import BaseModel
import re
from thefuzz import fuzz
from typing import List, Tuple, Dict
from mmda.types.annotation import SpanGroup
DIGITS = re.compile(r'[0-9]+')
ALPHA = re.compile(r'[A-Za-z]+')
RELEVANT_PUNCTUATION = re.compile(r"\(|\)|\[|,|\]|\.|&|\;")
FUZZ_RATIO = "fuzz_ratio"
JACCARD_1GRAM = "jaccard_1gram"
JACCARD_2GRAM = "jaccard_2gram"
JACCARD_3GRAM = "jaccard_3gram"
JACCARD_4GRAM = "jaccard_4gram"
HEURISTIC = "heuristic"
HAS_SOURCE_TEXT = "has_source_text"
JACCARD_NUMERIC = "jaccard_numeric"
MATCH_NUMERIC = "match_numeric"
JACCARD_ALPHA = "jaccard_alpha"
MATCH_FIRST_TOKEN = "match_first_token"
FIRST_POSITION = "first_position"
class CitationLink:
def __init__(self, mention: SpanGroup, bib: SpanGroup):
self.mention = mention
self.bib = bib
def to_text_dict(self) -> Dict[str, str]:
return {"source_text": " ".join(self.mention.symbols), "target_text": " ".join(self.bib.symbols)}
def featurize(possible_links: List[CitationLink]) -> pd.DataFrame:
# create dataframe
df = pd.DataFrame.from_records([link.to_text_dict() for link in possible_links])
df[FUZZ_RATIO] = df.apply(lambda row: fuzz.ratio(row['source_text'], row['target_text']), axis=1)
df[JACCARD_1GRAM] = df.apply(lambda row: jaccardify(row['source_text'], row['target_text'], 1), axis=1)
df[JACCARD_2GRAM] = df.apply(lambda row: jaccardify(row['source_text'], row['target_text'], 2), axis=1)
df[JACCARD_3GRAM] = df.apply(lambda row: jaccardify(row['source_text'], row['target_text'], 3), axis=1)
df[JACCARD_4GRAM] = df.apply(lambda row: jaccardify(row['source_text'], row['target_text'], 4), axis=1)
df[HEURISTIC] = df.apply(lambda row: match_source_tokens(row['source_text'], row['target_text']), axis=1)
df[HAS_SOURCE_TEXT] = df.apply(lambda row: has_source_text(row['source_text']), axis=1)
df[JACCARD_NUMERIC] = df.apply(lambda row: jaccard_numeric(row['source_text'], row['target_text']), axis=1)
df[MATCH_NUMERIC] = df.apply(lambda row: match_numeric(row['source_text'], row['target_text']), axis=1)
df[JACCARD_ALPHA] = df.apply(lambda row: jaccard_alpha(row['source_text'], row['target_text']), axis=1)
df[MATCH_FIRST_TOKEN] = df.apply(lambda row: match_first_token(row['source_text'], row['target_text']), axis=1)
df[FIRST_POSITION] = df.apply(lambda row: first_position(row['source_text'], row['target_text']), axis=1)
# drop text columns
X_features = df.drop(columns=['source_text', 'target_text'])
return X_features
def first_position(source: str, target: str) -> float:
truncated_target = target[:50]
source_tokens = strip_and_tokenize(source)
target_tokens = strip_and_tokenize(truncated_target)
if not source_tokens:
return np.nan
else:
first_source_token = source_tokens[0]
if first_source_token in target_tokens:
return target_tokens.index(first_source_token)
else:
return np.nan
def ngramify(s: str, n: int) -> List[str]:
s_len = len(s)
return [s[i:i+n] for i in range(s_len-n+1)]
def jaccard_ngram(ngrams1: List[str], ngrams2: List[str]) -> float:
if ngrams1 or ngrams2:
s1 = set(ngrams1)
s2 = set(ngrams2)
return len(s1.intersection(s2)) / len(s1.union(s2))
else:
return 0.0
def jaccardify(source: str, target: str, n: int) -> float:
truncated_target = target[:50]
source_ngrams = ngramify(source, n)
target_ngrams = ngramify(truncated_target, n)
return jaccard_ngram(source_ngrams, target_ngrams)
def has_source_text(source: str) -> int:
if source.strip():
return 1
else:
return 0
def jaccard_numeric(source: str, target: str) -> float:
source_numerics = re.findall(DIGITS, source)
truncated_target = target[:100]
target_numerics = re.findall(DIGITS, truncated_target)
return jaccard_ngram(source_numerics, target_numerics)
def match_numeric(source: str, target: str) -> float:
source_numerics = re.findall(DIGITS, source)
truncated_target = target[:100]
target_numerics = re.findall(DIGITS, truncated_target)
token_found = []
for number in source_numerics:
found = number in target_numerics
token_found.append(found)
if False not in token_found:
return 1
else:
return 0
def jaccard_alpha(source: str, target: str) -> float:
source_alpha = re.findall(ALPHA, source)
truncated_target = target[:50]
target_alpha = re.findall(ALPHA, truncated_target)
return jaccard_ngram(source_alpha, target_alpha)
# predicts mention/bib entry matches by matching normalized source tokens
# examples returning True:
# source_text = "[78]"
# target_text = "[78]. C. L. Willis and S. L. Miertschin. Mind maps..."
# source_text = "(Wilkinson et al., 2017)"
# target_text = "Wilkinson, R., Quigley, Q., and Marimba, P. Time means nothing. Journal of Far-Fetched Hypotheses, 2017."
#
# examples returning False:
# source_text = "[3]"
# target_text = "[38] J. Koch, A. Lucero, L. Hegemann, and A. Oulas..."
# source_text = "(Shi 2020)"
# target_text = "Shi, X. Vanilla Ice Cream Is the Best. Epic Assertions, 2021"
# some failure modes: no source text; source text ranges such as "[13-15]";
# incomplete source text such as ", 2019)"; bib entry text with both item and page numbers
def strip_and_tokenize(text: str) -> List[str]:
stripped_text = RELEVANT_PUNCTUATION.sub("", text)
return stripped_text.lower().strip().split()
def match_source_tokens(source: str, target: str) -> float:
if not source:
return 0
else:
source_tokens = strip_and_tokenize(source)
target_tokens = strip_and_tokenize(target)
token_found = []
for token in source_tokens:
if token != 'et' and token != 'al' and token != 'and':
found = token in target_tokens
token_found.append(found)
if False not in token_found:
return 1
else:
return 0
def match_first_token(source: str, target: str) -> float:
truncated_target = target[:50]
source_tokens = strip_and_tokenize(source)
target_tokens = strip_and_tokenize(truncated_target)
if not source_tokens:
return 0
else:
first_source_token = source_tokens[0]
if first_source_token in target_tokens:
return 1
else:
return 0
| 6,480 | 36.680233 | 122 |
py
|
mmda
|
mmda-main/src/mmda/featurizers/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/types/document.py
|
"""
"""
import itertools
import logging
import warnings
from typing import Dict, Iterable, List, Optional
from mmda.types.annotation import Annotation, BoxGroup, SpanGroup
from mmda.types.image import PILImage
from mmda.types.indexers import Indexer, SpanGroupIndexer
from mmda.types.metadata import Metadata
from mmda.types.names import ImagesField, MetadataField, SymbolsField
from mmda.utils.tools import MergeSpans, allocate_overlapping_tokens_for_box, box_groups_to_span_groups
class Document:
SPECIAL_FIELDS = [SymbolsField, ImagesField, MetadataField]
UNALLOWED_FIELD_NAMES = ["fields"]
def __init__(self, symbols: str, metadata: Optional[Metadata] = None):
self.symbols = symbols
self.images = []
self.__fields = []
self.__indexers: Dict[str, Indexer] = {}
self.metadata = metadata if metadata else Metadata()
@property
def fields(self) -> List[str]:
return self.__fields
# TODO: extend implementation to support DocBoxGroup
def find_overlapping(self, query: Annotation, field_name: str) -> List[Annotation]:
if not isinstance(query, SpanGroup):
raise NotImplementedError(
f"Currently only supports query of type SpanGroup"
)
return self.__indexers[field_name].find(query=query)
def add_metadata(self, **kwargs):
"""Copy kwargs into the document metadata"""
for k, value in kwargs.items():
self.metadata.set(k, value)
def annotate(
self, is_overwrite: bool = False, **kwargs: Iterable[Annotation]
) -> None:
"""Annotate the fields for document symbols (correlating the annotations with the
symbols) and store them into the papers.
"""
# 1) check validity of field names
for field_name in kwargs.keys():
assert (
field_name not in self.SPECIAL_FIELDS
), f"The field_name {field_name} should not be in {self.SPECIAL_FIELDS}."
if field_name in self.fields:
# already existing field, check if ok overriding
if not is_overwrite:
raise AssertionError(
f"This field name {field_name} already exists. To override, set `is_overwrite=True`"
)
elif field_name in dir(self):
# not an existing field, but a reserved class method name
raise AssertionError(
f"The field_name {field_name} should not conflict with existing class properties"
)
# Kyle's preserved comment:
# Is it worth deepcopying the annotations? Safer, but adds ~10%
# overhead on large documents.
# 2) register fields into Document
for field_name, annotations in kwargs.items():
if len(annotations) == 0:
warnings.warn(f"The annotations is empty for the field {field_name}")
setattr(self, field_name, [])
self.__fields.append(field_name)
continue
annotation_types = {type(a) for a in annotations}
assert (
len(annotation_types) == 1
), f"Annotations in field_name {field_name} more than 1 type: {annotation_types}"
annotation_type = annotation_types.pop()
if annotation_type == SpanGroup:
span_groups = self._annotate_span_group(
span_groups=annotations, field_name=field_name
)
elif annotation_type == BoxGroup:
# TODO: not good. BoxGroups should be stored on their own, not auto-generating SpanGroups.
span_groups = self._annotate_span_group(
span_groups=box_groups_to_span_groups(annotations, self), field_name=field_name
)
else:
raise NotImplementedError(
f"Unsupported annotation type {annotation_type} for {field_name}"
)
# register fields
setattr(self, field_name, span_groups)
self.__fields.append(field_name)
def remove(self, field_name: str):
delattr(self, field_name)
self.__fields = [f for f in self.__fields if f != field_name]
del self.__indexers[field_name]
def annotate_images(
self, images: Iterable[PILImage], is_overwrite: bool = False
) -> None:
if not is_overwrite and len(self.images) > 0:
raise AssertionError(
"This field name {Images} already exists. To override, set `is_overwrite=True`"
)
if len(images) == 0:
raise AssertionError("No images were provided")
image_types = {type(a) for a in images}
assert len(image_types) == 1, f"Images contain more than 1 type: {image_types}"
image_type = image_types.pop()
if not issubclass(image_type, PILImage):
raise NotImplementedError(
f"Unsupported image type {image_type} for {ImagesField}"
)
self.images = images
def _annotate_span_group(
self, span_groups: List[SpanGroup], field_name: str
) -> List[SpanGroup]:
"""Annotate the Document using a bunch of span groups.
It will associate the annotations with the document symbols.
"""
assert all([isinstance(group, SpanGroup) for group in span_groups])
# 1) add Document to each SpanGroup
for span_group in span_groups:
span_group.attach_doc(doc=self)
# 2) Build fast overlap lookup index
self.__indexers[field_name] = SpanGroupIndexer(span_groups)
return span_groups
#
# to & from JSON
#
def to_json(self, fields: Optional[List[str]] = None, with_images=False) -> Dict:
"""Returns a dictionary that's suitable for serialization
Use `fields` to specify a subset of groups in the Document to include (e.g. 'sentences')
If `with_images` is True, will also turn the Images into base64 strings. Else, won't include them.
Output format looks like
{
symbols: "...",
field1: [...],
field2: [...],
metadata: {...}
}
"""
doc_dict = {SymbolsField: self.symbols, MetadataField: self.metadata.to_json()}
if with_images:
doc_dict[ImagesField] = [image.to_json() for image in self.images]
# figure out which fields to serialize
fields = (
self.fields if fields is None else fields
) # use all fields unless overridden
# add to doc dict
for field in fields:
doc_dict[field] = [
doc_span_group.to_json() for doc_span_group in getattr(self, field)
]
return doc_dict
@classmethod
def from_json(cls, doc_dict: Dict) -> "Document":
# 1) instantiate basic Document
symbols = doc_dict[SymbolsField]
doc = cls(symbols=symbols, metadata=Metadata(**doc_dict.get(MetadataField, {})))
if Metadata in doc_dict:
doc.add_metadata(**doc_dict[Metadata])
images_dict = doc_dict.get(ImagesField, None)
if images_dict:
doc.annotate_images(
[PILImage.frombase64(image_str) for image_str in images_dict]
)
# 2) convert span group dicts to span gropus
field_name_to_span_groups = {}
for field_name, span_group_dicts in doc_dict.items():
if field_name not in doc.SPECIAL_FIELDS:
span_groups = [
SpanGroup.from_json(span_group_dict=span_group_dict)
for span_group_dict in span_group_dicts
]
field_name_to_span_groups[field_name] = span_groups
# 3) load annotations for each field
doc.annotate(**field_name_to_span_groups)
return doc
| 8,030 | 36.180556 | 108 |
py
|
mmda
|
mmda-main/src/mmda/types/box.py
|
"""
"""
from typing import List, Dict, Tuple, Union
from dataclasses import dataclass
import warnings
import numpy as np
def is_overlap_1d(start1: float, end1: float, start2: float, end2: float, x: float = 0) -> bool:
"""Return whether two 1D intervals overlaps given x"""
assert start1 <= end1
assert start2 <= end2
return not (start1 - x > end2 or start1 > end2 + x or end1 + x < start2 or end1 < start2 - x) # ll # rr
@dataclass
class Box:
l: float
t: float
w: float
h: float
page: int
def to_json(self) -> Dict[str, float]:
return {'left': self.l, 'top': self.t, 'width': self.w, 'height': self.h, 'page': self.page}
@classmethod
def from_json(cls, box_dict: Dict[str, Union[float, int]]) -> "Box":
return Box(l=box_dict['left'], t=box_dict['top'], w=box_dict['width'], h=box_dict['height'],
page=box_dict['page'])
@classmethod
def from_coordinates(cls, x1: float, y1: float, x2: float, y2: float, page: int):
return cls(x1, y1, x2 - x1, y2 - y1, page)
@classmethod
def from_pdf_coordinates(
cls,
x1: float,
y1: float,
x2: float,
y2: float,
page_width: float,
page_height: float,
page: int,
):
"""
Convert PDF coordinates to absolute coordinates.
The difference between from_pdf_coordinates and from_coordinates is that this function
will perform extra checks to ensure the coordinates are valid, i.e.,
0<= x1 <= x2 <= page_width and 0<= y1 <= y2 <= page_height.
"""
_x1, _x2 = np.clip([x1, x2], 0, page_width)
_y1, _y2 = np.clip([y1, y2], 0, page_height)
if _x2 < _x1:
_x2 = _x1
if _y2 < _y1:
_y2 = _y1
if (_x1, _y1, _x2, _y2) != (x1, y1, x2, y2):
warnings.warn(
f"The coordinates ({x1}, {y1}, {x2}, {y2}) are not valid and converted to ({_x1}, {_y1}, {_x2}, {_y2})."
)
return cls(_x1, _y1, _x2 - _x1, _y2 - _y1, page)
@classmethod
def small_boxes_to_big_box(cls, boxes: List["Box"]) -> "Box":
"""Computes one big box that tightly encapsulates all smaller input boxes"""
boxes = [box for box in boxes if box is not None]
if not boxes:
return None
if len({box.page for box in boxes}) != 1:
raise ValueError(f"Bboxes not all on same page: {boxes}")
x1 = min([bbox.l for bbox in boxes])
y1 = min([bbox.t for bbox in boxes])
x2 = max([bbox.l + bbox.w for bbox in boxes])
y2 = max([bbox.t + bbox.h for bbox in boxes])
return Box(page=boxes[0].page, l=x1, t=y1, w=x2 - x1, h=y2 - y1)
@property
def coordinates(self) -> Tuple[float, float, float, float]:
"""Return a tuple of the (x1, y1, x2, y2) format."""
return self.l, self.t, self.l + self.w, self.t + self.h
@property
def center(self) -> Tuple[float, float]:
return self.l + self.w / 2, self.t + self.h / 2
@property
def xywh(self) -> Tuple[float, float, float, float]:
"""Return a tuple of the (left, top, width, height) format."""
return self.l, self.t, self.w, self.h
def get_relative(self, page_width: float, page_height: float) -> "Box":
"""Get the relative coordinates of self based on page_width, page_height."""
return self.__class__(
l=float(self.l) / page_width,
t=float(self.t) / page_height,
w=float(self.w) / page_width,
h=float(self.h) / page_height,
page=self.page,
)
def get_absolute(self, page_width: int, page_height: int) -> "Box":
"""Get the absolute coordinates of self based on page_width, page_height."""
return self.__class__(
l=self.l * page_width,
t=self.t * page_height,
w=self.w * page_width,
h=self.h * page_height,
page=self.page,
)
def is_overlap(self, other: "Box", x: float = 0.0, y: float = 0, center: bool = False) -> bool:
"""
Whether self overlaps with the other Box object.
x, y distances for padding
center (bool) if True, only consider overlapping if this box's center is contained by other
"""
x11, y11, x12, y12 = self.coordinates
x21, y21, x22, y22 = other.coordinates
if center:
center_x, center_y = self.center
res = is_overlap_1d(center_x, center_x, x21, x22, x) and is_overlap_1d(center_y, center_y, y21, y22, y)
else:
res = is_overlap_1d(x11, x12, x21, x22, x) and is_overlap_1d(y11, y12, y21, y22, y)
return res
| 4,742 | 33.369565 | 120 |
py
|
mmda
|
mmda-main/src/mmda/types/image.py
|
"""
Monkey patch the PIL.Image methods to add base64 conversion
"""
import base64
from io import BytesIO
from PIL import Image as pilimage
from PIL.Image import Image as PILImage
def tobase64(self):
# Ref: https://stackoverflow.com/a/31826470
buffered = BytesIO()
self.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue())
return img_str.decode("utf-8")
def frombase64(img_str):
# Use the same naming style as the original Image methods
buffered = BytesIO(base64.b64decode(img_str))
img = pilimage.open(buffered)
return img
PILImage.tobase64 = tobase64 # This is the method applied to individual Image classes
PILImage.to_json = tobase64 # Use the same API as the others
PILImage.frombase64 = frombase64 # This is bind to the module, used for loading the images
| 832 | 24.242424 | 90 |
py
|
mmda
|
mmda-main/src/mmda/types/user_data.py
|
"""
UserData and HasUserData allow a Python class to have an underscore `_` property for
accessing custom fields. Data captured within this property can be serialized along with
any instance of the class.
"""
from typing import Any, Callable, Dict, Optional
class UserData:
_data: Dict[str, Any]
_callback: Optional[Callable[[Any], None]]
def __init__(self, after_set_callback: Callable[[Any], None] = None):
# Use object.__setattr__ to avoid loop on self.__setattr__ during init
object.__setattr__(self, "_data", dict())
object.__setattr__(self, "_callback", after_set_callback)
def __setattr__(self, name: str, value: Any) -> None:
if object.__getattribute__(self, name):
raise ValueError(f"Cannot set reserved name {name}!")
self._data.__setitem__(name, value)
if not self._callback:
return
self._callback(name, value)
def __delattr__(self, name: str) -> None:
self._data.__delitem__(name)
def __getattr__(self, name: str) -> Any:
return self._data[name]
def keys(self):
return self._data.keys()
class HasUserData:
_user_data: UserData
def __init__(self, after_set_callback=None):
self._user_data = UserData(after_set_callback=after_set_callback)
@property
def _(self):
return self._user_data
| 1,376 | 26.54 | 88 |
py
|
mmda
|
mmda-main/src/mmda/types/metadata.py
|
from copy import deepcopy
from dataclasses import MISSING, Field, fields, is_dataclass
from functools import wraps
import inspect
import logging
from typing import (
Any,
Callable,
Dict,
Iterable,
Optional,
Tuple,
Type,
TypeVar,
Union,
overload,
)
__all__ = ["store_field_in_metadata", "Metadata"]
class _DEFAULT:
# object to keep track if a default value is provided when getting
# or popping a key from Metadata
...
class Metadata:
"""An object that contains metadata for an annotation.
It supports dot access and dict-like access."""
def __init__(self, **kwargs):
for k, v in kwargs.items():
self.set(k, v)
@overload
def get(self, key: str) -> Any:
"""Get value with name `key` in metadata"""
...
@overload
def get(self, key: str, default: Any) -> Any:
"""Get value with name `key` in metadata"""
...
def get(self, key: str, default: Optional[Any] = _DEFAULT) -> Any:
"""Get value with name `key` in metadata;
if not found, return `default` if specified,
otherwise raise `None`"""
if key in self.__dict__:
return self.__dict__[key]
elif default != _DEFAULT:
return default
else:
logging.warning(f"{key} not found in metadata")
return None
def has(self, key: str) -> bool:
"""Check if metadata contains key `key`; return `True` if so,
`False` otherwise"""
return key in self.__dict__
def set(self, key: str, value: Any) -> None:
"""Set `key` in metadata to `value`; key must be a valid Python
identifier (that is, a valid variable name) otherwise,
raise a ValueError"""
if not key.isidentifier():
raise ValueError(
f"`{key}` is not a valid variable name, "
"so it cannot be used as key in metadata"
)
self.__dict__[key] = value
@overload
def pop(self, key: str) -> Any:
"""Remove & returns value for `key` from metadata;
raise `KeyError` if not found"""
...
@overload
def pop(self, key: str, default: Any) -> Any:
"""Remove & returns value for `key` from metadata;
if not found, return `default`"""
...
def pop(self, key: str, default: Optional[Any] = _DEFAULT) -> Any:
"""Remove & returns value for `key` from metadata;
if not found, return `default` if specified,
otherwise raise `KeyError`"""
if key in self.__dict__:
return self.__dict__.pop(key)
elif default != _DEFAULT:
return default
else:
raise KeyError(f"{key} not found in metadata")
def keys(self) -> Iterable[str]:
"""Return an iterator over the keys in metadata"""
return self.__dict__.keys()
def values(self) -> Iterable[Any]:
"""Return an iterator over the values in metadata"""
return self.__dict__.values()
def items(self) -> Iterable[Tuple[str, Any]]:
"""Return an iterator over <key, value> pairs in metadata"""
return self.__dict__.items()
# Interfaces from loading/saving to dictionary
def to_json(self) -> Dict[str, Any]:
"""Return a dict representation of metadata"""
return deepcopy(self.__dict__)
@classmethod
def from_json(cls, di: Dict[str, Any]) -> "Metadata":
"""Create a Metadata object from a dict representation"""
metadata = cls()
for k, v in di.items():
metadata.set(k, v)
return metadata
# The following methods are to ensure equality between metadata
# with same keys and values
def __len__(self) -> int:
return len(self.__dict__)
def __eq__(self, __o: object) -> bool:
if not isinstance(__o, Metadata):
return False
if len(self) != len(__o):
return False
for k in __o.keys():
if k not in self.keys() or self[k] != __o[k]:
return False
return True
# The following methods are for compatibility with the dict interface
def __contains__(self, key: str) -> bool:
return self.has(key)
def __iter__(self) -> Iterable[str]:
return self.keys()
def __getitem__(self, key: str) -> Any:
return self.get(key)
def __setitem__(self, key: str, value: Any) -> None:
return self.set(key, value)
# The following methods are for compatibility with the dot access interface
def __getattr__(self, key: str) -> Any:
return self.get(key)
def __setattr__(self, key: str, value: Any) -> None:
return self.set(key, value)
def __delattr__(self, key: str) -> Any:
return self.pop(key)
# The following methods return a nice representation of the metadata
def __repr__(self) -> str:
return f"Metadata({repr(self.__dict__)})"
def __str__(self) -> str:
return f"Metadata({str(self.__dict__)})"
# Finally, we need to support pickling/copying
def __deepcopy__(self, memo: Dict[int, Any]) -> "Metadata":
return Metadata.from_json(deepcopy(self.__dict__, memo))
T = TypeVar("T")
def store_field_in_metadata(
field_name: str,
getter_fn: Optional[Callable[[T], Any]] = None,
setter_fn: Optional[Callable[[T, Any], None]] = None,
) -> Callable[[Type[T]], Type[T]]:
"""This decorator is used to store a field that was previously part of
a dataclass in a metadata attribute, while keeping it accessible as an
attribute using the .field_name notation. Example:
@store_field_in_metadata('field_a')
@dataclass
class MyDataclass:
metadata: Metadata = field(default_factory=Metadata)
field_a: int = 3
field_b: int = 4
d = MyDataclass()
print(d.field_a) # 3
print(d.metadata) # Metadata({'field_a': 3})
print(d) # MyDataclass(field_a=3, field_b=4, metadata={'field_a': 3})
d = MyDataclass(field_a=5)
print(d.field_a) # 5
print(d.metadata) # Metadata({'field_a': 5})
print(d) # MyDataclass(field_a=5, field_b=4, metadata={'field_a': 5})
Args:
field_name: The name of the field to store in the metadata.
getter_fn: A function that takes the dataclass instance and
returns the value of the field. If None, the field's value is
looked up from the metadata dictionary.
setter_fn: A function that takes the dataclass instance and a value
for the field and sets it. If None, the field's value is added
to the metadata dictionary.
"""
def wrapper_fn(
cls_: Type[T],
wrapper_field_name: str = field_name,
wrapper_getter_fn: Optional[Callable[[T], Any]] = getter_fn,
wrapper_setter_fn: Optional[Callable[[T, Any], None]] = setter_fn,
) -> Type[T]:
"""
This wrapper consists of three steps:
1. Basic checks to determine if a field can be stored in the metadata.
This includes checking that cls_ is a dataclass, that cls_ has a
metadata attribute, and that the field is a field of cls_.
2. Wrap the init method of cls_ to ensure that, if a field is specified
in the metadata, it is *NOT* overwritten by the default value of the
field. (keep reading through this function for more details)
3. Create getter and setter methods for the field; these are going to
override the original attribute and will be responsible for querying
the metadata for the value of the field.
Args:
cls_ (Type[T]): The dataclass to wrap.
wrapper_field_name (str): The name of the field to store in the
metadata.
wrapper_getter_fn (Optional[Callable[[T], Any]]): A function that
takes returns the value of the field. If None, the getter
is a simple lookup in the metadata dictionary.
wrapper_setter_fn (Optional[Callable[[T, Any], None]]): A function
that is used to set the value of the field. If None, the setter
is a simple addition to the metadata dictionary.
"""
# # # # # # # # # # # # STEP 1: BASIC CHECKS # # # # # # # # # # # # #
if not (is_dataclass(cls_)):
raise TypeError("add_deprecated_field only works on dataclasses")
dataclass_fields = {field.name: field for field in fields(cls_)}
# ensures we have a metadata dict where to store the field value
if "metadata" not in dataclass_fields:
raise TypeError(
"add_deprecated_field requires a `metadata` field"
"in the dataclass of type dict."
)
if not issubclass(dataclass_fields["metadata"].type, Metadata):
raise TypeError(
"add_deprecated_field requires a `metadata` field "
"in the dataclass of type Metadata, not "
f"{dataclass_fields['metadata'].type}."
)
# ensure the field is declared in the dataclass
if wrapper_field_name not in dataclass_fields:
raise TypeError(
f"add_deprecated_field requires a `{wrapper_field_name}` field"
"in the dataclass."
)
# # # # # # # # # # # # # # END OF STEP 1 # # # # # # # # # # # # # # #
# # # # # # # # # # # # # STEP 2: WRAP INIT # # # # # # # # # # # # # #
# In the following comment, we explain the need for step 2.
#
# We want to make sure that if a field is specified in the metadata,
# the default value of the field provided during class annotation does
# not override it. For example, consider the following code:
#
# @store_field_in_metadata('field_a')
# @dataclass
# class MyDataclass:
# metadata: Metadata = field(default_factory=Metadata)
# field_a: int = 3
#
# If we don't disable wrap the __init__ method, the following code
# will print `3`
#
# d = MyDataclass(metadata={'field_a': 5})
# print(d.field_a)
#
# but if we do, it will work fine and print `5` as expected.
#
# The reason why this occurs is that the __init__ method generated
# by a dataclass uses the default value of the field to initialize the
# class if a default is not provided.
#
# Our solution is rather simple: before calling the dataclass init,
# we look if:
# 1. A `metadata` argument is provided in the constructor, and
# 2. The `metadata` argument contains a field with name ``
#
# To disable the auto-init, we have to do two things:
# 1. create a new dataclass that inherits from the original one,
# but with init=False for field wrapper_field_name
# 2. create a wrapper for the __init__ method of the new dataclass
# that, when called, calls the original __init__ method and then
# adds the field value to the metadata dict.
# This signature is going to be used to bind to the args/kwargs during
# init, which allows easy lookup of arguments/keywords arguments by
# name.
cls_signature = inspect.signature(cls_.__init__)
# We need to save the init method since we will override it.
cls_init_fn = cls_.__init__
@wraps(cls_init_fn)
def init_wrapper(self, *args, **kwargs):
# parse the arguments and keywords arguments
arguments = cls_signature.bind(self, *args, **kwargs).arguments
# this adds the metadata to kwargs if it is not already there
metadata = arguments.setdefault("metadata", Metadata())
# this is the main check:
# (a) the metadata argument contains the field we are storing in
# the metadata, and (b) the field is not in args/kwargs, then we
# pass the field value in the metadata to the original init method
# to prevent it from being overwritten by its default value.
if (
wrapper_field_name in metadata
and wrapper_field_name not in arguments
):
arguments[wrapper_field_name] = metadata[wrapper_field_name]
# type: ignore is due to pylance not recognizing that the
# arguments in the signature contain a `self` key
cls_init_fn(**arguments) # type: ignore
setattr(cls_, "__init__", init_wrapper)
# # # # # # # # # # # # # # END OF STEP 2 # # # # # # # # # # # # # # #
# # # # # # # # # # # STEP 3: GETTERS & SETTERS # # # # # # # # # # # #
# We add the getter from here on:
if wrapper_getter_fn is None:
# create property for the deprecated field, as well as a setter
# that will add to the underlying metadata dict
def _wrapper_getter_fn(
self, field_spec: Field = dataclass_fields[wrapper_field_name]
):
# we expect metadata to be of type Metadata
metadata: Union[Metadata, None] = getattr(
self, "metadata", None
)
if metadata is not None and wrapper_field_name in metadata:
return metadata.get(wrapper_field_name)
elif field_spec.default is not MISSING:
return field_spec.default
elif field_spec.default_factory is not MISSING:
return field_spec.default_factory()
else:
raise AttributeError(
f"Value for attribute '{wrapper_field_name}' "
"has not been set."
)
# this avoids mypy error about redefining an argument
wrapper_getter_fn = _wrapper_getter_fn
field_property = property(wrapper_getter_fn)
# We add the setter from here on:
if wrapper_setter_fn is None:
def _wrapper_setter_fn(self: T, value: Any) -> None:
# need to use getattr otherwise pylance complains
# about not knowing if 'metadata' is available as an
# attribute of self (which it is, since we checked above
# that it is in the dataclass fields)
metadata: Union[Metadata, None] = getattr(
self, "metadata", None
)
if metadata is None:
raise RuntimeError(
"all deprecated fields must be declared after the "
f"`metadata` field; however, `{wrapper_field_name}`"
" was declared before. Fix your class definition."
)
metadata.set(wrapper_field_name, value)
# this avoids mypy error about redefining an argument
wrapper_setter_fn = _wrapper_setter_fn
# make a setter for the deprecated field
field_property = field_property.setter(wrapper_setter_fn)
# assign the property to the dataclass
setattr(cls_, wrapper_field_name, field_property)
# # # # # # # # # # # # # # END OF STEP 3 # # # # # # # # # # # # # # #
return cls_
return wrapper_fn
| 15,513 | 37.306173 | 79 |
py
|
mmda
|
mmda-main/src/mmda/types/names.py
|
"""
Names of fields, as strings
@kylel
"""
# document field names
SymbolsField = "symbols"
MetadataField = "metadata"
ImagesField = "images"
PagesField = "pages"
TokensField = "tokens"
RowsField = "rows"
SentencesField = "sents"
BlocksField = "blocks"
WordsField = "words"
SectionsField = "sections"
| 305 | 13.571429 | 27 |
py
|
mmda
|
mmda-main/src/mmda/types/span.py
|
"""
"""
from dataclasses import dataclass
from typing import Dict, List, Optional
from mmda.types.box import Box
@dataclass
class Span:
start: int
end: int
box: Optional[Box] = None
def to_json(self) -> Dict:
if self.box:
return dict(start=self.start, end=self.end, box=self.box.to_json())
else:
return dict(start=self.start, end=self.end)
@classmethod
def from_json(cls, span_dict) -> "Span":
box_dict = span_dict.get("box")
if box_dict:
box = Box.from_json(box_dict=span_dict["box"])
else:
box = None
return Span(start=span_dict["start"], end=span_dict["end"], box=box)
def __lt__(self, other: "Span"):
if self.id and other.id:
return self.id < other.id
else:
return self.start < other.start
@classmethod
def small_spans_to_big_span(
cls, spans: List["Span"], merge_boxes: bool = True
) -> "Span":
# TODO: add warning for non-contiguous spans?
start = spans[0].start
end = spans[0].end
for span in spans[1:]:
if span.start < start:
start = span.start
if span.end > end:
end = span.end
if merge_boxes and all(span.box for span in spans):
new_box = Box.small_boxes_to_big_box(boxes=[span.box for span in spans])
else:
new_box = None
return Span(
start=start,
end=end,
box=new_box,
)
def is_overlap(self, other: "Span") -> bool:
is_self_before_other = self.start < other.end and self.end > other.start
is_other_before_self = other.start < self.end and other.end > self.start
return is_self_before_other or is_other_before_self
@classmethod
def are_disjoint(cls, spans: List["Span"]) -> bool:
for i in range(len(spans)):
for j in range(i + 1, len(spans)):
if spans[i].is_overlap(other=spans[j]):
return False
return True
| 2,096 | 27.337838 | 84 |
py
|
mmda
|
mmda-main/src/mmda/types/__init__.py
|
from mmda.types.document import Document
from mmda.types.annotation import SpanGroup, BoxGroup
from mmda.types.span import Span
from mmda.types.box import Box
from mmda.types.image import PILImage
from mmda.types.metadata import Metadata
__all__ = [
'Document',
'SpanGroup',
'BoxGroup',
'Span',
'Box',
'PILImage',
'Metadata'
]
| 355 | 21.25 | 53 |
py
|
mmda
|
mmda-main/src/mmda/types/indexers.py
|
"""
Indexes for Annotations
"""
from typing import List
from abc import abstractmethod
from dataclasses import dataclass, field
from mmda.types.annotation import SpanGroup, Annotation
from ncls import NCLS
import numpy as np
import pandas as pd
@dataclass
class Indexer:
"""Stores an index for a particular collection of Annotations.
Indexes in this library focus on *INTERSECT* relations."""
@abstractmethod
def find(self, query: Annotation) -> List[Annotation]:
"""Returns all matching Annotations given a suitable query"""
raise NotImplementedError()
class SpanGroupIndexer(Indexer):
"""
Manages a data structure for locating overlapping SpanGroups.
Builds a static nested containment list from SpanGroups
and accepts other SpanGroups as search probes.
See: https://github.com/biocore-ntnu/ncls
[citation]
Alexander V. Alekseyenko, Christopher J. Lee;
Nested Containment List (NCList): a new algorithm for accelerating interval query of genome
alignment and interval databases, Bioinformatics,
Volume 23, Issue 11, 1 June 2007, Pages 1386–1393, https://doi.org/10.1093/bioinformatics/btl647
"""
def __init__(self, span_groups: List[SpanGroup]) -> None:
starts = []
ends = []
ids = []
for sg_id, span_group in enumerate(span_groups):
for span in span_group.spans:
starts.append(span.start)
ends.append(span.end)
ids.append(sg_id)
self._sgs = span_groups
self._index = NCLS(
pd.Series(starts, dtype=np.int64),
pd.Series(ends, dtype=np.int64),
pd.Series(ids, dtype=np.int64)
)
self._ensure_disjoint()
def _ensure_disjoint(self) -> None:
"""
Constituent span groups must be fully disjoint.
Ensure the integrity of the built index.
"""
for span_group in self._sgs:
for span in span_group.spans:
matches = [match for match in self._index.find_overlap(span.start, span.end)]
if len(matches) > 1:
raise ValueError(
f"Detected overlap with existing SpanGroup(s) {matches} for {span_group}"
)
def find(self, query: SpanGroup) -> List[SpanGroup]:
if not isinstance(query, SpanGroup):
raise ValueError(f'SpanGroupIndexer only works with `query` that is SpanGroup type')
if not query.spans:
return []
matched_ids = set()
for span in query.spans:
for _start, _end, matched_id in self._index.find_overlap(span.start, span.end):
matched_ids.add(matched_id)
matched_span_groups = [self._sgs[matched_id] for matched_id in matched_ids]
# Retrieval above doesn't preserve document order; sort here
# TODO: provide option to return matched span groups in same order as self._sgs
# (the span groups the index was built with originally)
return sorted(list(matched_span_groups))
| 3,107 | 30.714286 | 100 |
py
|
mmda
|
mmda-main/src/mmda/types/annotation.py
|
"""
Annotations are objects that are 'aware' of the Document
Collections of Annotations are how one constructs a new
Iterable of Group-type objects within the Document
"""
import warnings
from abc import abstractmethod
from copy import deepcopy
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Union
from mmda.types.box import Box
from mmda.types.metadata import Metadata
from mmda.types.span import Span
if TYPE_CHECKING:
from mmda.types.document import Document
__all__ = ["Annotation", "BoxGroup", "SpanGroup", "Relation"]
def warn_deepcopy_of_annotation(obj: "Annotation") -> None:
"""Warns when a deepcopy is performed on an Annotation."""
cls_name = type(obj).__name__
msg = (
f"Creating a deep copy of a {cls_name} is computationally"
"expensive; consider using references instead."
)
warnings.warn(msg, UserWarning, stacklevel=2)
class Annotation:
"""Annotation is intended for storing model predictions for a document."""
def __init__(
self,
id: Optional[int] = None,
doc: Optional['Document'] = None,
metadata: Optional[Metadata] = None
):
self.id = id
self.doc = doc
self.metadata = metadata if metadata else Metadata()
@abstractmethod
def to_json(self) -> Dict:
pass
@classmethod
@abstractmethod
def from_json(cls, annotation_dict: Dict) -> "Annotation":
pass
def attach_doc(self, doc: "Document") -> None:
if not self.doc:
self.doc = doc
else:
raise AttributeError("This annotation already has an attached document")
# TODO[kylel] - comment explaining
def __getattr__(self, field: str) -> List["Annotation"]:
if self.doc is None:
raise ValueError("This annotation is not attached to a document")
if field in self.doc.fields:
return self.doc.find_overlapping(self, field)
if field in self.doc.fields:
return self.doc.find_overlapping(self, field)
return self.__getattribute__(field)
class BoxGroup(Annotation):
def __init__(
self,
boxes: List[Box],
id: Optional[int] = None,
doc: Optional['Document'] = None,
metadata: Optional[Metadata] = None,
):
self.boxes = boxes
super().__init__(id=id, doc=doc, metadata=metadata)
def to_json(self) -> Dict:
box_group_dict = dict(
boxes=[box.to_json() for box in self.boxes],
id=self.id,
metadata=self.metadata.to_json()
)
return {
key: value for key, value in box_group_dict.items() if value
} # only serialize non-null values
@classmethod
def from_json(cls, box_group_dict: Dict) -> "BoxGroup":
if "metadata" in box_group_dict:
metadata_dict = box_group_dict["metadata"]
else:
# this fallback is necessary to ensure compatibility with box
# groups that were create before the metadata migration and
# therefore have "type" in the root of the json dict instead.
metadata_dict = {
"type": box_group_dict.get("type", None)
}
return cls(
boxes=[
Box.from_json(box_dict=box_dict)
# box_group_dict["boxes"] might not be present since we
# minimally serialize when running to_json()
for box_dict in box_group_dict.get("boxes", [])
],
id=box_group_dict.get("id", None),
metadata=Metadata.from_json(metadata_dict),
)
def __getitem__(self, key: int):
return self.boxes[key]
def __deepcopy__(self, memo):
warn_deepcopy_of_annotation(self)
box_group = BoxGroup(
boxes=deepcopy(self.boxes, memo),
id=self.id,
metadata=deepcopy(self.metadata, memo)
)
# Don't copy an attached document
box_group.doc = self.doc
return box_group
@property
def type(self) -> str:
return self.metadata.get("type", None)
@type.setter
def type(self, type: Union[str, None]) -> None:
self.metadata.type = type
class SpanGroup(Annotation):
def __init__(
self,
spans: List[Span],
box_group: Optional[BoxGroup] = None,
id: Optional[int] = None,
doc: Optional['Document'] = None,
metadata: Optional[Metadata] = None,
):
self.spans = spans
self.box_group = box_group
super().__init__(id=id, doc=doc, metadata=metadata)
@property
def symbols(self) -> List[str]:
if self.doc is not None:
return [
self.doc.symbols[span.start: span.end] for span in self.spans
]
else:
return []
def annotate(
self, is_overwrite: bool = False, **kwargs: Iterable["Annotation"]
) -> None:
if self.doc is None:
raise ValueError("SpanGroup has no attached document!")
key_remaps = {k: v for k, v in kwargs.items()}
self.doc.annotate(is_overwrite=is_overwrite, **key_remaps)
def to_json(self) -> Dict:
span_group_dict = dict(
spans=[span.to_json() for span in self.spans],
id=self.id,
metadata=self.metadata.to_json(),
box_group=self.box_group.to_json() if self.box_group else None
)
return {
key: value
for key, value in span_group_dict.items()
if value is not None
} # only serialize non-null values
@classmethod
def from_json(cls, span_group_dict: Dict) -> "SpanGroup":
box_group_dict = span_group_dict.get("box_group")
if box_group_dict:
box_group = BoxGroup.from_json(box_group_dict=box_group_dict)
else:
box_group = None
if "metadata" in span_group_dict:
metadata_dict = span_group_dict["metadata"]
else:
# this fallback is necessary to ensure compatibility with span
# groups that were create before the metadata migration and
# therefore have "id", "type" in the root of the json dict instead.
metadata_dict = {
"type": span_group_dict.get("type", None),
"text": span_group_dict.get("text", None)
}
return cls(
spans=[
Span.from_json(span_dict=span_dict)
for span_dict in span_group_dict["spans"]
],
id=span_group_dict.get("id", None),
metadata=Metadata.from_json(metadata_dict),
box_group=box_group,
)
def __getitem__(self, key: int):
return self.spans[key]
@property
def start(self) -> Union[int, float]:
return (
min([span.start for span in self.spans])
if len(self.spans) > 0
else float("-inf")
)
@property
def end(self) -> Union[int, float]:
return (
max([span.end for span in self.spans])
if len(self.spans) > 0
else float("inf")
)
def __lt__(self, other: "SpanGroup"):
if self.id and other.id:
return self.id < other.id
else:
return self.start < other.start
def __deepcopy__(self, memo):
warn_deepcopy_of_annotation(self)
span_group = SpanGroup(
spans=deepcopy(self.spans, memo),
id=self.id,
metadata=deepcopy(self.metadata, memo),
box_group=deepcopy(self.box_group, memo)
)
# Don't copy an attached document
span_group.doc = self.doc
return span_group
@property
def type(self) -> str:
return self.metadata.get("type", None)
@type.setter
def type(self, type: Union[str, None]) -> None:
self.metadata.type = type
@property
def text(self) -> str:
maybe_text = self.metadata.get("text", None)
if maybe_text is None:
return " ".join(self.symbols)
return maybe_text
@text.setter
def text(self, text: Union[str, None]) -> None:
self.metadata.text = text
class Relation(Annotation):
pass
| 8,389 | 28.031142 | 84 |
py
|
mmda
|
mmda-main/src/mmda/types/old/image.old.py
|
"""
Dataclass for doing stuff on images of pages of a document
@kylel, @shannons
"""
import base64
from io import BytesIO
from PIL import Image
# Monkey patch the PIL.Image methods to add base64 conversion
def tobase64(self):
# Ref: https://stackoverflow.com/a/31826470
buffered = BytesIO()
self.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue())
return img_str.decode("utf-8")
def frombase64(img_str):
# Use the same naming style as the original Image methods
buffered = BytesIO(base64.b64decode(img_str))
img = Image.open(buffered)
return img
Image.Image.tobase64 = tobase64 # This is the method applied to individual Image classes
Image.frombase64 = frombase64 # This is bind to the module, used for loading the images
| 798 | 23.96875 | 89 |
py
|
mmda
|
mmda-main/src/mmda/types/old/boundingbox.old.py
|
"""
Dataclass for doing stuff on bounding boxes
@kyle
"""
from typing import List, Dict
import json
class BoundingBox:
def __init__(self, l: float, t: float, w: float, h: float, page: int):
"""Assumes x=0.0 and y=0.0 is the top-left of the page, and
x=1.0 and y =1.0 as the bottom-right of the page"""
if l < 0.0 or l > 1.0:
raise ValueError(f'l={l} is not within 0.0~1.0')
if t < 0.0 or t > 1.0:
raise ValueError(f't={t} is not within 0.0~1.0')
if l + w < 0.0 or l + w > 1.0:
raise ValueError(f'l+w={l+w} is not within 0.0~1.0')
if t + h < 0.0 or t + h > 1.0:
raise ValueError(f't+h={t+h} is not within 0.0~1.0')
self.l = l
self.t = t
self.w = w
self.h = h
self.page = page
@classmethod
def from_xyxy(cls, x0: float, y0: float, x1: float, y1: float,
page_height: float, page_width: float) -> 'BoundingBox':
"""Assumes (x0,y0) is top-left of box and (x1,y1) is bottom-right of box
where x=0.0 and y=0.0 is top-left of the page"""
raise NotImplementedError
@classmethod
def from_null(cls):
"""Creates an empty bbox; mostly useful for quick tests"""
bbox = cls.__new__(cls)
bbox.l = None
bbox.t = None
bbox.w = None
bbox.h = None
bbox.page = None
return bbox
@classmethod
def from_json(cls, bbox_json: Dict) -> 'BoundingBox':
l, t, w, h, page = bbox_json
bbox = BoundingBox(l=l, t=t, w=w, h=h, page=page)
return bbox
def to_json(self):
return [self.l, self.t, self.w, self.h, self.page]
def __repr__(self):
return json.dumps(self.to_json())
@classmethod
def union_bboxes(cls, bboxes: List['BoundingBox']) -> 'BoundingBox':
if len({bbox.page for bbox in bboxes}) != 1:
raise ValueError(f'Bboxes not all on same page: {bboxes}')
x1 = min([bbox.l for bbox in bboxes])
y1 = min([bbox.t for bbox in bboxes])
x2 = max([bbox.l + bbox.w for bbox in bboxes])
y2 = max([bbox.t + bbox.h for bbox in bboxes])
return BoundingBox(page=bboxes[0].page, l=x1, t=y1, w=x2 - x1, h=y2 - y1)
| 2,270 | 31.442857 | 81 |
py
|
mmda
|
mmda-main/src/mmda/types/old/span.old.py
|
"""
Dataclass for doing stuff on token streams of a document
@kylel
"""
from typing import List, Optional, Dict, Union
from mmda.types.boundingbox import BoundingBox
import json
class Span:
def __init__(self, start: int, end: int, id: Optional[int] = None, type: Optional[str] = None,
text: Optional[str] = None, bbox: Optional[BoundingBox] = None):
self.start = start
self.end = end
self.type = type
self.id = id
self.text = text
self.bbox = bbox
@classmethod
def from_json(cls, span_json: Dict):
bbox = BoundingBox.from_json(bbox_json=span_json['bbox']) if 'bbox' in span_json else None
span = cls(start=span_json['start'], end=span_json['end'], id=span_json.get('id'),
type=span_json.get('type'), text=span_json.get('text'), bbox=bbox)
return span
def to_json(self, exclude: List[str] = []) -> Dict:
full_json = {'start': self.start,
'end': self.end,
'type': self.type,
'id': self.id,
'text': self.text,
'bbox': self.bbox.to_json() if self.bbox else None}
# the `is not None` is to save serialization space for empty fields
return {k: v for k, v in full_json.items() if k not in exclude and v is not None}
def __repr__(self):
return json.dumps({k: v for k, v in self.to_json().items() if v is not None})
def __contains__(self, val: Union[int, BoundingBox]) -> bool:
"""Checks whether an index value `i` is within the span"""
if isinstance(val, int):
return self.start <= val < self.end
elif isinstance(val, str):
return val in self.text
elif isinstance(val, BoundingBox):
raise NotImplementedError
else:
raise ValueError(f'{val} of type {type(val)} not supported for __contains__')
def __lt__(self, other: 'Span'):
if self.id and other.id:
return self.id < other.id
else:
return self.start < other.start
| 2,121 | 33.225806 | 98 |
py
|
mmda
|
mmda-main/src/mmda/types/old/annotations.old.py
|
"""
Dataclass for representing annotations on documents
@kylel
"""
from typing import List, Optional
import json
from mmda.types.span import Span
from mmda.types.boundingbox import BoundingBox
class Annotation:
def to_json(self):
raise NotImplementedError
def __repr__(self):
return json.dumps(self.to_json())
class SpanAnnotation(Annotation):
def __init__(self, span: Span, label: str):
self.span = span
self.label = label
def to_json(self):
return {'span': self.span.to_json(), 'label': self.label}
def __contains__(self, i: int) -> bool:
return i in self.span
class BoundingBoxAnnotation(Annotation):
def __init__(self, bbox: BoundingBox, label: str):
self.bbox = bbox
self.label = label
def to_json(self):
return {'bbox': self.bbox.to_json(), 'label': self.label}
if __name__ == '__main__':
# In this example, we construct a sequence tagger training dataset using these classes.
text = 'I live in New York. I read the New York Times.'
tokens = [(0, 1), (2, 6), (7, 9), (10, 13), (14, 18), (18, 19),
(20, 21), (22, 26), (27, 30), (31, 34), (35, 39), (40, 45), (45, 46)]
tokens = [Span(start=start, end=end) for start, end in tokens]
for token in tokens:
print(text[token.start:token.end])
tags = [Span(start=10, end=19, attr=['entity']), Span(start=31, end=46, attr=['entity'])]
for tag in tags:
print(f'{text[tag.start:tag.end]}\t{tag.tags}')
def get_label(i: int, tags: List[SpanAnnotation]) -> Optional[str]:
for tag in tags:
if i in tag:
return tag.label
return None
training_data = []
for i, token in enumerate(tokens):
tag = get_label(i=i, tags=tags)
if tag:
training_data.append((token, 1))
else:
training_data.append((token, 0))
| 1,928 | 24.051948 | 93 |
py
|
mmda
|
mmda-main/src/mmda/types/old/document.old.py
|
"""
Dataclass for representing a document and all its constituents
@kylel
"""
from typing import List, Optional, Dict, Tuple, Type
from intervaltree import IntervalTree
from mmda.types.boundingbox import BoundingBox
from mmda.types.annotations import Annotation, SpanAnnotation, BoundingBoxAnnotation
from mmda.types.image import Image
from mmda.types.span import Span
Text = 'text'
Page = 'page'
Token = 'token'
Row = 'row'
Sent = 'sent'
Block = 'block'
DocImage = 'image' # Conflicting the PIL Image naming
class Document:
valid_types = [Page, Token, Row, Sent, Block]
def __init__(self, text: str):
self.text = text
# TODO: if have span_type Map, do still need these?
self._pages: List[Span] = []
self._tokens: List[Span] = []
self._rows: List[Span] = []
self._sents: List[Span] = []
self._blocks: List[Span] = []
self._images: List["PIL.Image"] = []
self._span_type_to_spans: Dict[Type, List[Span]] = {
Page: self._pages,
Token: self._tokens,
Row: self._rows,
Sent: self._sents,
Block: self._blocks
}
self._page_index: IntervalTree = IntervalTree()
self._token_index: IntervalTree = IntervalTree()
self._row_index: IntervalTree = IntervalTree()
self._sent_index: IntervalTree = IntervalTree()
self._block_index: IntervalTree = IntervalTree()
self._span_type_to_index: Dict[Type, IntervalTree] = {
Page: self._page_index,
Token: self._token_index,
Row: self._row_index,
Sent: self._sent_index,
Block: self._block_index
}
@classmethod
def from_json(cls, doc_json: Dict) -> 'Document':
doc = Document(text=doc_json[Text])
pages = []
tokens = []
rows = []
sents = []
blocks = []
for span_type in cls.valid_types:
if span_type in doc_json:
doc_spans = [DocSpan.from_span(span=Span.from_json(span_json=span_json), doc=doc, span_type=span_type)
for span_json in doc_json[span_type]]
if span_type == Page:
pages = doc_spans
elif span_type == Token:
tokens = doc_spans
elif span_type == Row:
rows = doc_spans
elif span_type == Sent:
sents = doc_spans
elif span_type == Block:
blocks = doc_spans
else:
raise Exception(f'Should never reach here')
images = [Image.frombase64(image_str) for image_str in doc_json.get(DocImage,[])]
doc.load(pages=pages, tokens=tokens, rows=rows, sents=sents, blocks=blocks, images=images)
return doc
# TODO: consider simpler more efficient method (e.g. JSONL; text)
def to_json(self) -> Dict:
return {
Text: self.text,
Page: [page.to_json(exclude=['text', 'type']) for page in self.pages],
Token: [token.to_json(exclude=['text', 'type']) for token in self.tokens],
Row: [row.to_json(exclude=['text', 'type']) for row in self.rows],
Sent: [sent.to_json(exclude=['text', 'type']) for sent in self.sents],
Block: [block.to_json(exclude=['text', 'type']) for block in self.blocks],
DocImage: [image.tobase64() for image in self.images]
}
#
# methods for building Document
#
def _build_span_index(self, spans: List[Span]) -> IntervalTree:
"""Builds index for a collection of spans"""
index = IntervalTree()
for span in spans:
# constraint - all spans disjoint
existing = index[span.start:span.end]
if existing:
raise ValueError(f'Existing {existing} when attempting index {span}')
# add to index
index[span.start:span.end] = span
return index
def _build_span_type_to_spans(self):
self._span_type_to_spans: Dict[Type, List[Span]] = {
Page: self._pages,
Token: self._tokens,
Row: self._rows,
Sent: self._sents,
Block: self._blocks
}
def _build_span_type_to_index(self):
self._span_type_to_index: Dict[Type, IntervalTree] = {
Page: self._page_index,
Token: self._token_index,
Row: self._row_index,
Sent: self._sent_index,
Block: self._block_index
}
def load(self, pages: Optional[List[Span]] = None,
tokens: Optional[List[Span]] = None,
rows: Optional[List[Span]] = None,
sents: Optional[List[Span]] = None,
blocks: Optional[List[Span]] = None,
images: Optional[List["PIL.Image"]] = None):
if pages:
self._pages = pages
self._page_index = self._build_span_index(spans=pages)
if tokens:
self._tokens = tokens
self._token_index = self._build_span_index(spans=tokens)
if rows:
self._rows = rows
self._row_index = self._build_span_index(spans=rows)
if sents:
self._sents = sents
self._sent_index = self._build_span_index(spans=sents)
if blocks:
self._blocks = blocks
self._block_index = self._build_span_index(spans=blocks)
if images:
self._images = images
self._build_span_type_to_spans()
self._build_span_type_to_index()
#
# don't mess with Document internals
#
@property
def pages(self) -> List[Span]:
return self._pages
@property
def tokens(self) -> List[Span]:
return self._tokens
@property
def rows(self) -> List[Span]:
return self._rows
@property
def sents(self) -> List[Span]:
return self._sents
@property
def blocks(self) -> List[Span]:
return self._blocks
@property
def images(self) -> List["PIL.Image"]:
return self._images
#
# methods for using Document
#
# TODO: how should `containment` lookups be handled in this library? intersection is symmetric but containment isnt
# TODO: @lru.cache or some memoization might improve performance
def find(self, query: Span, types: str) -> List[Span]:
index = self._span_type_to_index[types]
return sorted([interval.data for interval in index[query.start:query.end]])
# TODO: what happens to the document data when annotate?
def annotate(self, annotations: List[Annotation]):
for annotation in annotations:
if isinstance(annotation, SpanAnnotation):
pass
elif isinstance(annotation, BoundingBoxAnnotation):
pass
else:
pass
raise NotImplementedError
class DocSpan(Span):
def __init__(self, start: int, end: int, doc: Document,
id: Optional[int] = None, type: Optional[str] = None,
text: Optional[str] = None, bbox: Optional[BoundingBox] = None):
super().__init__(start=start, end=end, id=id, type=type, text=text, bbox=bbox)
self.doc = doc
@property
def tokens(self) -> List:
if self.type == 'token':
raise ValueError(f'{self} is a Token and cant lookup other Tokens')
else:
return self.doc.find(query=self, types='token')
@property
def pages(self) -> List:
if self.type == 'page':
raise ValueError(f'{self} is a Page and cant lookup other Pages')
else:
return self.doc.find(query=self, types='page')
@property
def rows(self) -> List:
if self.type == 'row':
raise ValueError(f'{self} is a Row and cant lookup other Rows')
else:
return self.doc.find(query=self, types='row')
@property
def sents(self) -> List:
if self.type == 'sent':
raise ValueError(f'{self} is a Sentence and cant lookup other Sentences')
else:
return self.doc.find(query=self, types='sent')
@property
def blocks(self) -> List:
if self.type == 'block':
raise ValueError(f'{self} is a Block and cant lookup other Blocks')
else:
return self.doc.find(query=self, types='block')
@classmethod
def from_span(cls, span: Span, doc: Document, span_type: str) -> 'DocSpan':
doc_span = cls(start=span.start, end=span.end, doc=doc,
type=span.type, id=span.id, text=span.text, bbox=span.bbox)
# these two fields are optional for `Span` & not often serialized in span_jsons, but are
# critical for DocSpan methods to work properly
if not doc_span.type:
doc_span.type = span_type
if not doc_span.text:
doc_span.text = doc.text[doc_span.start:doc_span.end]
return doc_span
| 9,084 | 32.278388 | 119 |
py
|
mmda
|
mmda-main/src/mmda/types/old/document_elements.py
|
"""
"""
# TODO[kylel] not sure this class needs to exist; seems extra boilerplate for no benefit
from typing import List, Optional, Dict, Tuple, Type
from abc import abstractmethod
from dataclasses import dataclass, field
@dataclass
class DocumentElement:
"""DocumentElement is the base class for all children objects
of a Document. It defines the necessary APIs for manipulating
the children objects.
"""
@abstractmethod
def to_json(self) -> Dict:
pass
# TODO: unclear if should be `annotations` or `annotation`
@abstractmethod
@classmethod
def load(cls, field_name: str, annotations: List["Annotation"], document: Optional["Document"] = None):
pass
@dataclass
class DocumentPageSymbols(DocumentElement):
"""Storing the symbols of a page."""
symbols: str
# TODO: Add support for symbol bounding boxes and style
def __getitem__(self, key):
return self.symbols[key]
def to_json(self):
return self.symbols
@dataclass
class DocumentSymbols(DocumentElement):
"""Storing the symbols of a document."""
page_count: int
page_symbols: List[DocumentPageSymbols] = field(default_factory=list)
# TODO[kylel] - this is more confusing than simply treating it as list[list], like it is == `docsyms[0][2:3]`
def __getitem__(self, indices):
page_id, symbol_slices = indices
assert page_id < len(self.page_symbols), "Page index out of range"
return self.page_symbols[page_id][symbol_slices]
def to_json(self):
return [page_symbols.to_json() for page_symbols in self.page_symbols]
@classmethod
def from_json(cls, symbols_dict: List[str]) -> "DocumentSymbols":
page_symbols = [DocumentPageSymbols(symbols=page_text) for page_text in symbols_dict]
return cls(page_count=len(page_symbols), page_symbols=page_symbols)
| 1,889 | 26.794118 | 113 |
py
|
mmda
|
mmda-main/src/mmda/utils/stringify.py
|
"""
Utility that converts a List[SpanGroup] into a string
@kylel, @lucas
Prior versions:
- https://github.com/allenai/timo_scim/blob/9fa19cd29cde0e2573e0079da8d776895f4d6caa/scim/predictors/utils.py#L221-L234
-
"""
import logging
from typing import List, Optional
from mmda.types import Document, Span, SpanGroup
# logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
def stringify_span_group(
span_group: SpanGroup,
document: Document,
use_word_text: bool = True,
replace_newlines_with: str = " ",
join_words_with: str = " ",
normalize_whitespace: bool = True,
allow_partial_word_match: bool = True,
allow_disjoint_spans: bool = True,
include_symbols_between_disjoint_spans: bool = False,
) -> str:
"""Requires doc.words to exist. This technique applies 4 main steps:
1. Given a query span_group, find associated Words
2. Given associated Words, find associated Symbols (i.e. start-end indices)
3. Given associated Symbols, produce List[str] which includes whitespace chars
4. Given List[str], join into a single string
"""
matched_words = document.find_overlapping(span_group, "words")
# warn if no words intersecting query span_group
if len(matched_words) == 0:
logger.debug(f"span_group {span_group} has no overlapping words in document")
return ""
# are words cut in half? suppose word is (0, 3), but the query asks for (2, 3). Should it include the whole word?
match_any_word_start = any(
[word.start == span_group.start for word in matched_words]
)
match_any_word_end = any([word.end == span_group.end for word in matched_words])
if allow_partial_word_match:
if not match_any_word_start:
logger.debug(
f"span_group {span_group}'s start index doesnt match w/ start of any word. output string may thus include more text than expected."
)
if not match_any_word_end:
logger.debug(
f"span_group {span_group}'s end index doesnt match w/ end of any word. output string may thus include more text than expected."
)
else:
if not match_any_word_start:
raise ValueError(
f"span_group {span_group}'s start index doesnt match w/ start of any word"
)
if not match_any_word_end:
raise ValueError(
f"span_group {span_group}'s end index doesnt match w/ end of any word"
)
# if query has disjoint spans, what should we do with the in-between symbols when stringifying?
if Span.are_disjoint(spans=span_group.spans):
if not allow_disjoint_spans:
raise ValueError(
f"span_group {span_group} has disjoint spans but allow_disjoint_spans is False"
)
else:
logger.debug(f"span_group {span_group} has disjoint spans")
if include_symbols_between_disjoint_spans:
# TODO: easiest is probably to convert disjoint spans into a single longer span
raise NotImplementedError
# if matched words are disjoint, what should we do with the in-between symbols when stringifying?
if Span.are_disjoint(spans=[span for word in matched_words for span in word.spans]):
if not allow_disjoint_spans:
raise ValueError(
f"span_group {span_group} intersects words {matched_words} which have disjoint spans but allow_disjoint_spans is False"
)
else:
logger.debug(
f"span_group {span_group} intersects words {matched_words} which have disjoint spans"
)
if include_symbols_between_disjoint_spans:
# TODO: easiest is probably to convert disjoint spans into a single longer span
raise NotImplementedError
# TODO: actually, maybe refactor this. it doesnt matter if query spangroup is disjoint
# the actual handling should just happen if it's disjoint words.
# define util function that produces text from a word
_stringify_word = lambda word: word.text if use_word_text else None
if use_word_text is False:
raise NotImplementedError(
f"""Havnt figured out how to do this yet. Only supports use_word_text=True for now.
One possible consideration is `document.symbols[start:end]` as a means to get
text, which may be useful for debugging purposes. But this isn't high priority
right now."""
)
# define util function that replaces all whitespace with a single character
_normalize_whitespace = lambda text: " ".join(text.split())
# stringify!
prev = matched_words[0]
text_from_words_including_whitespace: List[str] = [_stringify_word(word=prev)]
for current in matched_words[1:]:
is_there_a_gap = current.start > prev.end
if is_there_a_gap:
text_from_words_including_whitespace.append(join_words_with)
text_from_words_including_whitespace.append(_stringify_word(word=current))
prev = current
# final step of formatting the text to return
candidate_text = "".join(text_from_words_including_whitespace)
if replace_newlines_with is not None:
candidate_text = candidate_text.replace("\n", replace_newlines_with)
if normalize_whitespace:
candidate_text = _normalize_whitespace(candidate_text)
return candidate_text
| 5,487 | 41.215385 | 147 |
py
|
mmda
|
mmda-main/src/mmda/utils/tools.py
|
from __future__ import annotations
import logging
from collections import defaultdict
from itertools import groupby
import itertools
from typing import List, Dict, Tuple
import numpy as np
from mmda.types.annotation import BoxGroup, SpanGroup
from mmda.types.box import Box
from mmda.types.span import Span
def allocate_overlapping_tokens_for_box(
tokens: List[SpanGroup], box, token_box_in_box_group: bool = False, x: float = 0.0, y: float = 0.0, center: bool = False
) -> Tuple[List[Span], List[Span]]:
"""Finds overlap of tokens for given box
Args
`tokens` (List[SpanGroup])
`box` (Box)
`token_box_in_box_group` (bool) defaults to False, assumes token SpanGroup box is on the single span's box.
`center` (bool) if set to True, considers a token to be overlapping with given box only if its center overlaps
Returns
a tuple: (allocated_tokens, remaining_tokens):
`allocated_tokens` is a list of token SpanGroups where their boxes overlap with the input box,
`remaining_tokens` is a list of token SpanGroups where they don't overlap with the input box.
"""
allocated_tokens, remaining_tokens = [], []
for token in tokens:
if token_box_in_box_group and token.box_group.boxes[0].is_overlap(other=box, x=x, y=y, center=center):
# The token "box" is stored within the SpanGroup's .box_group
allocated_tokens.append(token)
elif token.spans[0].box is not None and token.spans[0].box.is_overlap(other=box, x=x, y=y, center=center):
# default to assuming the token "box" is stored in the SpanGroup .box
allocated_tokens.append(token)
else:
remaining_tokens.append(token)
return allocated_tokens, remaining_tokens
def box_groups_to_span_groups(
box_groups: List[BoxGroup], doc: Document, pad_x: bool = False, center: bool = False
) -> List[SpanGroup]:
"""Generate SpanGroups from BoxGroups.
Args
`box_groups` (List[BoxGroup])
`doc` (Document) base document annotated with pages, tokens, rows to
`center` (bool) if True, considers tokens to be overlapping with boxes only if their centers overlap
Returns
List[SpanGroup] with each SpanGroup.spans corresponding to spans (sans boxes) of allocated tokens per box_group,
and each SpanGroup.box_group containing original box_groups
"""
assert all([isinstance(group, BoxGroup) for group in box_groups])
all_page_tokens = dict()
avg_token_widths = dict()
derived_span_groups = []
token_box_in_box_group = None
for box_id, box_group in enumerate(box_groups):
all_tokens_overlapping_box_group = []
for box in box_group.boxes:
# Caching the page tokens to avoid duplicated search
if box.page not in all_page_tokens:
cur_page_tokens = all_page_tokens[box.page] = doc.pages[
box.page
].tokens
if token_box_in_box_group is None:
# Determine whether box is stored on token SpanGroup span.box or in the box_group
token_box_in_box_group = all(
[
(
(hasattr(token.box_group, "boxes") and len(token.box_group.boxes) == 1)
and token.spans[0].box is None
)
for token in cur_page_tokens
]
)
# Determine average width of tokens on this page if we are going to pad x
if pad_x:
if token_box_in_box_group and box.page not in avg_token_widths:
avg_token_widths[box.page] = np.average([t.box_group.boxes[0].w for t in cur_page_tokens])
elif not token_box_in_box_group and box.page not in avg_token_widths:
avg_token_widths[box.page] = np.average([t.spans[0].box.w for t in cur_page_tokens])
else:
cur_page_tokens = all_page_tokens[box.page]
# Find all the tokens within the box
tokens_in_box, remaining_tokens = allocate_overlapping_tokens_for_box(
tokens=cur_page_tokens,
box=box,
token_box_in_box_group=token_box_in_box_group,
# optionally pad x a small amount so that extra narrow token boxes (when split at punctuation) are not missed
x=avg_token_widths.get(box.page, 0.0) * 0.5 if pad_x else 0.0,
y=0.0,
center=center
)
all_page_tokens[box.page] = remaining_tokens
all_tokens_overlapping_box_group.extend(tokens_in_box)
merge_spans = (
MergeSpans.from_span_groups_with_box_groups(
span_groups=all_tokens_overlapping_box_group, index_distance=1
)
if token_box_in_box_group
else MergeSpans(
list_of_spans=list(
itertools.chain.from_iterable(
span_group.spans for span_group in all_tokens_overlapping_box_group
)
),
index_distance=1,
)
)
derived_span_groups.append(
SpanGroup(
spans=merge_spans.merge_neighbor_spans_by_symbol_distance(),
box_group=box_group,
# id = box_id,
)
# TODO Right now we cannot assign the box id, or otherwise running doc.blocks will
# generate blocks out-of-the-specified order.
)
if not token_box_in_box_group:
logging.warning("tokens with box stored in SpanGroup span.box will be deprecated (that is, "
"future Spans wont contain box). Ensure Document is annotated with tokens "
"having box stored in SpanGroup box_group.boxes")
del all_page_tokens
derived_span_groups = sorted(
derived_span_groups, key=lambda span_group: span_group.start
)
# ensure they are ordered based on span indices
for box_id, span_group in enumerate(derived_span_groups):
span_group.id = box_id
# return self._annotate_span_group(
# span_groups=derived_span_groups, field_name=field_name
# )
return derived_span_groups
class MergeSpans:
"""
Given w=width and h=height merge neighboring spans which are w, h or less apart or by merging neighboring spans
which are index distance apart
Inspired by https://leetcode.com/problems/merge-intervals/
"""
def __init__(
self,
list_of_spans: List["Span"],
w: float = 0,
h: float = 0,
index_distance: int = 1,
) -> None:
"""
Args
w (float): The input width between boxes to merge
h (float): The input height between the boxes to merge
index_distance (int): Distance between the spans
"""
self.list_of_spans = list_of_spans
self.w = w
self.h = h
self.graph = defaultdict(list)
self.index_distance = index_distance
@classmethod
def from_span_groups_with_box_groups(
cls,
span_groups: List["SpanGroup"],
w: float = 0,
h: float = 0,
index_distance: int = 1,
) -> MergeSpans:
# Convert SpanGroups with single box_group box into SpanGroups with span.box
spans_with_boxes = []
for sg in span_groups:
assert len(sg.spans) == len(
sg.box_group.boxes
), "Unequal number of spans and boxes for SpanGroup"
for span, box in zip(sg.spans, sg.box_group.boxes):
spans_with_boxes.append(Span(start=span.start, end=span.end, box=box))
return cls(spans_with_boxes, w, h, index_distance)
def build_graph_index_overlap(self):
"""
Build graph, each node is represented by (start, end) of tuple, with the list of spans. Spans are considered
overlapping if they are index_distance apart
"""
starts_matrix = np.full(
(len(self.list_of_spans), len(self.list_of_spans)),
[span.start for span in self.list_of_spans]
)
ends_matrix = np.full(
(len(self.list_of_spans), len(self.list_of_spans)),
[span.end for span in self.list_of_spans]
)
starts_minus_ends = np.abs(starts_matrix - ends_matrix.T)
ends_minus_starts = np.abs(ends_matrix - starts_matrix.T)
are_neighboring_spans = np.minimum(starts_minus_ends, ends_minus_starts) <= self.index_distance
neighboring_spans = np.transpose(are_neighboring_spans.nonzero())
if len(neighboring_spans) > 0:
neighboring_spans_no_dupes = neighboring_spans[np.where(neighboring_spans[:,1] < neighboring_spans[:,0])]
for j, i in neighboring_spans_no_dupes:
span_i = self.list_of_spans[i]
span_j = self.list_of_spans[j]
self.graph[span_i.start, span_i.end].append(span_j)
self.graph[span_j.start, span_j.end].append(span_i)
def build_graph_box_overlap(self):
"""
Build graph, each node is represented by (start, end) of tuple, with the list of spans with overlapping
boxes given, w, h
"""
for i, span_i in enumerate(self.list_of_spans):
assert hasattr(span_i, "box"), "Missing attribute box in a span"
for j in range(i + 1, len(self.list_of_spans)):
assert hasattr(
self.list_of_spans[j], "box"
), "Missing attribute box in a span"
if span_i.box.is_overlap(self.list_of_spans[j].box, self.w, self.h):
self.graph[span_i.start, span_i.end].append(self.list_of_spans[j])
self.graph[
self.list_of_spans[j].start, self.list_of_spans[j].end
].append(span_i)
# gets the connected components of the boxes overlap graph.
def get_components(self):
"""
Groups connected graph nodes into dictionary list
"""
visited = set()
comp_number = 0
nodes_in_comp = defaultdict(list)
def mark_component_dfs(start):
stack = [start]
while stack:
span = stack.pop()
node = span.start, span.end
if node not in visited:
visited.add(node)
nodes_in_comp[comp_number].append(span)
stack.extend(self.graph[node])
# mark all nodes in the same connected component with the same integer.
for span in self.list_of_spans:
center = span.start, span.end
if center not in visited:
mark_component_dfs(span)
comp_number += 1
return nodes_in_comp, comp_number
def merge_neighbor_spans_by_symbol_distance(self):
"""
For each of the lists of the connected nodes determined by index distance between the spans,
merge boxes and find, min, max of the index
"""
return self.build_merged_spans_from_connected_components(index=True)
def merge_neighbor_spans_by_box_coordinate(self):
"""
For each of the lists of the connected nodes determined by distance between the boxes,
merge boxes and find, min, max of the index
"""
return self.build_merged_spans_from_connected_components(index=False)
def build_merged_spans_from_connected_components(self, index):
"""
For each of the lists of the connected nodes determined by symbol distance or box distance,
merge boxes and find, min, max of the index
"""
if index:
self.build_graph_index_overlap()
else:
self.build_graph_box_overlap()
nodes_in_comp, number_of_comps = self.get_components()
# all intervals in each connected component must be merged.
merged_spans = []
for comp in range(number_of_comps):
if nodes_in_comp[comp]:
spans_by_page: Dict[any, List[Span]] = defaultdict(list)
for pg, page_spans in groupby(
nodes_in_comp[comp],
lambda s: s.box.page if s.box is not None else None,
):
for span in page_spans:
spans_by_page[pg].append(span)
for page_spans in spans_by_page.values():
merged_box = Box.small_boxes_to_big_box(
[span.box for span in page_spans]
)
merged_spans.append(
Span(
start=min([span.start for span in page_spans]),
end=max([span.end for span in page_spans]),
box=merged_box,
)
)
return merged_spans
| 13,197 | 40.373041 | 128 |
py
|
mmda
|
mmda-main/src/mmda/utils/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/utils/outline_metadata.py
|
"""
Extract outline (table of contents) metadata from a PDF. Potentially useful for
identifying section headers in the PDF body.
@rauthur
"""
from dataclasses import asdict, dataclass
from io import BytesIO
from typing import Any, Dict, List, Union
import pdfminer.pdfdocument as pd
import pdfminer.pdfpage as pp
import pdfminer.pdfparser as ps
import pdfminer.pdftypes as pt
import pdfminer.psparser as pr
from mmda.types.document import Document
from mmda.types.metadata import Metadata
class PDFMinerOutlineExtractorError(Exception):
"""Base class for outline metadata extration errors."""
class PDFUnsupportedDestination(PDFMinerOutlineExtractorError):
"""Raised when a destination pointer cannot be parsed to a location."""
class PDFNoUsableDestinations(PDFMinerOutlineExtractorError):
"""Raised when there are no usable destinations for any outline metadata."""
class PDFDestinationLocationMissing(PDFMinerOutlineExtractorError):
"""Raised when there is no destination data on a particular outline item."""
class PDFNoOutlines(PDFMinerOutlineExtractorError):
"""Raised when underlying PDF contains no outline metadata (common)."""
class PDFDestinationNotFound(PDFMinerOutlineExtractorError):
"""Raised when the underlying destination cannot be found in the PDF."""
class PDFInvalidSyntax(PDFMinerOutlineExtractorError):
"""Raised when the PDF cannot be properly parsed."""
class PDFPageMissing(PDFMinerOutlineExtractorError):
"""Raised when the destination points to a page that cannot be found."""
class PDFEncryptionError(PDFMinerOutlineExtractorError):
"""Raised for encrypted PDFs."""
class PDFRecursionError(PDFMinerOutlineExtractorError):
"""Underlying parse has cyclic reference of some sort causing recursion error."""
class PDFAttributeError(PDFMinerOutlineExtractorError):
"""Wraps an underlying AttributeError."""
class PDFTypeError(PDFMinerOutlineExtractorError):
"""Wraps an underlying TypeError."""
class PDFEOF(PDFMinerOutlineExtractorError):
"""Raised when encountering an unexpected EOF in parsing."""
class PDFPSSyntaxError(PDFMinerOutlineExtractorError):
"""Raised if the PDF syntax is invalid."""
@dataclass
class _PDFDestination:
"""Destination on the target page."""
top: float
left: float
@dataclass
class _PDFPageInfo:
"""Enumeration of PDF page along with dimensions."""
index: int
x0: float
y0: float
x1: float
y1: float
_OutlineItemValues = Union[str, int, float]
@dataclass
class OutlineItem:
"""A pointer to a section location in a PDF."""
id: int # pylint: disable=invalid-name
title: str
level: int
page: int
l: float # pylint: disable=invalid-name
t: float # pylint: disable=invalid-name
@classmethod
def from_metadata_dict(
cls, metadata_dict: Dict[str, _OutlineItemValues]
) -> "OutlineItem":
"""Instantiate from a metadata dict on a Document
Args:
metadata_dict (Dict[str, _OutlineItemValues]): Document metadata object
Returns:
OutlineItem: Rehydrated OutlineItem object
"""
return OutlineItem(
id=metadata_dict["id"],
title=metadata_dict["title"],
level=metadata_dict["level"],
page=metadata_dict["page"],
l=metadata_dict["l"],
t=metadata_dict["t"],
)
def to_metadata_dict(self) -> Dict[str, _OutlineItemValues]:
"""Convert object to a dict for storing as metadata on Document
Returns:
Dict[str, _OutlineMetadataKeys]: dict representation of object
"""
return asdict(self)
@dataclass
class Outline:
"""A class to represent an ordered list of outline items."""
items: List[OutlineItem]
@classmethod
def from_metadata_dict(cls, metadata_dict: Metadata) -> "Outline":
"""Instantiate from a metadata dict on a Document
Args:
metadata_dict (Metadata): Document metadata object
Returns:
Outline: Rehydrated Outline object
"""
return Outline(
items=[
OutlineItem.from_metadata_dict(i)
for i in metadata_dict["outline"]["items"]
]
)
def to_metadata_dict(self) -> Dict[str, _OutlineItemValues]:
"""Convert object to a dict for storing as metadata on Document
Returns:
Dict[str, List[Dict[str, _OutlineItemValues]]]: dict representation
"""
return asdict(self)
def _dest_to_outline_metadata(
dest: _PDFDestination, page: int, outline_id: int, title: str, level: int
) -> OutlineItem:
return OutlineItem(
id=outline_id, title=title, level=level, page=page, l=dest.left, t=dest.top
)
def _get_page_infos(doc: pd.PDFDocument) -> Dict[Any, _PDFPageInfo]:
infos = {}
for idx, page in enumerate(pp.PDFPage.create_pages(doc)):
x0, y0, x1, y1 = page.mediabox
infos[page.pageid] = _PDFPageInfo(index=idx, x0=x0, y0=y0, x1=x1, y1=y1)
return infos
def _resolve_dest(dest, doc: pd.PDFDocument):
if isinstance(dest, str) or isinstance(dest, bytes):
dest = pt.resolve1(doc.get_dest(dest))
elif isinstance(dest, pr.PSLiteral):
dest = pt.resolve1(doc.get_dest(dest.name))
if isinstance(dest, dict):
dest = dest["D"]
return dest
def _get_dest(dest: List[Any], page_info: _PDFPageInfo) -> _PDFDestination:
w = page_info.x1 - page_info.x0
h = page_info.y1 - page_info.y0
if dest[1] == pr.PSLiteralTable.intern("XYZ"):
# Sometimes the expected coordinates can be missing
if dest[3] is None or dest[2] is None:
raise PDFDestinationLocationMissing(f"Missing location: {dest}!")
return _PDFDestination(top=(h - dest[3]) / h, left=dest[2] / w)
if dest[1] == pr.PSLiteralTable.intern("FitR"):
return _PDFDestination(top=(h - dest[5]) / h, left=dest[2] / w)
else:
raise PDFUnsupportedDestination(f"Unkown destination value: {dest}!")
class PDFMinerOutlineExtractor:
"""Parse a PDF and return a new Document with just outline metadata added."""
def extract(self, input_pdf_path: str, doc: Document, **kwargs) -> Outline:
"""Get outline metadata from a PDF document and store on Document metadata.
Args:
input_pdf_path (str): The PDF to process
doc (Document): The instantiated document
Raises:
ex: If `raise_exceptions` is passed in kwargs and evaluates as True then
underlying processing exceptions will be raised. Otherwise an empty
array of results will be appended to the Document.
"""
outlines: List[OutlineItem] = []
try:
outlines: List[OutlineItem] = self._extract_outlines(input_pdf_path)
except PDFMinerOutlineExtractorError as ex:
if kwargs.get("raise_exceptions"):
raise ex
# If we have just one top-level outline assume that it's the title and remove
if len([o for o in outlines if o.level == 0]) == 1:
outlines = [
OutlineItem(
id=o.id, title=o.title, level=o.level - 1, page=o.page, l=o.l, t=o.t
)
for o in outlines
if o.level > 0
]
return Outline(items=[o for o in outlines])
def _extract_outlines(self, input_pdf_path: str) -> List[OutlineItem]:
outlines = []
with open(input_pdf_path, "rb") as pdf_file:
pdf_bytes = BytesIO(pdf_file.read())
try:
psdoc = pd.PDFDocument(ps.PDFParser(pdf_bytes))
pages = _get_page_infos(psdoc)
# pylint: disable=invalid-name
for oid, (level, title, dest, a, _se) in enumerate(psdoc.get_outlines()):
page = None
# First try to get target location from a dest object
if dest:
try:
dest = _resolve_dest(dest, psdoc)
page = pages[dest[0].objid]
except AttributeError:
dest = None
page = None
# If no dest, try to get it from an action object
elif a:
action = a if isinstance(a, dict) else a.resolve()
if isinstance(action, dict):
subtype = action.get("S")
if (
subtype
and subtype == pr.PSLiteralTable.intern("GoTo")
and action.get("D")
):
dest = _resolve_dest(action["D"], psdoc)
page = pages[dest[0].objid]
if page is not None:
outlines.append(
_dest_to_outline_metadata(
dest=_get_dest(dest, page),
page=page.index,
outline_id=oid,
title=title,
level=level - 1,
)
)
if len(outlines) == 0:
raise PDFNoUsableDestinations("Did not find any usable dests!")
except pd.PDFNoOutlines as ex:
raise PDFNoOutlines() from ex
except pd.PDFDestinationNotFound as ex:
raise PDFDestinationNotFound() from ex
except pd.PDFSyntaxError as ex:
raise PDFInvalidSyntax() from ex
except pd.PDFEncryptionError as ex:
raise PDFEncryptionError() from ex
except AttributeError as ex:
raise PDFAttributeError() from ex
except pr.PSEOF as ex:
raise PDFEOF() from ex
except pr.PSSyntaxError as ex:
raise PDFPSSyntaxError() from ex
except RecursionError as ex:
raise PDFRecursionError() from ex
except TypeError as ex:
raise PDFTypeError() from ex
except KeyError as ex:
raise PDFPageMissing() from ex
return outlines
| 10,257 | 30.370031 | 88 |
py
|
mmda
|
mmda-main/src/mmda/parsers/parser.py
|
"""
Protocol for creating token streams from a document
@kylel, shannons
"""
from abc import abstractmethod
from typing import Protocol
from mmda.types.document import Document
class Parser(Protocol):
@abstractmethod
def parse(self, input_pdf_path: str, **kwargs) -> Document:
"""Given an input PDF return a Document with at least symbols
Args:
input_pdf_path (str): Path to the input PDF to process
Returns:
Document: Depending on parser support at least symbols in the PDF
"""
| 552 | 20.269231 | 77 |
py
|
mmda
|
mmda-main/src/mmda/parsers/symbol_scraper_parser.py
|
"""
Dataclass for creating token streams from a document via SymbolScraper
@kylel
"""
import os
import json
import logging
import math
import re
import subprocess
import tempfile
from collections import defaultdict
from typing import Optional, List, Dict, Tuple
from mmda.types.span import Span
from mmda.types.box import Box
from mmda.types.annotation import SpanGroup
from mmda.types.document import Document
from mmda.parsers.parser import Parser
from mmda.types.names import PagesField, RowsField, SymbolsField, TokensField
logger = logging.getLogger(__name__)
class SymbolScraperParser(Parser):
def __init__(self, sscraper_bin_path: str):
self.sscraper_bin_path = sscraper_bin_path
def parse(self, input_pdf_path: str, tempdir: Optional[str] = None) -> Document:
if tempdir is None:
with tempfile.TemporaryDirectory() as tempdir:
xmlfile = self._run_sscraper(input_pdf_path=input_pdf_path, outdir=tempdir)
doc: Document = self._parse_xml_to_doc(xmlfile=xmlfile)
else:
xmlfile = self._run_sscraper(input_pdf_path=input_pdf_path, outdir=tempdir)
doc: Document = self._parse_xml_to_doc(xmlfile=xmlfile)
return doc
#
# methods for interacting with SymbolScraper binary
#
def _run_sscraper(self, input_pdf_path: str, outdir: str) -> str:
"""Returns xmlpath of parsed output"""
if not input_pdf_path.endswith('.pdf'):
raise FileNotFoundError(f'{input_pdf_path} doesnt end in .pdf extension, which {self} expected')
os.makedirs(outdir, exist_ok=True)
cmd = [self.sscraper_bin_path, '-b', input_pdf_path, outdir]
self._run_and_log(cmd)
xmlfile = os.path.join(outdir, os.path.basename(input_pdf_path).replace('.pdf', '.xml'))
if not os.path.exists(xmlfile):
raise FileNotFoundError(f'Parsing {input_pdf_path} may have failed. Cant find {xmlfile}.')
else:
return xmlfile
#
# methods for building bbox from sscraper XML
#
def _build_from_sscraper_bbox(self, sscraper_bbox: str,
sscraper_page_width: float,
sscraper_page_height: float,
page_id: int) -> Optional[Box]:
left, bottom, width, height = [float(element) for element in sscraper_bbox.split(' ')]
if any(math.isnan(num) for num in [left, bottom, width, height]):
return None
return Box(l=left / sscraper_page_width,
t=(sscraper_page_height - bottom - height) / sscraper_page_height,
# annoyingly, sscraper goes other way
w=width / sscraper_page_width,
h=height / sscraper_page_height,
page=page_id)
#
# helper methods for parsing sscraper's particular XML format
#
def _split_list_by_start_end_tags(self, my_list: List[str],
start_tag: str,
end_tag: str) -> List[Tuple[int, int]]:
"""Basically hunts through `my_list` for start & end tag values and returns (start, end) indices"""
start = None
end = None
current = 0
my_start_ends: List[Tuple[int, int]] = []
while current < len(my_list):
if start_tag in my_list[current]:
start = current
elif end_tag in my_list[current]:
end = current + 1
else:
pass
if start is not None and end is not None:
my_start_ends.append((start, end))
start = None
end = None
current += 1
return my_start_ends
def _find_one_and_extract(self, my_list: List[str],
start_tag: str,
end_tag: str) -> Optional[str]:
"""Hunts for an element in `my_list` to be bounded within start & end tag values."""
for element in my_list:
if start_tag in element and end_tag in element:
return element.replace(start_tag, '').replace(end_tag, '')
return None
def _parse_row_head_tag(self, row_tag: str) -> Dict:
# TODO - not sure why line bboxes are useful; skip for now. they dont quite make sense (e.g. bbox[1] == bbox[3])
match = re.match(pattern=r'<Line id=\"([0-9]+)\" BBOX=\"(.+)\">', string=row_tag)
return {'id': int(match.group(1)), 'bbox': match.group(2)}
def _parse_token_head_tag(self, token_tag: str) -> Dict:
match = re.match(pattern=r'<Word id=\"([0-9]+)\">', string=token_tag)
return {'id': int(match.group(1))}
def _parse_char_head_tag(self, char_tag: str) -> Dict:
match = re.match(pattern=r'<Char id=\"([0-9]+)\" mergeId=\"(.+)\" BBOX=\"(.+)\" (.*?)>(.+)</Char>',
string=char_tag) # RGB string is inconsistent formatting so skip
return {'id': match.group(1), 'bbox': match.group(3), 'text': match.group(5)}
#
# main parsing methods
#
def _parse_page_to_metrics(self, xml_lines: List[str]) -> Dict:
start, end = self._split_list_by_start_end_tags(my_list=xml_lines,
start_tag='<pagemetrics>',
end_tag='</pagemetrics>')[0] # just one of them exists
pagemetrics = xml_lines[start:end]
page_to_metrics = {}
for start, end in self._split_list_by_start_end_tags(my_list=pagemetrics, start_tag='<page>', end_tag='</page>'):
partition = pagemetrics[start:end]
page_num = int(self._find_one_and_extract(my_list=partition, start_tag='<no>', end_tag='</no>'))
page_width = float(self._find_one_and_extract(my_list=partition, start_tag='<pagewidth>', end_tag='</pagewidth>'))
page_height = float(self._find_one_and_extract(my_list=partition, start_tag='<pageheight>', end_tag='</pageheight>'))
page_num_rows = int(self._find_one_and_extract(my_list=partition, start_tag='<lines>', end_tag='</lines>'))
page_num_tokens = int(self._find_one_and_extract(my_list=partition, start_tag='<words>', end_tag='</words>'))
page_num_chars = int(self._find_one_and_extract(my_list=partition, start_tag='<characters>', end_tag='</characters>'))
page_to_metrics[page_num] = {
'height': page_height,
'width': page_width,
'rows': page_num_rows,
'tokens': page_num_tokens,
'chars': page_num_chars
}
return page_to_metrics
def _parse_page_to_row_to_tokens(self, xml_lines: List[str], page_to_metrics: Dict) -> Dict:
page_to_row_to_tokens = defaultdict(lambda: defaultdict(list))
for page_start, page_end in self._split_list_by_start_end_tags(my_list=xml_lines,
start_tag='<Page',
end_tag='</Page>'):
page_lines = xml_lines[page_start:page_end]
page_id = int(page_lines[0].replace('<Page id="', '').replace('">', ''))
for row_start, row_end in self._split_list_by_start_end_tags(my_list=page_lines,
start_tag='<Line',
end_tag='</Line>'):
row_lines = page_lines[row_start:row_end]
row_info = self._parse_row_head_tag(row_tag=row_lines[0]) # first line is the head tag
row_id = row_info['id']
for token_start, token_end in self._split_list_by_start_end_tags(my_list=row_lines,
start_tag='<Word',
end_tag='</Word>'):
token_lines = row_lines[token_start:token_end]
token_info = self._parse_token_head_tag(token_tag=token_lines[0]) # first line is the head tag
char_bboxes: List[Box] = []
token = ''
for char_tag in [t for t in token_lines if t.startswith('<Char') and t.endswith('</Char>')]:
char_info = self._parse_char_head_tag(char_tag=char_tag)
bbox = self._build_from_sscraper_bbox(sscraper_bbox=char_info['bbox'],
sscraper_page_width=page_to_metrics[page_id]['width'],
sscraper_page_height=page_to_metrics[page_id]['height'],
page_id=page_id)
if not bbox:
continue
char_bboxes.append(bbox)
token += char_info['text']
# sometimes, just empty tokens (e.g. figures)
if not token or not char_bboxes:
continue
else:
token_bbox = Box.small_boxes_to_big_box(boxes=char_bboxes)
page_to_row_to_tokens[page_id][row_id].append({'text': token, 'bbox': token_bbox})
return {
page: {row: tokens for row, tokens in row_to_tokens.items()}
for page, row_to_tokens in page_to_row_to_tokens.items()
}
def _convert_nested_text_to_doc_json(self, page_to_row_to_tokens: Dict) -> Dict:
text = ''
page_annos: List[SpanGroup] = []
token_annos: List[SpanGroup] = []
row_annos: List[SpanGroup] = []
start = 0
for page, row_to_tokens in page_to_row_to_tokens.items():
page_rows: List[SpanGroup] = []
for row, tokens in row_to_tokens.items():
# process tokens in this row
row_tokens: List[SpanGroup] = []
for k, token in enumerate(tokens):
# TODO: this is a graphical token specific to SScraper. We process it here,
# instead of in XML so we can still reuse XML cache. But this should be replaced w/ better
# SScraper at some point.
if token['text'] == 'fraction(-)':
continue
text += token['text']
end = start + len(token['text'])
# make token
token = SpanGroup(spans=[Span(start=start, end=end, box=token['bbox'])])
row_tokens.append(token)
token_annos.append(token)
if k < len(tokens) - 1:
text += ' '
else:
text += '\n' # start newline at end of row
start = end + 1
# make row
row = SpanGroup(spans=[
Span(start=row_tokens[0][0].start, end=row_tokens[-1][0].end,
box=Box.small_boxes_to_big_box(boxes=[span.box for t in row_tokens for span in t]))
])
page_rows.append(row)
row_annos.append(row)
# make page
page = SpanGroup(spans=[
Span(start=page_rows[0][0].start, end=page_rows[-1][0].end,
box=Box.small_boxes_to_big_box(boxes=[span.box for r in page_rows for span in r]))
])
page_annos.append(page)
# add IDs
for i, page in enumerate(page_annos):
page.id = i
for j, row in enumerate(row_annos):
row.id = j
for k, token in enumerate(token_annos):
token.id = k
return {
SymbolsField: text,
PagesField: [page.to_json() for page in page_annos],
TokensField: [token.to_json() for token in token_annos],
RowsField: [row.to_json() for row in row_annos]
}
def _run_and_log(self, cmd):
with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
for line in iter(proc.stdout):
logger.info(str(line, 'utf-8'))
def _parse_xml_to_doc(self, xmlfile: str) -> Document:
with open(xmlfile, 'r') as f_in:
xml_lines = [line.strip() for line in f_in]
# get runtime
runtime = int(self._find_one_and_extract(my_list=xml_lines, start_tag='<runtime>', end_tag='</runtime>'))
if runtime is None:
raise ValueError(f'No Runtime for {xmlfile}')
else:
logger.info(f'Symbol Scraper took {runtime} sec for {xmlfile}...')
# get page metrics
page_to_metrics = self._parse_page_to_metrics(xml_lines=xml_lines)
logger.info(f'\tNum pages: {len(page_to_metrics)}')
logger.info(f"\tAvg tokens: {sum([metric['tokens'] for metric in page_to_metrics.values()]) / len(page_to_metrics)}")
logger.info(f"\tAvg rows: {sum([metric['rows'] for metric in page_to_metrics.values()]) / len(page_to_metrics)}")
# get token stream (grouped by page & row)
page_to_row_to_tokens = self._parse_page_to_row_to_tokens(xml_lines=xml_lines, page_to_metrics=page_to_metrics)
# convert to spans
doc_dict = self._convert_nested_text_to_doc_json(page_to_row_to_tokens=page_to_row_to_tokens)
# build Document
doc = Document.from_json(doc_dict=doc_dict)
return doc
| 13,725 | 47.673759 | 130 |
py
|
mmda
|
mmda-main/src/mmda/parsers/pdfplumber_parser.py
|
import itertools
import string
from typing import List, Optional, Union, Tuple
import pdfplumber
try:
# pdfplumber >= 0.8.0
import pdfplumber.utils.text as ppu
except:
# pdfplumber <= 0.7.6
import pdfplumber.utils as ppu
from mmda.parsers.parser import Parser
from mmda.types.annotation import SpanGroup
from mmda.types.box import Box
from mmda.types.document import Document
from mmda.types.metadata import Metadata
from mmda.types.names import PagesField, RowsField, SymbolsField, TokensField
from mmda.types.span import Span
_TOL = Union[int, float]
class WordExtractorWithFontInfo(ppu.WordExtractor):
"""Override WordExtractor methods to append additional char-level info."""
def __init__(
self,
x_tolerance: _TOL = ppu.DEFAULT_X_TOLERANCE,
y_tolerance: _TOL = ppu.DEFAULT_Y_TOLERANCE,
keep_blank_chars: bool = False,
use_text_flow: bool = False,
horizontal_ltr: bool = True,
vertical_ttb: bool = True,
extra_attrs: Optional[List[str]] = None,
split_at_punctuation: Union[bool, str] = False,
append_attrs: Optional[List[str]] = None,
):
super().__init__(
x_tolerance=x_tolerance,
y_tolerance=y_tolerance,
keep_blank_chars=keep_blank_chars,
use_text_flow=use_text_flow,
horizontal_ltr=horizontal_ltr,
vertical_ttb=vertical_ttb,
extra_attrs=extra_attrs,
split_at_punctuation=split_at_punctuation,
)
self.append_attrs = append_attrs
def merge_chars(self, ordered_chars: ppu.T_obj_list) -> ppu.T_obj:
"""Modify returned word to capture additional char-level info."""
word = super().merge_chars(ordered_chars=ordered_chars)
# ordered_chars is a list of characters for the word with extra attributes.
# Here we simply append additional information to the word using the first char.
for key in self.append_attrs:
if key not in word:
word[key] = ordered_chars[0][key]
return word
def extract(self, chars: ppu.T_obj_list) -> ppu.T_obj_list:
if hasattr(super(), "extract"):
# pdfplumber <= 0.7.6
return super().extract(chars)
else:
# pdfplumber >= 0.8.0
return super().extract_words(chars)
class PDFPlumberParser(Parser):
# manually added characters: '–' and '§'
DEFAULT_PUNCTUATION_CHARS = string.punctuation + chr(8211) + chr(167)
def __init__(
self,
token_x_tolerance: int = 1.5,
token_y_tolerance: int = 2,
line_x_tolerance: int = 10,
line_y_tolerance: int = 10,
keep_blank_chars: bool = False,
use_text_flow: bool = True,
horizontal_ltr: bool = True,
vertical_ttb: bool = True,
extra_attrs: Optional[List[str]] = None,
split_at_punctuation: Union[str, bool] = True,
):
"""The PDFPlumber PDF Detector
Args:
token_x_tolerance (int, optional):
The threshold used for extracting "word tokens" from the pdf file.
It will merge the pdf characters into a word token if the difference
between the x_2 of one character and the x_1 of the next is less than
or equal to token_x_tolerance. See details in `pdf2plumber's documentation
<https://github.com/jsvine/pdfplumber#the-pdfplumberpage-class>`_.
Defaults to 1.5, in absolute coordinates.
token_y_tolerance (int, optional):
The threshold used for extracting "word tokens" from the pdf file.
It will merge the pdf characters into a word token if the difference
between the y_2 of one character and the y_1 of the next is less than
or equal to token_y_tolerance. See details in `pdf2plumber's documentation
<https://github.com/jsvine/pdfplumber#the-pdfplumberpage-class>`_.
Defaults to 2, in absolute coordinates.
line_x_tolerance (int, optional):
The threshold used for extracting "line tokens" from the pdf file.
Defaults to 10, in absolute coordinates.
line_y_tolerance (int, optional):
The threshold used for extracting "line tokens" from the pdf file.
Defaults to 10, in absolute coordinates.
keep_blank_chars (bool, optional):
When keep_blank_chars is set to True, it will treat blank characters
are treated as part of a word, not as a space between words. See
details in `pdf2plumber's documentation
<https://github.com/jsvine/pdfplumber#the-pdfplumberpage-class>`_.
Defaults to False.
use_text_flow (bool, optional):
When use_text_flow is set to True, it will use the PDF's underlying
flow of characters as a guide for ordering and segmenting the words,
rather than presorting the characters by x/y position. (This mimics
how dragging a cursor highlights text in a PDF; as with that, the
order does not always appear to be logical.) See details in
`pdf2plumber's documentation
<https://github.com/jsvine/pdfplumber#the-pdfplumberpage-class>`_.
Defaults to True.
horizontal_ltr (bool, optional):
When horizontal_ltr is set to True, it means the doc should read
text from left to right, vice versa.
Defaults to True.
vertical_ttb (bool, optional):
When vertical_ttb is set to True, it means the doc should read
text from top to bottom, vice versa.
Defaults to True.
extra_attrs (Optional[List[str]], optional):
Passing a list of extra_attrs (e.g., ["fontname", "size"]) will
restrict each words to characters that share exactly the same
value for each of those `attributes extracted by pdfplumber
<https://github.com/jsvine/pdfplumber/blob/develop/README.md#char-properties>`_,
and the resulting word dicts will indicate those attributes.
See details in `pdf2plumber's documentation
<https://github.com/jsvine/pdfplumber#the-pdfplumberpage-class>`_.
Defaults to `["fontname", "size"]`.
"""
self.token_x_tolerance = token_x_tolerance
self.token_y_tolerance = token_y_tolerance
self.line_x_tolerance = line_x_tolerance
self.line_y_tolerance = line_y_tolerance
self.keep_blank_chars = keep_blank_chars
self.use_text_flow = use_text_flow
self.horizontal_ltr = horizontal_ltr
self.vertical_ttb = vertical_ttb
self.extra_attrs = (
extra_attrs if extra_attrs is not None else ["fontname", "size"]
)
if split_at_punctuation is True:
split_at_punctuation = type(self).DEFAULT_PUNCTUATION_CHARS
self.split_at_punctuation = split_at_punctuation
def parse(self, input_pdf_path: str) -> Document:
with pdfplumber.open(input_pdf_path) as plumber_pdf_object:
all_tokens = []
all_word_ids = []
last_word_id = -1
all_row_ids = []
last_row_id = -1
all_page_ids = []
all_page_dims = []
for page_id, page in enumerate(plumber_pdf_object.pages):
page_unit = float(page.page_obj.attrs.get("UserUnit", 1.0))
all_page_dims.append((float(page.width), float(page.height), page_unit))
# 1) tokens we use for Document.symbols
coarse_tokens = page.extract_words(
x_tolerance=self.token_x_tolerance,
y_tolerance=self.token_y_tolerance,
keep_blank_chars=self.keep_blank_chars,
use_text_flow=self.use_text_flow,
horizontal_ltr=self.horizontal_ltr,
vertical_ttb=self.vertical_ttb,
extra_attrs=self.extra_attrs,
split_at_punctuation=None,
)
# 2) tokens we use for Document.tokens
fine_tokens = WordExtractorWithFontInfo(
x_tolerance=self.token_x_tolerance,
y_tolerance=self.token_y_tolerance,
keep_blank_chars=self.keep_blank_chars,
use_text_flow=self.use_text_flow,
horizontal_ltr=self.horizontal_ltr,
vertical_ttb=self.vertical_ttb,
extra_attrs=self.extra_attrs,
split_at_punctuation=self.split_at_punctuation,
append_attrs=["fontname", "size"],
).extract(page.chars)
# 3) align fine tokens with coarse tokens
word_ids_of_fine_tokens = self._align_coarse_and_fine_tokens(
coarse_tokens=[c["text"] for c in coarse_tokens],
fine_tokens=[f["text"] for f in fine_tokens],
)
assert len(word_ids_of_fine_tokens) == len(fine_tokens)
# 4) normalize / clean tokens & boxes
fine_tokens = [
{
"text": token["text"],
"fontname": token["fontname"],
"size": token["size"],
"bbox": Box.from_pdf_coordinates(
x1=float(token["x0"]),
y1=float(token["top"]),
x2=float(token["x1"]),
y2=float(token["bottom"]),
page_width=float(page.width),
page_height=float(page.height),
page=int(page_id),
).get_relative(
page_width=float(page.width), page_height=float(page.height)
),
}
for token in fine_tokens
]
# 5) group tokens into lines
# TODO - doesnt belong in parser; should be own predictor
line_ids_of_fine_tokens = self._simple_line_detection(
page_tokens=fine_tokens,
x_tolerance=self.line_x_tolerance / page.width,
y_tolerance=self.line_y_tolerance / page.height,
)
assert len(line_ids_of_fine_tokens) == len(fine_tokens)
# 6) accumulate
all_tokens.extend(fine_tokens)
all_row_ids.extend(
[i + last_row_id + 1 for i in line_ids_of_fine_tokens]
)
last_row_id = all_row_ids[-1]
all_word_ids.extend(
[i + last_word_id + 1 for i in word_ids_of_fine_tokens]
)
last_word_id = all_word_ids[-1]
for _ in fine_tokens:
all_page_ids.append(page_id)
# now turn into a beautiful document!
doc_json = self._convert_nested_text_to_doc_json(
token_dicts=all_tokens,
word_ids=all_word_ids,
row_ids=all_row_ids,
page_ids=all_page_ids,
dims=all_page_dims,
)
doc = Document.from_json(doc_json)
return doc
def _convert_nested_text_to_doc_json(
self,
token_dicts: List[dict],
word_ids: List[int],
row_ids: List[int],
page_ids: List[int],
dims: List[Tuple[float, float]],
) -> dict:
"""For a single page worth of text"""
# 1) build tokens & symbols
symbols = ""
token_annos: List[SpanGroup] = []
start = 0
for token_id in range(len(token_dicts) - 1):
token_dict = token_dicts[token_id]
current_word_id = word_ids[token_id]
next_word_id = word_ids[token_id + 1]
current_row_id = row_ids[token_id]
next_row_id = row_ids[token_id + 1]
# 1) add to symbols
symbols += token_dict["text"]
# 2) make Token
end = start + len(token_dict["text"])
# 2b) gather token metadata
if "fontname" in token_dict and "size" in token_dict:
token_metadata = Metadata(
fontname=token_dict["fontname"],
size=token_dict["size"],
)
else:
token_metadata = None
token = SpanGroup(
spans=[Span(start=start, end=end, box=token_dict["bbox"])],
id=token_id,
metadata=token_metadata,
)
token_annos.append(token)
# 3) increment whitespace based on Row & Word membership. and build Rows.
if next_row_id == current_row_id:
if next_word_id == current_word_id:
start = end
else:
symbols += " "
start = end + 1
else:
# new row
symbols += "\n"
start = end + 1
# handle last token
symbols += token_dicts[-1]["text"]
end = start + len(token_dicts[-1]["text"])
token = SpanGroup(
spans=[Span(start=start, end=end, box=token_dicts[-1]["bbox"])],
id=len(token_dicts) - 1,
)
token_annos.append(token)
# 2) build rows
tokens_with_group_ids = [
(token, row_id, page_id)
for token, row_id, page_id in zip(token_annos, row_ids, page_ids)
]
row_annos: List[SpanGroup] = []
for row_id, tups in itertools.groupby(
iterable=tokens_with_group_ids, key=lambda tup: tup[1]
):
row_tokens = [token for token, _, _ in tups]
row = SpanGroup(
spans=[
Span(
start=row_tokens[0][0].start,
end=row_tokens[-1][0].end,
box=Box.small_boxes_to_big_box(
boxes=[span.box for t in row_tokens for span in t]
),
)
],
id=row_id,
)
row_annos.append(row)
# 3) build pages
page_annos: List[SpanGroup] = []
for page_id, tups in itertools.groupby(
iterable=tokens_with_group_ids, key=lambda tup: tup[2]
):
page_tokens = [token for token, _, _ in tups]
page_w, page_h, page_unit = dims[page_id]
page = SpanGroup(
spans=[
Span(
start=page_tokens[0][0].start,
end=page_tokens[-1][0].end,
box=Box.small_boxes_to_big_box(
boxes=[span.box for t in page_tokens for span in t]
),
)
],
id=page_id,
metadata=Metadata(width=page_w, height=page_h, user_unit=page_unit),
)
page_annos.append(page)
return {
SymbolsField: symbols,
TokensField: [token.to_json() for token in token_annos],
RowsField: [row.to_json() for row in row_annos],
PagesField: [page.to_json() for page in page_annos],
}
def _simple_line_detection(
self, page_tokens: List[dict], x_tolerance: int = 10, y_tolerance: int = 10
) -> List[int]:
"""Get text lines from the page_tokens.
It will automatically add new lines for 1) line breaks (i.e., the current token
has a larger y_difference between the previous one than the y_tolerance) or
2) big horizontal gaps (i.e., the current token has a larger y_difference between
the previous one than the x_tolerance)
Adapted from https://github.com/allenai/VILA/blob/e6d16afbd1832f44a430074855fbb4c3d3604f4a/src/vila/pdftools/pdfplumber_extractor.py#L24
Modified Oct 2022 (kylel): Changed return value to be List[int]
"""
prev_y = None
prev_x = None
lines = []
cur_line_id = 0
n = 0
for token in page_tokens:
cur_y = token["bbox"].center[1]
cur_x = token["bbox"].coordinates[0]
if prev_y is None:
prev_y = cur_y
prev_x = cur_x
if abs(cur_y - prev_y) <= y_tolerance and cur_x - prev_x <= x_tolerance:
lines.append(cur_line_id)
if n == 0:
prev_y = cur_y
else:
prev_y = (prev_y * n + cur_y) / (n + 1) # EMA of the y_height
n += 1
else:
cur_line_id += 1
lines.append(cur_line_id)
n = 1
prev_y = cur_y
prev_x = token["bbox"].coordinates[2]
return lines
def _align_coarse_and_fine_tokens(
self, coarse_tokens: List[str], fine_tokens: List[str]
) -> List[int]:
"""Returns a list of length len(fine_tokens) where elements of the list are
integer indices into coarse_tokens elements."""
assert len(coarse_tokens) <= len(
fine_tokens
), f"This method requires |coarse| <= |fine|"
assert "".join(coarse_tokens) == "".join(
fine_tokens
), f"This method requires the chars(coarse) == chars(fine)"
coarse_start_ends = []
start = 0
for token in coarse_tokens:
end = start + len(token)
coarse_start_ends.append((start, end))
start = end
fine_start_ends = []
start = 0
for token in fine_tokens:
end = start + len(token)
fine_start_ends.append((start, end))
start = end
fine_id = 0
coarse_id = 0
out = []
while fine_id < len(fine_start_ends) and coarse_id < len(coarse_start_ends):
fine_start, fine_end = fine_start_ends[fine_id]
coarse_start, coarse_end = coarse_start_ends[coarse_id]
if coarse_start <= fine_start and fine_end <= coarse_end:
out.append(coarse_id)
fine_id += 1
else:
coarse_id += 1
return out
| 18,743 | 40.105263 | 144 |
py
|
mmda
|
mmda-main/src/mmda/parsers/grobid_parser.py
|
"""
@rauthur, @kylel
"""
import os
import io
import xml.etree.ElementTree as et
from typing import List, Optional, Text
import requests
import tempfile
import json
from mmda.parsers.parser import Parser
from mmda.types.annotation import SpanGroup
from mmda.types.document import Document
from mmda.types.metadata import Metadata
from mmda.types.span import Span
DEFAULT_API = "http://localhost:8070/api/processHeaderDocument"
NS = {"tei": "http://www.tei-c.org/ns/1.0"}
def _null_span_group() -> SpanGroup:
sg = SpanGroup(spans=[])
return sg
def _get_token_spans(text: str, tokens: List[str], offset: int = 0) -> List[int]:
assert len(text) > 0
assert len(tokens) > 0
assert offset >= 0
spans = [Span(start=offset, end=len(tokens[0]) + offset)]
for i, token in enumerate(tokens):
if i == 0:
continue
start = text.find(token, spans[-1].end - offset, len(text))
end = start + len(token)
spans.append(Span(start=start + offset, end=end + offset))
return spans
def _post_document(url: str, input_pdf_path: str) -> str:
req = requests.post(url, files={"input": open(input_pdf_path, "rb")})
if req.status_code != 200:
raise RuntimeError(f"Unable to process document: {input_pdf_path}!")
return req.text
class GrobidHeaderParser(Parser):
"""Grobid parser that uses header API methods to get title and abstract only. The
current purpose of this class is evaluation against other methods for title and
abstract extraction from a PDF.
"""
_url: str
def __init__(self, url: str = DEFAULT_API) -> None:
self._url = url
@property
def url(self) -> str:
return self._url
def parse(self, input_pdf_path: str, tempdir: Optional[str] = None) -> Document:
xml = _post_document(url=self.url, input_pdf_path=input_pdf_path)
if tempdir:
os.makedirs(tempdir, exist_ok=True)
xmlfile = os.path.join(tempdir, os.path.basename(input_pdf_path).replace('.pdf', '.xml'))
with open(xmlfile, 'w') as f_out:
f_out.write(xml)
doc: Document = self._parse_xml_to_doc(xml=xml)
return doc
def _parse_xml_to_doc(self, xml: str) -> Document:
root = et.parse(io.StringIO(xml)).getroot()
title = self._get_title(root=root)
# Here we +1 len because we add a "\n" later when joining (if title found)
abstract_offset = 0 if len(title.text) == 0 else (len(title.text) + 1)
abstract = self._get_abstract(root=root, offset=abstract_offset)
symbols = "\n".join([t for t in [title.text, abstract.text] if len(t) > 0])
document = Document(symbols=symbols)
document.annotate(title=[title], abstract=[abstract])
return document
def _get_title(self, root: et.Element) -> SpanGroup:
matches = root.findall(".//tei:titleStmt/tei:title", NS)
if len(matches) == 0:
return _null_span_group()
if not matches[0].text:
return _null_span_group()
text = matches[0].text.strip()
tokens = text.split()
spans = _get_token_spans(text, tokens)
sg = SpanGroup(spans=spans, metadata=Metadata(text=text))
return sg
def _get_abstract(self, root: et.Element, offset: int) -> SpanGroup:
matches = root.findall(".//tei:profileDesc//tei:abstract//", NS)
if len(matches) == 0:
return _null_span_group()
# An abstract may have many paragraphs
text = "\n".join(m.text for m in matches)
tokens = text.split()
spans = _get_token_spans(text, tokens, offset=offset)
sg = SpanGroup(spans=spans, metadata=Metadata(text=text))
return sg
| 3,770 | 28.232558 | 101 |
py
|
mmda
|
mmda-main/src/mmda/parsers/__init__.py
|
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
__all__ = [
'PDFPlumberParser'
]
| 97 | 18.6 | 59 |
py
|
mmda
|
mmda-main/src/mmda/parsers/grobid_augment_existing_document_parser.py
|
"""
@geli-gel
"""
from grobid_client.grobid_client import GrobidClient
from typing import List, Optional
import os
import xml.etree.ElementTree as et
from mmda.parsers.parser import Parser
from mmda.types import Metadata
from mmda.types.annotation import BoxGroup, Box, SpanGroup
from mmda.types.document import Document
from mmda.types.names import PagesField, RowsField, TokensField
from mmda.utils.tools import box_groups_to_span_groups
REQUIRED_DOCUMENT_FIELDS = [PagesField, RowsField, TokensField]
NS = {
"tei": "http://www.tei-c.org/ns/1.0",
"xml": "http://www.w3.org/XML/1998/namespace",
}
ID_ATTR_KEY = f"{{{NS['xml']}}}id"
class GrobidAugmentExistingDocumentParser(Parser):
"""Grobid parser that uses Grobid python client to hit a running
Grobid server and convert resulting grobid XML TEI coordinates into
MMDA BoxGroups to annotate an existing Document.
Run a Grobid server (from https://grobid.readthedocs.io/en/latest/Grobid-docker/):
> docker pull lfoppiano/grobid:0.7.2
> docker run -t --rm -p 8070:8070 lfoppiano/grobid:0.7.2
"""
def __init__(self, config_path: str = "grobid.config", check_server: bool = True):
self.client = GrobidClient(config_path=config_path, check_server=check_server)
def parse(self, input_pdf_path: str, doc: Document, xml_out_dir: Optional[str] = None) -> Document:
assert doc.symbols != ""
for field in REQUIRED_DOCUMENT_FIELDS:
assert field in doc.fields
(_, _, xml) = self.client.process_pdf(
"processFulltextDocument",
input_pdf_path,
generateIDs=False,
consolidate_header=False,
consolidate_citations=False,
include_raw_citations=False,
include_raw_affiliations=False,
tei_coordinates=True,
segment_sentences=True
)
if xml_out_dir:
os.makedirs(xml_out_dir, exist_ok=True)
xmlfile = os.path.join(
xml_out_dir, os.path.basename(input_pdf_path).replace(".pdf", ".xml")
)
with open(xmlfile, "w") as f_out:
f_out.write(xml)
self._parse_xml_onto_doc(xml, doc)
return doc
def _parse_xml_onto_doc(self, xml: str, doc: Document) -> Document:
xml_root = et.fromstring(xml)
self._cache_page_sizes(xml_root)
# authors
author_box_groups = self._get_box_groups(xml_root, "sourceDesc", "persName")
doc.annotate(
authors=box_groups_to_span_groups(author_box_groups, doc, center=True)
)
# bibliography entries
bib_entry_box_groups = self._get_box_groups(xml_root, "listBibl", "biblStruct")
doc.annotate(
bib_entries=box_groups_to_span_groups(
bib_entry_box_groups, doc, center=True
)
)
# citation mentions
citation_mention_box_groups = self._get_box_groups(
xml_root, "body", "ref", type_attr="bibr"
)
doc.annotate(
citation_mentions=box_groups_to_span_groups(
citation_mention_box_groups, doc, center=True
)
)
return doc
def _xml_coords_to_boxes(self, coords_attribute: str):
coords_list = coords_attribute.split(";")
boxes = []
for coords in coords_list:
pg, x, y, w, h = coords.split(",")
proper_page = int(pg) - 1
boxes.append(
Box(
l=float(x), t=float(y), w=float(w), h=float(h), page=proper_page
).get_relative(*self.page_sizes[proper_page])
)
return boxes
def _cache_page_sizes(self, root: et.Element):
page_size_root = root.find(".//tei:facsimile", NS)
page_size_data = page_size_root.findall(".//tei:surface", NS)
page_sizes = dict()
for data in page_size_data:
page_sizes[int(data.attrib["n"]) - 1] = [
float(data.attrib["lrx"]),
float(data.attrib["lry"]),
]
self.page_sizes = page_sizes
return page_sizes
def _get_box_groups(
self,
root: et.Element,
list_tag: str,
item_tag: str,
type_attr: Optional[str] = None,
) -> List[BoxGroup]:
item_list_root = root.find(f".//tei:{list_tag}", NS)
box_groups = []
if type_attr:
elements = item_list_root.findall(
f".//tei:{item_tag}[@type='{type_attr}']", NS
)
else:
elements = item_list_root.findall(f".//tei:{item_tag}", NS)
for e in elements:
coords_string = e.attrib["coords"]
boxes = self._xml_coords_to_boxes(coords_string)
grobid_id = e.attrib[ID_ATTR_KEY] if ID_ATTR_KEY in e.keys() else None
target_id = e.attrib["target"][1:] if (item_tag == "ref" and "target" in e.keys()) else None
if grobid_id and target_id:
box_groups.append(
BoxGroup(
boxes=boxes,
metadata=Metadata(grobid_id=grobid_id, target_id=target_id),
)
)
elif grobid_id:
box_groups.append(
BoxGroup(boxes=boxes, metadata=Metadata(grobid_id=grobid_id))
)
elif target_id:
box_groups.append(
BoxGroup(boxes=boxes, metadata=Metadata(target_id=target_id))
)
else:
box_groups.append(BoxGroup(boxes=boxes))
return box_groups
| 5,682 | 33.23494 | 104 |
py
|
mmda
|
mmda-main/src/ai2_internal/api.py
|
from typing import List, Optional, Type
from pydantic import BaseModel, Extra, Field
from pydantic.fields import ModelField
import mmda.types.annotation as mmda_ann
__all__ = ["BoxGroup", "SpanGroup"]
class Box(BaseModel):
left: float
top: float
width: float
height: float
page: int
@classmethod
def from_mmda(cls, box: mmda_ann.Box) -> "Box":
return cls(
left=box.l, top=box.t, width=box.w, height=box.h, page=box.page
)
def to_mmda(self) -> mmda_ann.Box:
return mmda_ann.Box(
l=self.left,
t=self.top,
w=self.width,
h=self.height,
page=self.page
)
class Span(BaseModel):
start: int
end: int
box: Optional[Box]
@classmethod
def from_mmda(cls, span: mmda_ann.Span) -> "Span":
box = Box.from_mmda(span.box) if span.box is not None else None
ret = cls(start=span.start, end=span.end, box=box)
if span.box is not None:
ret.box = Box.from_mmda(span.box)
return ret
def to_mmda(self) -> mmda_ann.Span:
ret = mmda_ann.Span(start=self.start, end=self.end)
if self.box is not None:
ret.box = self.box.to_mmda()
return ret
class Attributes(BaseModel):
"""Class to represent attributes for a SpanGroup or BoxGroup.
Attributes are generally stored in mmda as mmda_ann.Metadata objects.
Unlike mmda.types.annotation.Metadata, this class ignores fields
id, type, and text, which are expected to be stored in the SpanGroup
/ BoxGroup itself."""
@classmethod
def from_mmda(cls, metadata: mmda_ann.Metadata) -> "Attributes":
return cls(**metadata.to_json())
def to_mmda(self) -> mmda_ann.Metadata:
return mmda_ann.Metadata.from_json(self.dict())
class Annotation(BaseModel, extra=Extra.ignore):
attributes: Attributes = Attributes()
@classmethod
def get_metadata_cls(cls) -> Type[Attributes]:
attrs_field: ModelField = cls.__fields__["attributes"]
return attrs_field.type_
class BoxGroup(Annotation):
boxes: List[Box]
id: Optional[int]
type: Optional[str]
@classmethod
def from_mmda(cls, box_group: mmda_ann.BoxGroup) -> "BoxGroup":
# for the Pydantic model, we need to convert the metadata to a dict,
# and remove `id` and `type` that are stored there in MMDA
# boxes need to be nestedly converted
boxes = [Box.from_mmda(box) for box in box_group.boxes]
metadata = cls.get_metadata_cls().from_mmda(box_group.metadata)
return cls(
boxes=boxes,
id=box_group.id,
type=box_group.type,
attributes=metadata
)
def to_mmda(self) -> mmda_ann.BoxGroup:
metadata = mmda_ann.Metadata.from_json(self.attributes.dict())
if self.type:
metadata.type=self.type
return mmda_ann.BoxGroup(
metadata=metadata,
boxes=[box.to_mmda() for box in self.boxes],
id=self.id,
)
class SpanGroup(Annotation):
spans: List[Span]
box_group: Optional[BoxGroup]
id: Optional[int]
type: Optional[str]
text: Optional[str]
@classmethod
def from_mmda(cls, span_group: mmda_ann.SpanGroup) -> "SpanGroup":
box_group = (
BoxGroup.from_mmda(span_group.box_group)
if span_group.box_group is not None
else None
)
spans = [Span.from_mmda(sp) for sp in span_group.spans]
metadata = cls.get_metadata_cls().from_mmda(span_group.metadata)
if span_group.metadata.has('type'):
type_val = span_group.metadata.type
else:
type_val = None
if span_group.metadata.has('text'):
text_val = span_group.metadata.text
else:
text_val = None
ret = cls(
spans=spans,
box_group=box_group,
id=span_group.id,
type=type_val,
text=text_val,
attributes=metadata,
)
if span_group.box_group is not None:
ret.box_group = BoxGroup.from_mmda(span_group.box_group)
return ret
def to_mmda(self) -> mmda_ann.SpanGroup:
metadata = mmda_ann.Metadata.from_json(self.attributes.dict())
if self.type:
metadata.type = self.type
if self.text:
metadata.text = self.text
return mmda_ann.SpanGroup(
metadata=metadata,
spans=[span.to_mmda() for span in self.spans],
box_group=self.box_group.to_mmda()if self.box_group else None,
id=self.id
)
class Relation(BaseModel):
from_id: int
to_id: int
attributes: Attributes = Attributes()
| 4,799 | 27.742515 | 76 |
py
|
mmda
|
mmda-main/src/ai2_internal/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/bibentry_predictor_mmda/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import gzip
import json
import logging
import os
import pathlib
import sys
import unittest
from .. import api
from mmda.types.document import Document
from .interface import Instance, Prediction
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
def resolve(file: str) -> str:
return os.path.join(pathlib.Path(os.path.dirname(__file__)), "data", file)
def read_fixture_doc(filename):
path = resolve(filename)
with gzip.open(path, "r") as f:
doc_json = json.loads(f.read())
doc = Document.from_json(doc_json)
return doc
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__handles_no_bib_entries(self, container):
filename = "test_data.json.gz"
doc = read_fixture_doc(filename)
instance = Instance(
symbols=doc.symbols,
tokens=[api.SpanGroup.from_mmda(token) for token in doc.tokens],
pages=[api.SpanGroup.from_mmda(page) for page in doc.pages],
bib_entries=[]
)
prediction = container.predict_batch([instance])[0]
self.assertEqual(prediction, Prediction(
bib_entry_number=[],
bib_entry_authors=[],
bib_entry_title=[],
bib_entry_venue_or_event=[],
bib_entry_year=[],
bib_entry_doi=[],
bib_entry_url=[]
))
def test__predictions(self, container):
# Produced from running upstream models on example paper
# (000026bab3c52aa8ff37dc3e155ffbcb506aa1f6.pdf)
filename = "test_data.json.gz"
doc = read_fixture_doc(filename)
instance = Instance(
symbols=doc.symbols,
tokens=[api.SpanGroup.from_mmda(token) for token in doc.tokens],
pages=[api.SpanGroup.from_mmda(page) for page in doc.pages],
bib_entries=[api.SpanGroup.from_mmda(bib_entry) for bib_entry in doc.bib_entries]
)
prediction = container.predict_batch([instance])[0]
final_doc = instance.to_mmda()
final_doc.annotate(bib_entry_number=[sg.to_mmda() for sg in prediction.bib_entry_number])
final_doc.annotate(bib_entry_authors=[sg.to_mmda() for sg in prediction.bib_entry_authors])
final_doc.annotate(bib_entry_title=[sg.to_mmda() for sg in prediction.bib_entry_title])
final_doc.annotate(bib_entry_venue_or_event=[sg.to_mmda() for sg in prediction.bib_entry_venue_or_event])
final_doc.annotate(bib_entry_doi=[sg.to_mmda() for sg in prediction.bib_entry_doi])
final_doc.annotate(bib_entry_year=[sg.to_mmda() for sg in prediction.bib_entry_year])
final_doc.annotate(bib_entry_url=[sg.to_mmda() for sg in prediction.bib_entry_url])
# Make some assertions about a couple arbitrary entries in the bibliography
# First entry is technically number "10" based on symbol start position only. Order came out of pdf oddly.
self.assertEqual(final_doc.bib_entries[0].bib_entry_number[0].text, "10")
self.assertEqual(final_doc.bib_entries[0].bib_entry_authors[0].text, "Srivastava, K.")
self.assertEqual(final_doc.bib_entries[0].bib_entry_authors[1].text, "V.B. Upadhyay")
self.assertEqual(final_doc.bib_entries[0].bib_entry_title[0].text, "Effect of Phytoecdysteroid on Length of Silk Filament and\nNon-Breakable Filament Length of Multivoltine\nMulberry Silkworm B. mori Linn")
# *Actual* first entry
self.assertEqual(final_doc.bib_entries[1].bib_entry_number[0].text, "1")
self.assertEqual(final_doc.bib_entries[1].bib_entry_authors[0].text, "Upadhyay, V.B.")
self.assertEqual(final_doc.bib_entries[1].bib_entry_authors[1].text, "K.P. Gaur")
self.assertEqual(final_doc.bib_entries[1].bib_entry_authors[2].text, "S.K. Gupta")
self.assertEqual(final_doc.bib_entries[1].bib_entry_title[0].text, "Effect of ecological factors on the silk producing\npotential of the mulberry silkworm ( Bombyx mori\nLinn. )")
self.assertEqual(final_doc.bib_entries[1].bib_entry_venue_or_event[0].text, "Malays. Appl. Biol.")
def test__spanless_bibs_pass(self, container):
# Produced from getting annotation store data from running upstream models on example paper
# Upstream bib detector model produces annotations which result in SpanGroups with empty spans
# See https://github.com/allenai/mmda/pull/186
# (3cf45514384bbb7d083ae53e19bdc22300e648ab.pdf)
filename = "test_data_v2_first_2_bibs_have_empty_span_groups.json.gz"
doc = read_fixture_doc(filename)
instance = Instance(
symbols=doc.symbols,
tokens=[api.SpanGroup.from_mmda(token) for token in doc.tokens],
pages=[api.SpanGroup.from_mmda(page) for page in doc.pages],
bib_entries=[api.SpanGroup.from_mmda(bib_entry) for bib_entry in doc.bib_entries]
)
# doesn't fail
prediction = container.predict_batch([instance])[0]
| 5,941 | 40.552448 | 214 |
py
|
mmda
|
mmda-main/src/ai2_internal/bibentry_predictor_mmda/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/bibentry_predictor_mmda/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
from typing import List
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal import api
from mmda.predictors.hf_predictors.bibentry_predictor.predictor import BibEntryPredictor
from mmda.predictors.hf_predictors.bibentry_predictor.types import BibEntryStructureSpanGroups
from mmda.types.document import Document
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
The fields below are examples only; please replace them with
appropriate fields for your model.
To learn more about declaring pydantic model fields, please see:
https://pydantic-docs.helpmanual.io/
"""
symbols: str
tokens: List[api.SpanGroup]
pages: List[api.SpanGroup]
bib_entries: List[api.SpanGroup]
def to_mmda(self) -> Document:
doc = Document(symbols=self.symbols)
doc.annotate(tokens=[token.to_mmda() for token in self.tokens])
doc.annotate(pages=[page.to_mmda() for page in self.pages])
doc.annotate(bib_entries=[bib_entry.to_mmda() for bib_entry in self.bib_entries])
return doc
class Prediction(BaseModel):
"""
Describes the outcome of inference for one Instance
The fields below are examples only; please replace them with
appropriate fields for your model.
To learn more about declaring pydantic model fields, please see:
https://pydantic-docs.helpmanual.io/
"""
bib_entry_number: List[api.SpanGroup]
bib_entry_authors: List[api.SpanGroup]
bib_entry_title: List[api.SpanGroup]
bib_entry_venue_or_event: List[api.SpanGroup]
bib_entry_year: List[api.SpanGroup]
bib_entry_doi: List[api.SpanGroup]
bib_entry_url: List[api.SpanGroup]
@staticmethod
def from_mmda(mmda: BibEntryStructureSpanGroups) -> 'Prediction':
return Prediction(
bib_entry_number=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_number],
bib_entry_authors=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_authors],
bib_entry_title=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_title],
bib_entry_venue_or_event=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_venue_or_event],
bib_entry_year=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_year],
bib_entry_doi=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_doi],
bib_entry_url=[api.SpanGroup.from_mmda(sg) for sg in mmda.bib_entry_url],
)
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
The fields below are examples only; please replace them with ones
appropriate for your model. These serve as a record of the ENV
vars the consuming application needs to set.
"""
bibentries_per_run: int = Field(
default=5,
description="The maximum number of bibentries we can send to the model at one time. "
"Used for capping the maximum memory used during token classification."
)
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
"""
Perform whatever start-up operations are required to get your
model ready for inference. This operation is performed only once
during the application life-cycle.
"""
self._predictor = BibEntryPredictor(self._artifacts_dir)
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
documents = [i.to_mmda() for i in instances]
mmda_predictions = [
self._predictor.predict(
document,
bibentries_per_run=self._config.bibentries_per_run
) for document in documents
]
return [Prediction.from_mmda(prediction) for prediction in mmda_predictions]
| 5,306 | 35.854167 | 107 |
py
|
mmda
|
mmda-main/src/ai2_internal/dwp_heuristic/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import gzip
import json
import logging
import os
import sys
import unittest
from .interface import Instance, Prediction
from ai2_internal import api
from mmda.types.document import Document
FIXTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_fixtures")
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
def resolve(file: str) -> str:
return os.path.join(os.path.dirname(__file__), "test_fixtures", file)
def read_fixture_doc(filename):
path = resolve(filename)
with gzip.open(path, "r") as f:
doc_json = json.loads(f.read())
doc = Document.from_json(doc_json)
return doc
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions(self, container):
doc_file = resolve("test_doc.json")
with open(doc_file) as f:
doc = Document.from_json(json.load(f))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
rows = [api.SpanGroup.from_mmda(sg) for sg in doc.rows]
instances = [Instance(
symbols=doc.symbols,
tokens=tokens,
rows=rows
)]
predictions = container.predict_batch(instances)
prediction = predictions[0]
self.assertTrue(len(prediction.words) <= len(tokens))
self.assertTrue(all([w.text is not None for w in prediction.words]))
| 2,347 | 24.802198 | 87 |
py
|
mmda
|
mmda-main/src/ai2_internal/dwp_heuristic/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/dwp_heuristic/interface.py
|
from typing import List
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal.api import SpanGroup
from mmda.predictors.heuristic_predictors.dictionary_word_predictor import (
DictionaryWordPredictor
)
from mmda.types.document import Document
class Instance(BaseModel):
"""
Inference input for a single paper.
"""
symbols: str = Field(description="Extracted PDF document text")
tokens: List[SpanGroup] = Field(description="The tokens to coerce into words")
rows: List[SpanGroup] = Field(description="Document rows, used as signal for determining word boundaries")
class Prediction(BaseModel):
"""
Inference output for a single paper.
"""
words: List[SpanGroup] = Field(description="Input tokens coerced into words. Includes cleaned-up text.")
class PredictorConfig(BaseSettings):
"""
no-op for this model
"""
pass
class Predictor:
"""
This class is instantiated at application startup as a singleton,
and is used by the TIMO framework to interface with the underlying
DWP predictor.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
self._predictor = DictionaryWordPredictor("/dev/null")
def predict_one(self, instance: Instance) -> Prediction:
doc = Document(instance.symbols)
doc.annotate(tokens=[t.to_mmda() for t in instance.tokens])
doc.annotate(rows=[r.to_mmda() for r in instance.rows])
words = self._predictor.predict(doc)
# RE: https://github.com/allenai/scholar/issues/36200
for word in words:
if word.text:
word.text = word.text.replace("\u0000", "")
return Prediction(
words=[SpanGroup.from_mmda(w) for w in words]
)
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
"""
return [self.predict_one(instance) for instance in instances]
| 2,309 | 29.8 | 110 |
py
|
mmda
|
mmda-main/src/ai2_internal/citation_links/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import logging
import sys
import unittest
from ai2_internal import api
from ai2_internal.citation_links.interface import Instance
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
# single text string representing text contents of pdf
SYMBOLS = "titlexxxx4xxxx16xxx[16] C. Fisch, Centennial of the string galvanometer and the electro- cardiogram4. Wei Zhuo, Qianyi Zhan, Yuan Liu, Zhenping Xie, and Jing Lu. Context attention heterogeneous network embed- ding.37 Urban Taco Collective, Tacos with sauce, 2019"
SPAN_1 = api.Span(start = 9, end = 10, box = None)
MENTION_1 = api.SpanGroup(
spans = [SPAN_1],
box_group = None,
id = 1,
type = None,
text = None
)
# text for this span is "16"
SPAN_2 = api.Span(start = 14, end = 16, box = None)
MENTION_2 = api.SpanGroup(
spans = [SPAN_2],
box_group = None,
id = 2,
type = None,
text = None
)
# text for this span is "[16] C. Fisch, Centennial of the string galvanometer and the electro- cardiogram"
BIB_SPAN_1 = api.Span(start = 19, end = 98, box = None)
BIB_1 = api.SpanGroup(
spans = [BIB_SPAN_1],
box_group = None,
id = 1,
type = None,
text = None
)
# text for this span is "4. Wei Zhuo, Qianyi Zhan, Yuan Liu, Zhenping Xie, and Jing Lu. Context attention heterogeneous network embed- ding."
BIB_SPAN_2 = api.Span(start = 99, end = 213, box = None)
BIB_2 = api.SpanGroup(
spans = [BIB_SPAN_2],
box_group = None,
id = 2,
type = None,
text = None
)
# text for this span is "37 Urban Taco Collective, Tacos with sauce, 2019"
BIB_SPAN_3 = api.Span(start = 214, end = 261, box = None)
BIB_3 = api.SpanGroup(
spans = [BIB_SPAN_3],
box_group = None,
id = 3,
type = None,
text = None
)
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions(self, container):
instances = [
Instance(symbols = SYMBOLS, mentions = [MENTION_1, MENTION_2], bibs = [BIB_1, BIB_2, BIB_3])
]
predictions = container.predict_batch(instances)
self.assertEqual(len(predictions), 1)
predicted_links = predictions[0].linked_mentions
self.assertEqual(len(predicted_links), 2)
self.assertEqual(predicted_links[0], (str(MENTION_1.id), str(BIB_2.id)))
self.assertEqual(predicted_links[1], (str(MENTION_2.id), str(BIB_1.id)))
predicted_relations = predictions[0].linked_mention_relations
self.assertEqual(len(predicted_relations), 2)
self.assertEqual(predicted_relations[0], api.Relation(from_id=MENTION_1.id, to_id=BIB_2.id))
self.assertEqual(predicted_relations[1], api.Relation(from_id=MENTION_2.id, to_id=BIB_1.id))
def test__predictions_predicts_nothing_when_there_are_no_mentions(self, container):
instances = [
Instance(symbols = SYMBOLS, mentions = [], bibs = [BIB_1, BIB_2, BIB_3])
]
predictions = container.predict_batch(instances)
self.assertEqual(len(predictions), 1)
predicted_relations = predictions[0].linked_mention_relations
self.assertEqual(len(predicted_relations), 0)
def test__predictions_predicts_nothing_when_there_are_no_bib_entries(self, container):
instances = [
Instance(symbols = SYMBOLS, mentions = [MENTION_1, MENTION_2], bibs = [])
]
predictions = container.predict_batch(instances)
self.assertEqual(len(predictions), 1)
predicted_relations = predictions[0].linked_mention_relations
self.assertEqual(len(predicted_relations), 0)
| 4,538 | 31.191489 | 274 |
py
|
mmda
|
mmda-main/src/ai2_internal/citation_links/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/citation_links/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
from typing import List, Tuple
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal import api
from mmda.predictors.xgb_predictors.citation_link_predictor import CitationLinkPredictor
from mmda.types.document import Document
# these should represent the extracted citation mentions and bibliography entries for a paper
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
"""
symbols: str
mentions: List[api.SpanGroup]
bibs: List[api.SpanGroup]
class Prediction(BaseModel):
"""
Describes the outcome of inference for one Instance
"""
# tuple represents mention.id and bib.id for the linked pair
linked_mentions: List[Tuple[str, str]]
linked_mention_relations: List[api.Relation]
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
"""
CIT_LINK_PREDICTOR_SCORE_THRESHOLD: float = Field(default=0.8, description="Prediction threshold for linking a cit mention-bib pair.")
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._predictor = CitationLinkPredictor(artifacts_dir, config.CIT_LINK_PREDICTOR_SCORE_THRESHOLD)
def predict_one(self, inst: Instance) -> Prediction:
"""
Should produce a single Prediction for the provided Instance.
Leverage your underlying model to perform this inference.
"""
doc = Document(symbols=inst.symbols)
doc.annotate(mentions=[sg.to_mmda() for sg in inst.mentions])
doc.annotate(bibs=[sg.to_mmda() for sg in inst.bibs])
prediction = self._predictor.predict(doc) # returns [(mention.id, bib.id)]
return Prediction(
linked_mentions = prediction,
linked_mention_relations = [
api.Relation(from_id=mention_id, to_id=bib_id)
for mention_id, bib_id in prediction
]
)
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
return [self.predict_one(instance) for instance in instances]
| 3,401 | 34.4375 | 138 |
py
|
mmda
|
mmda-main/src/ai2_internal/figure_table_predictors/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import json
import logging
import os
import sys
import unittest
from .. import api
from mmda.types.document import Document
from .interface import Instance
import mmda.types as mmda_types
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
def resolve(file: str) -> str:
return os.path.join(os.path.dirname(__file__), 'test_fixtures', file)
def get_test_instance(sha) -> Instance:
doc_file = resolve(f'test_doc_sha_{sha}.json')
with open(doc_file) as f:
dic_json = json.load(f)
doc = Document.from_json(dic_json['doc'])
layout_equations = [mmda_types.BoxGroup.from_json(entry) for entry in dic_json['layout_equations']]
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
pages = [api.SpanGroup.from_mmda(sg) for sg in doc.pages]
vila_span_groups = [api.SpanGroup.from_mmda(sg) for sg in doc.vila_span_groups]
blocks = [api.BoxGroup.from_mmda(bg) for bg in layout_equations]
return Instance(
symbols=doc.symbols,
tokens=tokens,
pages=pages,
vila_span_groups=vila_span_groups,
blocks=blocks,
)
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions_test_doc_sha_d045(self, container):
instances = [get_test_instance('d0450478c38dda61f9943f417ab9fcdb2ebeae0a')]
predictions = container.predict_batch(instances)
assert isinstance(predictions[0].figures[0], api.BoxGroup)
assert isinstance(predictions[0].figure_captions[0], api.SpanGroup)
assert isinstance(predictions[0].figure_to_figure_captions[0], api.Relation)
assert isinstance(predictions[0].tables[0], api.BoxGroup)
assert isinstance(predictions[0].table_captions[0], api.SpanGroup)
assert isinstance(predictions[0].table_to_table_captions[0], api.Relation)
assert len(predictions[0].figures) == 5
assert len(predictions[0].tables) == 6
def test__predictions_test_doc_sha_08f05(self, container):
instances = [get_test_instance('08f02e7888f140a76a00ed23fce2f2fc303a')]
predictions = container.predict_batch(instances)
assert isinstance(predictions[0].figures[0], api.BoxGroup)
assert isinstance(predictions[0].figure_captions[0], api.SpanGroup)
assert isinstance(predictions[0].figure_to_figure_captions[0], api.Relation)
assert isinstance(predictions[0].tables[0], api.BoxGroup)
assert isinstance(predictions[0].table_captions[0], api.SpanGroup)
assert isinstance(predictions[0].table_to_table_captions[0], api.Relation)
assert len(predictions[0].figures) == 4
assert len(predictions[0].tables) == 3
| 3,639 | 36.525773 | 103 |
py
|
mmda
|
mmda-main/src/ai2_internal/figure_table_predictors/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/figure_table_predictors/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
from typing import List
from pydantic import BaseModel, BaseSettings
from mmda.predictors.heuristic_predictors.figure_table_predictors import FigureTablePredictions
from mmda.types.document import Document
from ai2_internal import api
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
The fields below are examples only; please replace them with
appropriate fields for your model.
To learn more about declaring pydantic model fields, please see:
https://pydantic-docs.helpmanual.io/
"""
symbols: str
tokens: List[api.SpanGroup]
pages: List[api.SpanGroup]
vila_span_groups: List[api.SpanGroup]
blocks: List[api.BoxGroup]
def to_mmda(self):
"""
Convert this Instance to an mmda.types.Document
"""
doc = Document(symbols=self.symbols)
doc.annotate(tokens=[sg.to_mmda() for sg in self.tokens])
doc.annotate(pages=[sg.to_mmda() for sg in self.pages])
doc.annotate(blocks=[sg.to_mmda() for sg in self.blocks])
doc.annotate(vila_span_groups=[sg.to_mmda() for sg in self.vila_span_groups])
return doc
class Prediction(BaseModel):
"""
Describes the outcome of inference for one Instance
"""
figures: List[api.BoxGroup]
figure_captions: List[api.SpanGroup]
figure_to_figure_captions: List[api.Relation]
tables: List[api.BoxGroup]
table_captions: List[api.SpanGroup]
table_to_table_captions: List[api.Relation]
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
"""
pass
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
def predict_one(self, instance: Instance) -> Prediction:
"""
Should produce a single Prediction for the provided Instance.
Leverage your underlying model to perform this inference.
"""
predictions_table_figure_dict = FigureTablePredictions(instance.to_mmda()).predict()
return Prediction(
figures=[api.BoxGroup.from_mmda(sg) for sg in predictions_table_figure_dict['figures']],
figure_captions=[api.SpanGroup.from_mmda(bg) for bg in predictions_table_figure_dict['figure_captions']],
figure_to_figure_captions=predictions_table_figure_dict['figure_to_figure_captions'],
tables=[api.BoxGroup.from_mmda(sg) for sg in predictions_table_figure_dict['tables']],
table_captions=[api.SpanGroup.from_mmda(bg) for bg in predictions_table_figure_dict['table_captions']],
table_to_table_captions=predictions_table_figure_dict['table_to_table_captions']
)
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
return [self.predict_one(instance) for instance in instances]
| 4,263 | 35.135593 | 117 |
py
|
mmda
|
mmda-main/src/ai2_internal/vila/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import json
import logging
import os
import sys
import unittest
from pathlib import Path
from PIL import Image
from .. import api
from mmda.types.document import Document
from mmda.types.image import tobase64
from .interface import Instance
FIXTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_fixtures")
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
def resolve(file: str) -> str:
return os.path.join(os.path.dirname(__file__), "test_fixtures", file)
def resolve_image(file: str) -> str:
return os.path.join(Path(os.path.dirname(__file__)).parent, "shared_test_fixtures", file)
def get_test_instance() -> Instance:
doc_file = resolve("test_doc.json")
with open(doc_file) as f:
doc = Document.from_json(json.load(f))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
rows = [api.SpanGroup.from_mmda(sg) for sg in doc.rows]
pages = [api.SpanGroup.from_mmda(sg) for sg in doc.pages]
images = [tobase64(Image.open(resolve_image("page0.png")))]
return Instance(
symbols=doc.symbols,
images=images,
tokens=tokens,
rows=rows,
pages=pages
)
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions(self, container):
instances = [get_test_instance()]
predictions = container.predict_batch(instances)
prediction = predictions[0]
annotation_types = set(a.type for a in prediction.groups)
self.assertEqual({"Title", "Paragraph"}, annotation_types)
| 2,531 | 26.521739 | 93 |
py
|
mmda
|
mmda-main/src/ai2_internal/vila/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/vila/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
import logging
from typing import List
import torch
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal import api
from mmda.predictors.hf_predictors.token_classification_predictor import (
IVILATokenClassificationPredictor,
)
from mmda.types.document import Document, SpanGroup
from mmda.types.image import frombase64
logger = logging.getLogger(__name__)
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
"""
symbols: str
images: List[str]
tokens: List[api.SpanGroup]
rows: List[api.SpanGroup]
pages: List[api.SpanGroup]
def to_mmda(self):
doc = Document(symbols=self.symbols)
doc.annotate(tokens=[sg.to_mmda() for sg in self.tokens])
doc.annotate(rows=[sg.to_mmda() for sg in self.rows])
doc.annotate(pages=[sg.to_mmda() for sg in self.pages])
images = [frombase64(img) for img in self.images]
doc.annotate_images(images)
return doc
class Prediction(BaseModel):
"""
Describes the outcome of inference for one Instance
"""
groups: List[api.SpanGroup]
@classmethod
def from_mmda(cls, groups: List[SpanGroup]) -> "Prediction":
return cls(groups=[api.SpanGroup.from_mmda(grp) for grp in groups])
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
"""
subpage_per_run: int = Field(
default=2,
description="The maximum number of subpages we can send to the models at one time. "
"Used for capping the maximum memory usage during the vila dep."
)
class Predictor:
"""
Interface on to underlying VILA Predictor.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
device = "cuda" if torch.cuda.is_available() else None
if device == "cuda":
logger.info("CUDA device detected, running model with GPU acceleration.")
else:
logger.info("No CUDA device detected, running model on CPU.")
self._predictor = IVILATokenClassificationPredictor.from_pretrained(
self._artifacts_dir,
device=device
)
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
"""
predictions = []
for inst in instances:
span_groups = self._predictor.predict(
inst.to_mmda(), subpage_per_run=self._config.subpage_per_run
)
predictions.append(
Prediction(groups=[api.SpanGroup.from_mmda(sg) for sg in span_groups])
)
return predictions
| 3,302 | 27.721739 | 92 |
py
|
mmda
|
mmda-main/src/ai2_internal/bibentry_predictor/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import logging
import sys
import unittest
from .interface import Instance, Prediction
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions(self, container):
instances = [
Instance(bib_entry="[16] C. Fisch, Centennial of the string galvanometer and the electro- cardiogram, Journal of the American College of Cardiology , vol. 36, no. 6, pp. 1737–1745, 2000."),
Instance(bib_entry="Wei Zhuo, Qianyi Zhan, Yuan Liu, Zhenping Xie, and Jing Lu. Context attention heterogeneous network embed- ding. Computational Intelligence and Neuroscience , 2019. doi: 10.1155/2019/8106073."),
]
predictions = container.predict_batch(instances)
self.assertEqual(len(predictions), 2)
expected1 = Prediction(
citation_number="16",
title="Centennial of the string galvanometer and the electrocardiogram",
doi=None
)
self.assertEqual(predictions[0], expected1)
expected2 = Prediction(
citation_number=None,
title="Context attention heterogeneous network embedding",
doi="10.1155/2019/8106073"
)
self.assertEqual(predictions[1], expected2)
| 2,267 | 31.4 | 226 |
py
|
mmda
|
mmda-main/src/ai2_internal/bibentry_predictor/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/bibentry_predictor/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
from typing import List, Optional
from pydantic import BaseModel, BaseSettings, Field
from mmda.predictors.hf_predictors.bibentry_predictor.predictor import BibEntryPredictor
class Instance(BaseModel):
bib_entry: str = Field(description="Bibliography entry to parse")
class Prediction(BaseModel):
citation_number: Optional[str]
title: Optional[str]
doi: Optional[str]
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
The fields below are examples only; please replace them with ones
appropriate for your model. These serve as a record of the ENV
vars the consuming application needs to set.
"""
pass
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
"""
Perform whatever start-up operations are required to get your
model ready for inference. This operation is performed only once
during the application life-cycle.
"""
self._predictor = BibEntryPredictor(self._artifacts_dir)
def predict_one(self, instance: Instance) -> Prediction:
"""
Should produce a single Prediction for the provided Instance.
Leverage your underlying model to perform this inference.
"""
raise self.predict_batch([instance])
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
bib_entries = [i.bib_entry for i in instances]
preds = self._predictor.predict_raw(bib_entries)
cleaned = [Prediction.parse_obj(BibEntryPredictor.postprocess(p)) for p in preds]
return cleaned
| 3,109 | 32.085106 | 89 |
py
|
mmda
|
mmda-main/src/ai2_internal/layout_parser/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
"""
import logging
import sys
import unittest
from .interface import Instance
from PIL import Image
from pathlib import Path
import os.path
from mmda.types.image import tobase64
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def get_images(self):
return [
tobase64(
Image.open(os.path.join(Path(os.path.dirname(__file__)).parent, "shared_test_fixtures", "page0.png"))
)
]
def test__predictions(self, container):
instances = [Instance(page_images=self.get_images())]
predictions = container.predict_batch(instances)
for prediction in predictions:
self.assertEqual(
set(g.type for g in prediction.groups),
{"Text", "Title"},
)
| 1,513 | 24.661017 | 117 |
py
|
mmda
|
mmda-main/src/ai2_internal/layout_parser/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/layout_parser/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
import logging
from typing import List
import torch
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal.api import BoxGroup
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.types import image
from mmda.types.document import Document
logger = logging.getLogger(__name__)
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
Input is a list of page images, base64-encoded"""
page_images: List[str] = Field(description="List of base64-encoded page images")
class Prediction(BaseModel):
"""Output is a set of bounding boxes with metadata"""
groups: List[BoxGroup] = Field(description="PDF Text Regions")
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
"""
weights_paths = ["lp://efficientdet/PubLayNet", "lp://efficientdet/MFD"]
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
"""
Performs the start-up operations required to
ready the model for inference.
LayoutPraser uses pre-trained PubLayNet and MFD models managed
by the underlying layoutparser tool:
https://layout-parser.readthedocs.io/en/latest/api_doc/models.html
"""
device = "cuda" if torch.cuda.is_available() else None
if device == "cuda":
logger.info("CUDA device detected, running model with GPU acceleration.")
else:
logger.info("No CUDA device detected, running model on CPU.")
self._lp_predictors = [
LayoutParserPredictor.from_pretrained(weights_path, device=device)
for weights_path in self._config.weights_paths
]
def predict_one(self, instance: Instance) -> Prediction:
"""
Should produce a single Prediction for the provided Instance.
Leverage your underlying model to perform this inference.
"""
images = [image.frombase64(im) for im in instance.page_images]
doc = Document(symbols="")
doc.annotate_images(images)
box_groups = []
for predictor in self._lp_predictors:
box_groups.extend(predictor.predict(doc))
return Prediction(groups=[BoxGroup.from_mmda(bg) for bg in box_groups])
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
return [self.predict_one(instance) for instance in instances]
| 3,946 | 32.449153 | 85 |
py
|
mmda
|
mmda-main/src/ai2_internal/citation_mentions/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
predict_batch(instances: List[Instance]) -> List[Prediction]
"""
import logging
import pathlib
import sys
import unittest
from ai2_internal import api
from ai2_internal.citation_mentions.interface import Instance
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
expected_mentions_text = [
"1",
"2",
"3",
"9",
"10",
"12",
"10",
"13",
"14",
"15",
"16",
"17",
"18",
"11",
"19",
"17",
"18",
"20",
"22",
"23",
"28",
"29",
"32",
"33",
"38",
"38",
"39",
"40",
"44"
]
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions(self, container):
pdf_path = pathlib.Path(__file__).resolve().parent / "data" / "arxiv-1906.08632-pages1-2.pdf"
doc = PDFPlumberParser(split_at_punctuation=True).parse(str(pdf_path))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
pages = [api.SpanGroup.from_mmda(sg) for sg in doc.pages]
instances = [Instance(symbols=doc.symbols, tokens=tokens, pages=pages)]
predictions = container.predict_batch(instances)
mmda_mentions = [mention.to_mmda() for mention in predictions[0].mentions]
doc.annotate(mentions=mmda_mentions)
mentions_text = [m.text for m in doc.mentions]
self.assertEqual(mentions_text, expected_mentions_text)
| 1,938 | 23.2375 | 101 |
py
|
mmda
|
mmda-main/src/ai2_internal/citation_mentions/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/citation_mentions/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
from typing import List
from pydantic import BaseModel, BaseSettings
from ai2_internal import api
from mmda.predictors.hf_predictors.mention_predictor import MentionPredictor
from mmda.types.document import Document
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
"""
symbols: str
tokens: List[api.SpanGroup]
pages: List[api.SpanGroup]
class Prediction(BaseModel):
"""
Describes the outcome of inference for one Instance
"""
mentions: List[api.SpanGroup]
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
"""
pass
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._predictor = MentionPredictor(artifacts_dir)
def predict_one(self, inst: Instance) -> Prediction:
"""
Should produce a single Prediction for the provided Instance.
Leverage your underlying model to perform this inference.
"""
doc = Document(symbols=inst.symbols)
doc.annotate(tokens=[sg.to_mmda() for sg in inst.tokens])
doc.annotate(pages=[sg.to_mmda() for sg in inst.pages])
prediction_span_groups = self._predictor.predict(doc)
doc.annotate(citation_mentions=prediction_span_groups)
return Prediction(mentions=[api.SpanGroup.from_mmda(sg) for sg in doc.citation_mentions])
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
return [self.predict_one(instance) for instance in instances]
| 2,867 | 31.590909 | 97 |
py
|
mmda
|
mmda-main/src/ai2_internal/bibentry_detection_predictor/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import json
import logging
import os
import pathlib
import sys
import unittest
from .. import api
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.types.annotation import SpanGroup as MmdaSpanGroup
from mmda.types.image import tobase64
from .interface import Instance
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
def resolve(file: str) -> str:
return os.path.join(pathlib.Path(os.path.dirname(__file__)), "data", file)
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def get_images(self, pdf_filename):
rasterizer = PDF2ImageRasterizer()
return rasterizer.rasterize(str(resolve(pdf_filename)), dpi=72)
def test__predictions(self, container):
pdf = "000026bab3c52aa8ff37dc3e155ffbcb506aa1f6.pdf"
doc = PDFPlumberParser(split_at_punctuation=True).parse(resolve(pdf))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
rows = [api.SpanGroup.from_mmda(sg) for sg in doc.rows]
pages = [api.SpanGroup.from_mmda(sg) for sg in doc.pages]
page_images = self.get_images(pdf)
encoded_page_images = [tobase64(img) for img in page_images]
doc.annotate_images(page_images)
instances = [Instance(
symbols=doc.symbols,
tokens=tokens,
rows=rows,
pages=pages,
page_images=encoded_page_images)]
predictions = container.predict_batch(instances)
for bib_entry in predictions[0].bib_entries:
self.assertEqual(bib_entry.box_group.type, "bib_entry")
for raw_box in predictions[0].raw_bib_entry_boxes:
# raw_bib_entry_boxes are SpanGroups but all data is within the box_group
self.assertEqual(raw_box.box_group.type, "raw_model_prediction")
expected_bib_count = 34
expected_raw_bib_count = 35
self.assertEqual(len(predictions[0].bib_entries), expected_bib_count)
self.assertEqual(len(predictions[0].raw_bib_entry_boxes), expected_raw_bib_count)
def test__no_resulting_bibs(self, container):
pdf = "no_bibs.pdf"
doc = PDFPlumberParser(split_at_punctuation=True).parse(resolve(pdf))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
rows = [api.SpanGroup.from_mmda(sg) for sg in doc.rows]
pages = [api.SpanGroup.from_mmda(sg) for sg in doc.pages]
page_images = self.get_images(pdf)
encoded_page_images = [tobase64(img) for img in page_images]
doc.annotate_images(page_images)
instances = [Instance(
symbols=doc.symbols,
tokens=tokens,
rows=rows,
pages=pages,
page_images=encoded_page_images)]
# should not error
predictions = container.predict_batch(instances)
self.assertEqual(len(predictions[0].bib_entries), 0)
self.assertEqual(len(predictions[0].raw_bib_entry_boxes), 0)
def test__spanless_bibs(self, container):
pdf = "spanless_bibs_3cf45514384bbb7d083ae53e19bdc22300e648ab.pdf" # 3cf45514384bbb7d083ae53e19bdc22300e648ab
doc = PDFPlumberParser(split_at_punctuation=True).parse(resolve(pdf))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
rows = [api.SpanGroup.from_mmda(sg) for sg in doc.rows]
pages = [api.SpanGroup.from_mmda(sg) for sg in doc.pages]
page_images = self.get_images(pdf)
encoded_page_images = [tobase64(img) for img in page_images]
doc.annotate_images(page_images)
instances = [Instance(
symbols=doc.symbols,
tokens=tokens,
rows=rows,
pages=pages,
page_images=encoded_page_images)]
# should not error
predictions = container.predict_batch(instances)
# A bib box overlapped others, causing it to end up with no spans
expected_bib_count = 118
expected_raw_bib_count = 119
self.assertEqual(len(predictions[0].bib_entries), expected_bib_count)
self.assertEqual(len(predictions[0].raw_bib_entry_boxes), expected_raw_bib_count)
| 5,174 | 32.823529 | 118 |
py
|
mmda
|
mmda-main/src/ai2_internal/bibentry_detection_predictor/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/bibentry_detection_predictor/interface.py
|
"""
This file contains the classes required by Semantic Scholar's
TIMO tooling.
You must provide a wrapper around your model, as well
as a definition of the objects it expects, and those it returns.
"""
from typing import List
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal import api
from mmda.predictors.d2_predictors.bibentry_detection_predictor import BibEntryDetectionPredictor
from mmda.types import image
from mmda.types.document import Document
from mmda.utils.tools import box_groups_to_span_groups
class Instance(BaseModel):
"""
Describes one Instance over which the model performs inference.
The fields below are examples only; please replace them with
appropriate fields for your model.
To learn more about declaring pydantic model fields, please see:
https://pydantic-docs.helpmanual.io/
"""
symbols: str
tokens: List[api.SpanGroup]
rows: List[api.SpanGroup]
pages: List[api.SpanGroup]
page_images: List[str] = Field(description="List of base64-encoded page images")
class Prediction(BaseModel):
"""
Describes the outcome of inference for one Instance
"""
bib_entries: List[api.SpanGroup]
raw_bib_entry_boxes: List[api.SpanGroup]
class PredictorConfig(BaseSettings):
"""
Configuration required by the model to do its work.
Uninitialized fields will be set via Environment variables.
These serve as a record of the ENV
vars the consuming application needs to set.
"""
BIB_ENTRY_DETECTION_PREDICTOR_SCORE_THRESHOLD: float = Field(default=0.6, description="Prediction accuracy score used to determine threshold of returned predictions")
class Predictor:
"""
Interface on to your underlying model.
This class is instantiated at application startup as a singleton.
You should initialize your model inside of it, and implement
prediction methods.
If you specified an artifacts.tar.gz for your model, it will
have been extracted to `artifacts_dir`, provided as a constructor
arg below.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
"""
Perform whatever start-up operations are required to get your
model ready for inference. This operation is performed only once
during the application life-cycle.
"""
self._predictor = BibEntryDetectionPredictor(self._artifacts_dir, self._config.BIB_ENTRY_DETECTION_PREDICTOR_SCORE_THRESHOLD)
def predict_one(self, inst: Instance) -> Prediction:
"""
Should produce a single Prediction for the provided Instance.
Leverage your underlying model to perform this inference.
"""
doc = Document(symbols=inst.symbols)
doc.annotate(tokens=[sg.to_mmda() for sg in inst.tokens])
doc.annotate(rows=[sg.to_mmda() for sg in inst.rows])
doc.annotate(pages=[sg.to_mmda() for sg in inst.pages])
images = [image.frombase64(im) for im in inst.page_images]
doc.annotate_images(images)
processed_bib_entry_box_groups, original_box_groups = self._predictor.predict(
doc
)
# generate SpanGroups
if len(processed_bib_entry_box_groups) > 0:
bib_entry_span_groups = box_groups_to_span_groups(processed_bib_entry_box_groups, doc, pad_x=True, center=True)
doc.annotate(bib_entries=bib_entry_span_groups)
# remove boxes from spans to create entity-like SpanGroups with BoxGroups
# (where the only set of boxes is on SpanGroup.box_group)
no_span_box_span_groups = [
api.SpanGroup(
# omit s.box when generating list of spans
spans=[api.Span(start=s.start, end=s.end) for s in sg.spans],
box_group=api.BoxGroup.from_mmda(sg.box_group),
id=sg.id
)
for sg in doc.bib_entries
]
prediction = Prediction(
# filter out span-less SpanGroups which occasionally occur
bib_entries=[sg for sg in no_span_box_span_groups if len(sg.spans) != 0],
# retain the original model output
raw_bib_entry_boxes=[api.SpanGroup(spans=[], box_group=api.BoxGroup.from_mmda(bg), id=bg.id) for bg in original_box_groups]
)
else:
prediction = Prediction(
bib_entries=[],
raw_bib_entry_boxes=[]
)
return prediction
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
If your model gets performance benefits from batching during inference,
implement that here, explicitly.
Otherwise, you can leave this method as-is and just implement
`predict_one()` above. The default implementation here passes
each Instance into `predict_one()`, one at a time.
The size of the batches passed into this method is configurable
via environment variable by the calling application.
"""
return [self.predict_one(instance) for instance in instances]
| 5,523 | 36.073826 | 170 |
py
|
mmda
|
mmda-main/src/ai2_internal/svm_word_predictor/integration_test.py
|
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
To test your code, create `Instance`s and make normal `TestCase`
assertions against the returned `Prediction`s.
e.g.
```
def test_prediction(self, container):
instances = [Instance(), Instance()]
predictions = container.predict_batch(instances)
self.assertEqual(len(instances), len(predictions)
self.assertEqual(predictions[0].field1, "asdf")
self.assertGreatEqual(predictions[1].field2, 2.0)
```
"""
import gzip
import json
import logging
import os
import sys
import unittest
from .interface import Instance, Prediction
from ai2_internal import api
from mmda.types.document import Document
FIXTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_fixtures")
try:
from timo_interface import with_timo_container
except ImportError as e:
logging.warning("""
This test can only be run by a TIMO test runner. No tests will run.
You may need to add this file to your project's pytest exclusions.
""")
sys.exit(0)
def resolve(file: str) -> str:
return os.path.join(os.path.dirname(__file__), "test_fixtures", file)
def read_fixture_doc(filename):
path = resolve(filename)
with gzip.open(path, "r") as f:
doc_json = json.loads(f.read())
doc = Document.from_json(doc_json)
return doc
@with_timo_container
class TestInterfaceIntegration(unittest.TestCase):
def test__predictions(self, container):
doc_file = resolve("test_doc.json")
with open(doc_file) as f:
doc = Document.from_json(json.load(f))
tokens = [api.SpanGroup.from_mmda(sg) for sg in doc.tokens]
instances = [Instance(symbols=doc.symbols, tokens=tokens)]
predictions = container.predict_batch(instances)
prediction = predictions[0]
self.assertTrue(len(prediction.words) <= len(tokens))
| 2,146 | 25.182927 | 87 |
py
|
mmda
|
mmda-main/src/ai2_internal/svm_word_predictor/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/ai2_internal/svm_word_predictor/interface.py
|
from typing import List
from pydantic import BaseModel, BaseSettings, Field
from ai2_internal.api import SpanGroup
from mmda.predictors.sklearn_predictors.svm_word_predictor import SVMWordPredictor
from mmda.types.document import Document
class Instance(BaseModel):
"""
Inference input for a single paper.
"""
symbols: str = Field(description="Extracted PDF document text")
tokens: List[SpanGroup] = Field(description="The tokens to coerce into words")
class Prediction(BaseModel):
"""
Inference output for a single paper.
"""
words: List[SpanGroup] = Field(description="Input tokens coerced into words. Includes cleaned-up text.")
class PredictorConfig(BaseSettings):
hyphen_threshold: float = Field(
description="Score threshold to decide whether hyphenated text represents a line-break or a compound word",
default=-1.5
)
class Predictor:
"""
This class is instantiated at application startup as a singleton,
and is used by the TIMO framework to interface with the underlying
DWP predictor.
"""
_config: PredictorConfig
_artifacts_dir: str
def __init__(self, config: PredictorConfig, artifacts_dir: str):
self._config = config
self._artifacts_dir = artifacts_dir
self._load_model()
def _load_model(self) -> None:
self._predictor = SVMWordPredictor.from_directory(
dir=self._artifacts_dir,
threshold=self._config.hyphen_threshold
)
def predict_one(self, instance: Instance) -> Prediction:
doc = Document(instance.symbols)
doc.annotate(tokens=[t.to_mmda() for t in instance.tokens])
words = self._predictor.predict(doc)
# RE: https://github.com/allenai/scholar/issues/36200
for word in words:
if word.text:
word.text = word.text.replace("\u0000", "")
return Prediction(
words=[SpanGroup.from_mmda(w) for w in words]
)
def predict_batch(self, instances: List[Instance]) -> List[Prediction]:
"""
Method called by the client application. One or more Instances will
be provided, and the caller expects a corresponding Prediction for
each one.
"""
return [self.predict_one(instance) for instance in instances]
| 2,335 | 30.567568 | 115 |
py
|
mmda
|
mmda-main/tests/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/tests/test_predictors/test_vila_predictors.py
|
import json
import os
import pathlib
import unittest
from PIL import Image
from mmda.types.document import Document
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.predictors.hf_predictors.vila_predictor import IVILAPredictor, HVILAPredictor
from mmda.predictors.hf_predictors.token_classification_predictor import (
IVILATokenClassificationPredictor,
HVILATokenClassificationPredictor,
)
class TestFigureVilaPredictors(unittest.TestCase):
@classmethod
def setUp(cls):
cls.fixture_path = pathlib.Path(__file__).parent.parent / 'fixtures'
cls.DOCBANK_LABEL_MAP = {
"0": "paragraph",
"1": "title",
"2": "equation",
"3": "reference",
"4": "section",
"5": "list",
"6": "table",
"7": "caption",
"8": "author",
"9": "abstract",
"10": "footer",
"11": "date",
"12": "figure",
}
cls.DOCBANK_LABEL_MAP = {int(key): val for key, val in cls.DOCBANK_LABEL_MAP.items()}
cls.S2VL_LABEL_MAP = {
"0": "Title",
"1": "Author",
"2": "Abstract",
"3": "Keywords",
"4": "Section",
"5": "Paragraph",
"6": "List",
"7": "Bibliography",
"8": "Equation",
"9": "Algorithm",
"10": "Figure",
"11": "Table",
"12": "Caption",
"13": "Header",
"14": "Footer",
"15": "Footnote",
}
cls.S2VL_LABEL_MAP = {int(key): val for key, val in cls.S2VL_LABEL_MAP.items()}
def test_vila_predictors(self):
layout_predictor = LayoutParserPredictor.from_pretrained(
"lp://efficientdet/PubLayNet"
)
pdfplumber_parser = PDFPlumberParser()
rasterizer = PDF2ImageRasterizer()
doc = pdfplumber_parser.parse(input_pdf_path=self.fixture_path / "1903.10676.pdf")
images = rasterizer.rasterize(input_pdf_path=self.fixture_path / "1903.10676.pdf", dpi=72)
doc.annotate_images(images)
layout_regions = layout_predictor.predict(doc)
doc.annotate(blocks=layout_regions)
ivilaA = IVILATokenClassificationPredictor.from_pretrained(
"allenai/ivila-block-layoutlm-finetuned-docbank"
)
resA = ivilaA.predict(doc, subpage_per_run=2)
del ivilaA
ivilaB = IVILAPredictor.from_pretrained(
"allenai/ivila-block-layoutlm-finetuned-docbank",
agg_level="block",
added_special_sepration_token="[BLK]",
)
resB = ivilaB.predict(doc)
del ivilaB
assert [ele.spans for ele in resA] == [ele.spans for ele in resB]
assert [ele.type for ele in resA] == [self.DOCBANK_LABEL_MAP[ele.type] for ele in resB]
hvilaA = HVILATokenClassificationPredictor.from_pretrained(
"allenai/hvila-row-layoutlm-finetuned-docbank"
)
resA = hvilaA.predict(doc, subpage_per_run=2)
del hvilaA
hvilaB = HVILAPredictor.from_pretrained(
"allenai/hvila-row-layoutlm-finetuned-docbank",
agg_level="row",
added_special_sepration_token="[BLK]",
)
resB = hvilaB.predict(doc)
del hvilaB
assert [ele.spans for ele in resA] == [ele.spans for ele in resB]
assert [ele.type for ele in resA] == [self.DOCBANK_LABEL_MAP[ele.type] for ele in resB]
ivilaA = IVILATokenClassificationPredictor.from_pretrained(
"allenai/ivila-row-layoutlm-finetuned-s2vl-v2"
)
resA = ivilaA.predict(doc, subpage_per_run=2)
del ivilaA
ivilaB = IVILAPredictor.from_pretrained(
"allenai/ivila-row-layoutlm-finetuned-s2vl-v2",
agg_level="row",
added_special_sepration_token="[BLK]",
)
resB = ivilaB.predict(doc)
del ivilaB
assert [ele.spans for ele in resA] == [ele.spans for ele in resB]
assert [ele.type for ele in resA] == [self.S2VL_LABEL_MAP[ele.type] for ele in resB]
def test_vila_predictors_with_special_unicode_inputs(self):
test_doc_path = self.fixture_path / "unicode-test.json"
with open(test_doc_path, 'r') as fp:
res = json.load(fp)
doc = Document.from_json(res)
doc.annotate_images([Image.new("RGB", (596, 842))])
ivilaA = IVILATokenClassificationPredictor.from_pretrained(
"allenai/ivila-row-layoutlm-finetuned-s2vl-v2"
)
ivilaA.predict(doc, subpage_per_run=2)
| 4,777 | 31.951724 | 98 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_svm_word_predictor.py
|
"""
Tests for SVM Word Predictor
@kylel
"""
import json
import os
import unittest
from typing import List, Optional, Set
import numpy as np
from mmda.predictors.sklearn_predictors.svm_word_predictor import (
SVMClassifier,
SVMWordPredictor,
)
from mmda.types import Document, Span, SpanGroup
class TestSVMClassifier(unittest.TestCase):
@classmethod
def setUp(self):
self.fixture_path = os.path.join(os.path.dirname(__file__), "../fixtures/")
self.classifier = SVMClassifier.from_path(
tar_path=os.path.join(
self.fixture_path, "svm_word_predictor/svm_word_predictor.tar.gz"
)
)
with open(
os.path.join(self.fixture_path, "svm_word_predictor/pos_words.txt")
) as f_in:
self.pos_words = [line.strip() for line in f_in]
with open(
os.path.join(self.fixture_path, "svm_word_predictor/neg_words.txt")
) as f_in:
self.neg_words = [line.strip() for line in f_in]
def test_batch_predict_unit(self):
pos_words = [
"wizard-of-oz",
"moment-to-moment",
"batch-to-batch",
"Seven-day-old",
"slow-to-fast",
"HTLV-1-associated",
"anti-E-selectin",
]
neg_words = [
"sig-nal-to-noise",
"nonre-turn-to-zero",
"comput-er-assisted",
"concentra-tion-dependent",
"ob-ject-oriented",
"cog-nitive-behavioral",
"deci-sion-makers",
]
THRESHOLD = -1.5
pos_results = self.classifier.batch_predict(
words=pos_words, threshold=THRESHOLD
)
self.assertEqual(len(pos_results), len(pos_words))
self.assertTrue(all([r.is_edit is False for r in pos_results]))
neg_results = self.classifier.batch_predict(
words=neg_words, threshold=THRESHOLD
)
self.assertEqual(len(neg_results), len(neg_words))
self.assertTrue(all([r.is_edit is True for r in neg_results]))
def test_batch_predict_eval(self):
"""
As a guideline, we want Recall to be close to 1.0 because we want
the model to favor predicting things as "negative" (i.e. not an edit).
If the classifier predicts a "1", then essentially we don't do anything.
Meaning in all cases where the ground truth is "1" (dont do anything),
we want to recover all these cases nearly perfectly, and ONLY
take action when absolutely safe.
THRESHOLD = -1.7 --> P: 0.9621262458471761 R: 1.0
THRESHOLD = -1.6 --> P: 0.9674346429879954 R: 1.0
THRESHOLD = -1.5 --> P: 0.9716437941036409 R: 1.0
THRESHOLD = -1.4 --> P: 0.9755705281460552 R: 0.9999554446622705
THRESHOLD = -1.0 --> P: 0.9866772193641999 R: 0.9998217786490822
THRESHOLD = -0.5 --> P: 0.9955352184633155 R: 0.9984405631794689
THRESHOLD = 0.0 --> P: 0.9985657299090135 R: 0.9926483692746391
THRESHOLD = 1.0 --> P: 0.9997759019944723 R: 0.8944929602566387
"""
THRESHOLD = -1.5
preds_pos = self.classifier.batch_predict(
words=self.pos_words, threshold=THRESHOLD
)
self.assertEqual(len(preds_pos), len(self.pos_words))
preds_pos_as_ints = [int(r.is_edit is False) for r in preds_pos]
tp = sum(preds_pos_as_ints)
fn = len(preds_pos_as_ints) - tp
preds_neg = self.classifier.batch_predict(
words=self.neg_words, threshold=THRESHOLD
)
self.assertEqual(len(preds_neg), len(self.neg_words))
preds_neg_as_ints = [int(r.is_edit is True) for r in preds_neg]
tn = sum(preds_neg_as_ints)
fp = len(preds_neg_as_ints) - tn
self.assertEqual(tp + fn + tn + fp, len(preds_pos) + len(preds_neg))
p = tp / (tp + fp)
r = tp / (tp + fn)
# uncomment for debugging
# print(f"P: {p} R: {r}")
self.assertGreaterEqual(p, 0.9)
self.assertGreaterEqual(r, 0.9)
def test_get_features(self):
(
all_features,
word_id_to_feature_ids,
) = self.classifier._get_features(words=self.pos_words)
self.assertEqual(len(word_id_to_feature_ids), len(self.pos_words))
self.assertEqual(
all_features.shape[0],
sum([len(feature) for feature in word_id_to_feature_ids.values()]),
)
(
all_features,
word_id_to_feature_ids,
) = self.classifier._get_features(words=self.neg_words)
self.assertEqual(len(word_id_to_feature_ids), len(self.neg_words))
self.assertEqual(
all_features.shape[0],
sum([len(feature) for feature in word_id_to_feature_ids.values()]),
)
def test_exception_with_start_or_end_hyphen(self):
words = ["-wizard-of-", "wizard-of-"]
for word in words:
with self.assertRaises(ValueError):
self.classifier.batch_predict(words=[word], threshold=0.0)
class TestSVMWordPredictor(unittest.TestCase):
@classmethod
def setUp(self):
self.fixture_path = os.path.join(os.path.dirname(__file__), "../fixtures/")
self.predictor = SVMWordPredictor.from_path(
tar_path=os.path.join(
self.fixture_path, "svm_word_predictor/svm_word_predictor.tar.gz"
)
)
with open(
os.path.join(
self.fixture_path,
"types/20fdafb68d0e69d193527a9a1cbe64e7e69a3798__pdfplumber_doc.json",
)
) as f_in:
doc_dict = json.load(f_in)
self.doc = Document.from_json(doc_dict=doc_dict)
def test_predict_no_hyphen(self):
doc = Document.from_json(
doc_dict={
"symbols": "I am the wizard-of-oz.",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 1}]},
{"id": 1, "spans": [{"start": 2, "end": 4}]},
{"id": 2, "spans": [{"start": 5, "end": 8}]},
{"id": 3, "spans": [{"start": 9, "end": 15}]},
{"id": 4, "spans": [{"start": 15, "end": 16}]},
{"id": 5, "spans": [{"start": 16, "end": 18}]},
{"id": 6, "spans": [{"start": 18, "end": 19}]},
{"id": 7, "spans": [{"start": 19, "end": 21}]},
{"id": 8, "spans": [{"start": 21, "end": 22}]},
],
}
)
words = self.predictor.predict(document=doc)
self.assertEqual(len(words), 5)
doc.annotate(words=words)
self.assertListEqual(
[w.text for w in words], ["I", "am", "the", "wizard-of-oz", "."]
)
def test_predict(self):
words = self.predictor.predict(document=self.doc)
# double-check number of units
self.assertLess(len(words), len(self.doc.tokens))
# double-check can annotate
self.doc.annotate(words=words)
# after annotating, double-check words against tokens
for word in self.doc.words:
tokens_in_word = word.tokens
spans_in_tokens_in_word = [
span for token in tokens_in_word for span in token.spans
]
# if word is a single token, then it should be the same as the token
if len(tokens_in_word) == 1:
self.assertEqual(tokens_in_word[0].text, word.text)
self.assertEqual(tokens_in_word[0].spans, word.spans)
else:
# otherwise, most token units should be substring of word
overlap = np.mean([token.text in word.text for token in tokens_in_word])
self.assertGreaterEqual(overlap, 0.5)
# words basically have a single contiguous span
# TODO: though this may change if we affect reading order
self.assertEqual(len(word.spans), 1)
# word span should align w token span somehow
self.assertEqual(
word.spans[0],
Span(
start=min([span.start for span in spans_in_tokens_in_word]),
end=max([span.end for span in spans_in_tokens_in_word]),
),
)
# uncomment for debugging:
# for word in self.doc.words:
# token_text = str([t.text for t in word.tokens])
# if len(word.tokens) > 1 and "-" in token_text:
# print(f"{token_text}\t-->\t{word.text}")
# for word in self.doc.words:
# token_text = str([t.text for t in word.tokens])
# if len(word.tokens) > 1 and "." in token_text:
# print(f"{token_text}\t-->\t{word.text}")
def test_validate_tokenization(self):
doc = Document.from_json(
doc_dict={
"symbols": "I am the wizard-of-oz.",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 1}]},
{"id": 1, "spans": [{"start": 2, "end": 4}]},
{"id": 2, "spans": [{"start": 5, "end": 8}]},
{"id": 3, "spans": [{"start": 9, "end": 15}]},
{"id": 4, "spans": [{"start": 15, "end": 16}]},
{"id": 5, "spans": [{"start": 16, "end": 18}]},
{"id": 6, "spans": [{"start": 18, "end": 19}]},
{"id": 7, "spans": [{"start": 19, "end": 21}]},
{"id": 8, "spans": [{"start": 21, "end": 22}]},
],
}
)
self.predictor._validate_tokenization(document=doc)
# missing token id
with self.assertRaises(ValueError):
doc = Document.from_json(
doc_dict={
"symbols": "I",
"tokens": [{"spans": [{"start": 0, "end": 1}]}],
}
)
self.predictor._validate_tokenization(document=doc)
# hyphen not its own token
with self.assertRaises(ValueError):
doc = Document.from_json(
doc_dict={
"symbols": "wizard-of-oz",
"tokens": [{"spans": [{"start": 0, "end": 9}]}],
}
)
self.predictor._validate_tokenization(document=doc)
def test_cluster_tokens_by_whitespace(self):
clusters = self.predictor._cluster_tokens_by_whitespace(document=self.doc)
for token_ids in clusters:
if len(token_ids) == 1:
token = self.doc.tokens[token_ids[0]]
self.assertEqual(
self.doc.symbols[token.spans[0].start : token.spans[0].end],
token.text,
)
else:
tokens = [self.doc.tokens[token_id] for token_id in token_ids]
spans = [span for token in tokens for span in token.spans]
big_span = Span.small_spans_to_big_span(spans=spans)
self.assertEqual(
self.doc.symbols[big_span.start : big_span.end],
"".join([token.text for token in tokens]),
)
def test_predict_with_whitespace(self):
doc = Document.from_json(
doc_dict={
"symbols": "I am the wizard-of-oz.",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 1}]},
{"id": 1, "spans": [{"start": 2, "end": 4}]},
{"id": 2, "spans": [{"start": 5, "end": 8}]},
{"id": 3, "spans": [{"start": 9, "end": 15}]},
{"id": 4, "spans": [{"start": 15, "end": 16}]},
{"id": 5, "spans": [{"start": 16, "end": 18}]},
{"id": 6, "spans": [{"start": 18, "end": 19}]},
{"id": 7, "spans": [{"start": 19, "end": 21}]},
{"id": 8, "spans": [{"start": 21, "end": 22}]},
],
}
)
(
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) = self.predictor._predict_with_whitespace(document=doc)
self.assertDictEqual(
token_id_to_word_id, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 3, 6: 3, 7: 3, 8: 3}
)
self.assertDictEqual(
word_id_to_token_ids, {0: [0], 1: [1], 2: [2], 3: [3, 4, 5, 6, 7, 8]}
)
self.assertDictEqual(
word_id_to_text, {0: "I", 1: "am", 2: "the", 3: "wizard-of-oz."}
)
def test_group_adjacent_with_exceptions(self):
adjacent = [0, 1, 2, 3]
# alternating
self.assertListEqual(
self.predictor._group_adjacent_with_exceptions(
adjacent=adjacent, exception_ids={1, 3}
),
[[0], [1], [2], [3]],
)
# start
self.assertListEqual(
self.predictor._group_adjacent_with_exceptions(
adjacent=adjacent, exception_ids={0}
),
[[0], [1, 2, 3]],
)
# end
self.assertListEqual(
self.predictor._group_adjacent_with_exceptions(
adjacent=adjacent, exception_ids={3}
),
[[0, 1, 2], [3]],
)
# none
self.assertListEqual(
self.predictor._group_adjacent_with_exceptions(
adjacent=adjacent, exception_ids=set()
),
[[0, 1, 2, 3]],
)
# all
self.assertListEqual(
self.predictor._group_adjacent_with_exceptions(
adjacent=adjacent, exception_ids={0, 1, 2, 3}
),
[[0], [1], [2], [3]],
)
def test_find_hyphen_word_candidates(self):
(
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) = self.predictor._predict_with_whitespace(document=self.doc)
hyphen_word_candidates = self.predictor._find_hyphen_word_candidates(
tokens=self.doc.tokens,
token_id_to_word_id=token_id_to_word_id,
word_id_to_token_ids=word_id_to_token_ids,
word_id_to_text=word_id_to_text,
)
# verify the outputs correspond to hyphenated words
for prefix_word_id, suffix_word_id in hyphen_word_candidates:
prefix_word = word_id_to_text[prefix_word_id]
suffix_word = word_id_to_text[suffix_word_id]
self.assertTrue("-" in prefix_word + suffix_word)
# TODO: fix this test
def test_with_hyphen_boundaries_not_candidates(self):
doc = Document.from_json(
doc_dict={
"symbols": "COVID- 19",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 5}]},
{"id": 1, "spans": [{"start": 5, "end": 6}]},
{"id": 2, "spans": [{"start": 7, "end": 9}]},
],
}
)
(
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) = self.predictor._predict_with_whitespace(document=doc)
hyphen_word_candidates = self.predictor._find_hyphen_word_candidates(
tokens=doc.tokens,
token_id_to_word_id=token_id_to_word_id,
word_id_to_token_ids=word_id_to_token_ids,
word_id_to_text=word_id_to_text,
)
def test_keep_punct_as_words(self):
doc = Document.from_json(
doc_dict={
"symbols": "I am, !the@ wiz ard-of-oz.",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 1}]},
{"id": 1, "spans": [{"start": 2, "end": 4}]},
{"id": 2, "spans": [{"start": 4, "end": 5}]},
{"id": 3, "spans": [{"start": 6, "end": 7}]},
{"id": 4, "spans": [{"start": 7, "end": 10}]},
{"id": 5, "spans": [{"start": 10, "end": 11}]},
{"id": 6, "spans": [{"start": 12, "end": 15}]},
{"id": 7, "spans": [{"start": 16, "end": 19}]},
{"id": 8, "spans": [{"start": 19, "end": 20}]},
{"id": 9, "spans": [{"start": 20, "end": 22}]},
{"id": 10, "spans": [{"start": 22, "end": 23}]},
{"id": 11, "spans": [{"start": 23, "end": 25}]},
{"id": 12, "spans": [{"start": 25, "end": 26}]},
],
}
)
# stuff as it comes out of whitespace tokenization
token_id_to_word_id = {
0: 0,
1: 1,
2: 1,
3: 2,
4: 2,
5: 2,
6: 3,
7: 4,
8: 4,
9: 4,
10: 4,
11: 4,
12: 4,
}
word_id_to_token_ids = {
0: [0],
1: [1, 2],
2: [3, 4, 5],
3: [6],
4: [7, 8, 9, 10, 11, 12],
}
word_id_to_text = {0: "I", 1: "am,", 2: "!the@", 3: "wiz", 4: "ard-of-oz."}
# test that punctuation is kept as its own word, except for ones like hyphens
(
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) = self.predictor._keep_punct_as_words(
document=doc,
word_id_to_token_ids=word_id_to_token_ids,
punct_as_words=",!@.", # not including hyphens
)
self.assertDictEqual(
token_id_to_word_id,
{
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 7,
9: 7,
10: 7,
11: 7,
12: 8,
},
)
self.assertDictEqual(
word_id_to_token_ids,
{
0: [0],
1: [1],
2: [2],
3: [3],
4: [4],
5: [5],
6: [6],
7: [7, 8, 9, 10, 11],
8: [12],
},
)
self.assertDictEqual(
word_id_to_text,
{
0: "I",
1: "am",
2: ",",
3: "!",
4: "the",
5: "@",
6: "wiz",
7: "ard-of-oz",
8: ".",
},
)
def test_works_with_newlines(self):
doc = Document.from_json(
doc_dict={
"symbols": "I am\nthe wizard-\nof-oz.",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 1}]},
{"id": 1, "spans": [{"start": 2, "end": 4}]},
{"id": 2, "spans": [{"start": 5, "end": 8}]},
{"id": 3, "spans": [{"start": 9, "end": 15}]},
{"id": 4, "spans": [{"start": 15, "end": 16}]},
{"id": 5, "spans": [{"start": 17, "end": 19}]},
{"id": 6, "spans": [{"start": 19, "end": 20}]},
{"id": 7, "spans": [{"start": 20, "end": 22}]},
{"id": 8, "spans": [{"start": 22, "end": 23}]},
],
}
)
words = self.predictor.predict(document=doc)
self.assertLess(len(words), len(doc.tokens))
doc.annotate(words=words)
self.assertEqual(doc.tokens[0].spans, doc.words[0].spans) # I
self.assertEqual(doc.tokens[1].spans, doc.words[1].spans) # am
self.assertEqual(doc.tokens[2].spans, doc.words[2].spans) # the
self.assertEqual(doc.tokens[8].spans, doc.words[4].spans) # .
# wizard-of-oz
self.assertEqual(doc.words[3].spans, [Span(start=9, end=22, box=None)])
self.assertEqual(doc.words[3].text, "wizard-of-oz")
def test_works_with_cross_page_boxes(self):
doc = Document.from_json(
{
"symbols": "I am\nthe wizard-\nof-oz.",
"tokens": [
{
"id": 0,
"spans": [
{
"start": 0,
"end": 1,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 0,
},
}
],
},
{
"id": 1,
"spans": [
{
"start": 2,
"end": 4,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 1,
},
}
],
},
{
"id": 2,
"spans": [
{
"start": 5,
"end": 8,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 2,
},
}
],
},
{
"id": 3,
"spans": [
{
"start": 9,
"end": 15,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 3,
},
}
],
},
{
"id": 4,
"spans": [
{
"start": 15,
"end": 16,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 4,
},
}
],
},
{
"id": 5,
"spans": [
{
"start": 17,
"end": 19,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 5,
},
}
],
},
{
"id": 6,
"spans": [
{
"start": 19,
"end": 20,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 6,
},
}
],
},
{
"id": 7,
"spans": [
{
"start": 20,
"end": 22,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 7,
},
}
],
},
{
"id": 8,
"spans": [
{
"start": 22,
"end": 23,
"box": {
"left": 0.1,
"top": 0.2,
"width": 0.3,
"height": 0.4,
"page": 8,
},
}
],
},
],
}
)
words = self.predictor.predict(document=doc)
self.assertLess(len(words), len(doc.tokens))
doc.annotate(words=words)
def test_works_with_empty_tokens(self):
doc = Document.from_json(
doc_dict={
"symbols": "I am the wizard-of-oz.",
"tokens": [
{"id": 0, "spans": [{"start": 0, "end": 1}]},
{"id": 1, "spans": [{"start": 2, "end": 4}]},
{"id": 2, "spans": [{"start": 5, "end": 8}]},
{"id": 3, "spans": [{"start": 8, "end": 8}]},
{"id": 4, "spans": [{"start": 9, "end": 15}]},
{"id": 5, "spans": [{"start": 15, "end": 16}]},
{"id": 6, "spans": [{"start": 16, "end": 18}]},
{"id": 7, "spans": [{"start": 18, "end": 19}]},
{"id": 8, "spans": [{"start": 19, "end": 19}]},
{"id": 9, "spans": [{"start": 19, "end": 21}]},
{"id": 10, "spans": [{"start": 21, "end": 22}]},
],
}
)
words = self.predictor.predict(document=doc)
doc.annotate(words=words)
| 27,037 | 37.189266 | 88 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_bibentry_predictor.py
|
import unittest
from mmda.predictors.hf_predictors.bibentry_predictor.types import (
BibEntryPredictionWithSpan,
StringWithSpan
)
from mmda.predictors.hf_predictors.bibentry_predictor import utils
from mmda.types.annotation import SpanGroup
from mmda.types.span import Span
class TestBibEntryPredictor(unittest.TestCase):
def test__map_raw_predictions_to_mmda(self):
sg = SpanGroup(spans=[Span(start=17778, end=17832, box=None), Span(start=20057, end=20233, box=None)])
raw_prediction = BibEntryPredictionWithSpan(
citation_number=StringWithSpan(content='10', start=0, end=2),
authors=[
StringWithSpan(content='Srivastava, K.', start=4, end=18),
StringWithSpan(content='V.B. Upadhyay', start=23, end=36)
],
title=StringWithSpan(content='Effect of Phytoecdysteroid on Length of Silk Filament and\nNon-Breakable Filament Length of Multivoltine\nMulberry Silkworm B. mori Linn', start=45, end=179),
journal_venue_or_event=StringWithSpan(content='Academic Journal\nof Entomology', start=181, end=211),
year=None,
doi=None,
url=None
)
# Real world example
total_doc_text = "." * sg.spans[0].start \
+ "10. Srivastava, K. and V.B. Upadhyay, 2012b. Effect of" \
+ "." * (sg.spans[1].start - sg.spans[0].end) \
+ "Phytoecdysteroid on Length of Silk Filament and\nNon-Breakable Filament Length of Multivoltine\nMulberry Silkworm B. mori Linn. Academic Journal\nof Entomology, 5 ( 3 ) : 174-181."
prediction = utils.map_raw_predictions_to_mmda([sg], [raw_prediction])
self.assertEqual(total_doc_text[prediction.bib_entry_number[0].start:prediction.bib_entry_number[0].end], "10")
self.assertEqual(total_doc_text[prediction.bib_entry_authors[0].start:prediction.bib_entry_authors[0].end], "Srivastava, K.")
self.assertEqual(total_doc_text[prediction.bib_entry_authors[1].start:prediction.bib_entry_authors[1].end], "V.B. Upadhyay")
self.assertEqual(len(prediction.bib_entry_title[0].spans), 2)
self.assertEqual(total_doc_text[prediction.bib_entry_title[0].spans[0].start:prediction.bib_entry_title[0].spans[0].end], "Effect of")
self.assertEqual(total_doc_text[prediction.bib_entry_title[0].spans[1].start:prediction.bib_entry_title[0].spans[1].end], "Phytoecdysteroid on Length of Silk Filament and\nNon-Breakable Filament Length of Multivoltine\nMulberry Silkworm B. mori Linn")
self.assertEqual(total_doc_text[prediction.bib_entry_venue_or_event[0].start:prediction.bib_entry_venue_or_event[0].end], "Academic Journal\nof Entomology")
self.assertEqual(prediction.bib_entry_year, [])
self.assertEqual(prediction.bib_entry_doi, [])
self.assertEqual(prediction.bib_entry_url, [])
| 2,922 | 57.46 | 259 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_figure_table_predictors.py
|
import json
import pickle
import unittest
from collections import defaultdict
import pathlib
import pytest
from ai2_internal.api import Relation
from mmda.predictors.heuristic_predictors.figure_table_predictors import FigureTablePredictions
from mmda.types import Document, BoxGroup
from mmda.types.box import Box
from mmda.types.span import Span
class TestFigureCaptionPredictor(unittest.TestCase):
@classmethod
def setUp(cls):
cls.fixture_path = pathlib.Path(__file__).parent.parent
with open(cls.fixture_path / 'fixtures/doc_fixture_e5910c027af0ee9c1901c57f6579d903aedee7f4.pkl',
'rb') as file_handle:
doc_json = pickle.load(file_handle)
cls.doc = Document.from_json(doc_json)
assert cls.doc.pages
assert cls.doc.tokens
assert cls.doc.blocks
assert cls.doc.vila_span_groups
with open(cls.fixture_path / 'fixtures/doc_fixture_2149e0c1106e6dfa36ea787167d6611cf88b69cb.json',
'rb') as file_handle:
dic_json = json.load(file_handle)
cls.doc_2 = Document.from_json(dic_json['doc'])
layout_equations = [BoxGroup.from_json(entry) for entry in dic_json['layout_equations']]
cls.doc_2.annotate(blocks=layout_equations)
with open(cls.fixture_path / 'fixtures/figure_table_predictions.json', 'r') as file:
cls.figure_predictions = json.load(file)
cls.figure_table_predictor = FigureTablePredictions(cls.doc)
def test_merge_boxes(self):
result = self.figure_table_predictor.merge_boxes(self.doc.blocks, defaultdict(list))
assert list(result[0].keys()) == [0, 2, 3, 7]
assert isinstance(result[0][0][0], Span)
def test_get_figure_caption_distance(self):
distance = FigureTablePredictions._get_object_caption_distance(
Box(l=0.2, t=0.2, w=0.1, h=0.1, page=0), Box(l=0.3, t=0.3, w=0.1, h=0.1, page=0))
assert distance == 900
distance = FigureTablePredictions._get_object_caption_distance(
Box(l=0.2, t=0.2, w=0.1, h=0.1, page=0), Box(l=0.2, t=0.3, w=0.1, h=0.1, page=0))
assert distance == pytest.approx(0.15)
def test_generate_map_of_layout_to_tokens(self):
"""
Test that the function generates a map of layout to tokens using
"""
vila_caption = FigureTablePredictions._filter_span_group(
self.doc.vila_span_groups, caption_content='fig', span_group_types=['Caption'])
vila_caption_dict = FigureTablePredictions._create_dict_of_pages_spans_vila(vila_caption)
result = self.figure_table_predictor.generate_map_of_layout_to_tokens(
vila_caption_dict,
defaultdict(list), defaultdict(list))
assert list(result.keys()) == []
def test_predict_e5910c027af0ee9c1901c57f6579d903aedee7f4(self):
"""
Test that the function generates a map of layout to tokens using
for doc_fixture_e5910c027af0ee9c1901c57f6579d903aedee7f4.pkl
"""
result = self.figure_table_predictor.predict()
assert isinstance(result, dict)
assert list(result.keys()) == ['figures', 'figure_captions', 'figure_to_figure_captions', 'tables',
'table_captions',
'table_to_table_captions', ]
assert len(result['figures']) == 4
assert len(result['tables']) == 4
assert isinstance(result['figure_to_figure_captions'][0], Relation)
assert isinstance(result['table_to_table_captions'][0], Relation)
assert [figure.to_json() for figure in result['figures']] == [{'boxes': [{'height': 0.130624674787425,
'left': 0.5021962683185254,
'page': 0,
'top': 0.3574526237718987,
'width': 0.3930938321780535}]},
{'boxes': [{'height': 0.21034525861643782,
'left': 0.08724006952023973,
'page': 2,
'top': 0.09557842485832446,
'width': 0.3754700804068372}],
'id': 1},
{'boxes': [{'height': 0.31222110318652835,
'left': 0.08188235294117646,
'page': 3,
'top': 0.08723311954074436,
'width': 0.37919526861851516}],
'id': 2},
{'boxes': [{'height': 0.3527590433756511,
'left': 0.09958468543158637,
'page': 7,
'top': 0.08601251274648339,
'width': 0.8034834020278033}],
'id': 3}]
assert [figure_caption.to_json() for figure_caption in result['figure_captions']] == [
{'id': 0, 'metadata': {}, 'spans': [{'end': 2057, 'start': 2034}]},
{'id': 1, 'metadata': {}, 'spans': [{'end': 9679, 'start': 9175}]},
{'id': 2, 'metadata': {}, 'spans': [{'end': 13875, 'start': 13822}]},
{'id': 3, 'metadata': {}, 'spans': [{'end': 31364, 'start': 31224}]}]
assert [table.to_json() for table in result['tables']] == [{'boxes': [{'height': 0.2796805025351168,
'left': 0.16789371515411178,
'page': 4,
'top': 0.1370883614125878,
'width': 0.6443845462175756}]},
{'boxes': [{'height': 0.20913203075678666,
'left': 0.1747694701151131,
'page': 5,
'top': 0.13721680882001164,
'width': 0.622537251391442}],
'id': 1},
{'boxes': [{'height': 0.06003320096719145,
'left': 0.15402431114047183,
'page': 5,
'top': 0.5840287642045454,
'width': 0.2569979998021344}],
'id': 2},
{'boxes': [{'height': 0.23519277090978136,
'left': 0.5027104296715431,
'page': 6,
'top': 0.27805763784081045,
'width': 0.3950077131682751}],
'id': 3}]
assert [table_caption.to_json() for table_caption in result['table_captions']] == [
{'id': 0, 'metadata': {}, 'spans': [{'end': 18359, 'start': 18198}]},
{'id': 1, 'metadata': {}, 'spans': [{'end': 22214, 'start': 22042}]},
{'id': 2, 'metadata': {}, 'spans': [{'end': 23502, 'start': 23400}]},
{'id': 3, 'metadata': {}, 'spans': [{'end': 29584, 'start': 29369}]}]
def test_predict_2149e0c1106e6dfa36ea787167d6611cf88b69cb(self):
"""
Test that the function generates a map of layout to tokens using
for doc_fixture_2149e0c1106e6dfa36ea787167d6611cf88b69cb.json
"""
self.figure_table_predictor.doc = self.doc_2
result = self.figure_table_predictor.predict()
assert isinstance(result, dict)
assert list(result.keys()) == ['figures', 'figure_captions', 'figure_to_figure_captions', 'tables',
'table_captions',
'table_to_table_captions', ]
assert len(result['figures']) == 19
assert len(result['tables']) == 0
assert isinstance(result['figure_to_figure_captions'][0], Relation)
assert [figure.to_json() for figure in result['figures']] == self.figure_predictions
assert [figure_caption.to_json() for figure_caption in result['figure_captions']] == [
{'id': 0, 'metadata': {}, 'spans': [{'end': 5253, 'start': 5019}]},
{'id': 1, 'metadata': {}, 'spans': [{'end': 9230, 'start': 8976}]},
{'id': 2, 'metadata': {}, 'spans': [{'end': 13164, 'start': 12935}]},
{'id': 3, 'metadata': {}, 'spans': [{'end': 17600, 'start': 17373}]},
{'id': 4, 'metadata': {}, 'spans': [{'end': 23624, 'start': 23205}]},
{'id': 5, 'metadata': {}, 'spans': [{'end': 21009, 'start': 20070}]},
{'id': 6, 'metadata': {}, 'spans': [{'end': 28975, 'start': 28838}]},
{'id': 7, 'metadata': {}, 'spans': [{'end': 32839, 'start': 32681}]},
{'id': 8, 'metadata': {}, 'spans': [{'end': 37061, 'start': 36394}]},
{'id': 9, 'metadata': {}, 'spans': [{'end': 42245, 'start': 42063}]},
{'id': 10, 'metadata': {}, 'spans': [{'end': 43512, 'start': 43418}]},
{'id': 11, 'metadata': {}, 'spans': [{'end': 46726, 'start': 46542}]},
{'id': 12, 'metadata': {}, 'spans': [{'end': 50359, 'start': 50192}]},
{'id': 13, 'metadata': {}, 'spans': [{'end': 57779, 'start': 57323}]},
{'id': 14, 'metadata': {}, 'spans': [{'end': 60918, 'start': 60838}]},
{'id': 15, 'metadata': {}, 'spans': [{'end': 64943, 'start': 64238}]},
{'id': 16, 'metadata': {}, 'spans': [{'end': 69170, 'start': 68548}]},
{'id': 17, 'metadata': {}, 'spans': [{'end': 75951, 'start': 75767}]},
{'id': 18, 'metadata': {}, 'spans': [{'end': 80129, 'start': 79561}]}]
| 11,705 | 65.511364 | 113 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_section_header_predictor.py
|
"""
Tests for SectionHeaderPredictor
@rauthur
"""
import pathlib
import unittest
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.heuristic_predictors.section_header_predictor import (
SectionHeaderPredictor,
)
from mmda.utils.outline_metadata import PDFMinerOutlineExtractor
class TestSectionHeaderPredictor(unittest.TestCase):
def setUp(self) -> None:
self.fixture_path = pathlib.Path(__file__).parent.parent / "fixtures"
self.parser = PDFPlumberParser(extra_attrs=[])
self.extractor = PDFMinerOutlineExtractor()
self.predictor = SectionHeaderPredictor()
def test_finds_sections(self):
input_pdf_path = (
self.fixture_path / "4be952924cd565488b4a239dc6549095029ee578.pdf"
)
doc = self.parser.parse(input_pdf_path=input_pdf_path)
outline = self.extractor.extract(input_pdf_path=input_pdf_path, doc=doc)
doc.add_metadata(outline=outline.to_metadata_dict())
doc.annotate(sections=self.predictor.predict(document=doc))
self.assertEqual(18, len(doc.sections)) # pylint: disable=no-member
| 1,138 | 31.542857 | 80 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_section_nesting_predictor.py
|
"""
Tests for SectionNestingPredictor
@rauthur
"""
import pathlib
import unittest
from copy import deepcopy
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.hf_predictors.vila_predictor import IVILAPredictor
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.predictors.xgb_predictors.section_nesting_predictor import (
SectionNestingPredictor,
)
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.types.annotation import SpanGroup
class TestSectionNestingPredictor(unittest.TestCase):
def setUp(self) -> None:
self.fixture_path = pathlib.Path(__file__).parent.parent / "fixtures"
self.parser = PDFPlumberParser(extra_attrs=[])
self.rasterizer = PDF2ImageRasterizer()
self.layout_predictor = LayoutParserPredictor.from_pretrained(
"lp://efficientdet/PubLayNet"
)
self.vila = IVILAPredictor.from_pretrained(
"allenai/ivila-row-layoutlm-finetuned-s2vl-v2",
agg_level="row",
added_special_sepration_token="[BLK]",
)
self.predictor = SectionNestingPredictor(self.fixture_path / "nesting.bin")
def test_finds_sections(self):
input_pdf_path = (
self.fixture_path / "4be952924cd565488b4a239dc6549095029ee578.pdf"
)
doc = self.parser.parse(input_pdf_path)
images = self.rasterizer.rasterize(input_pdf_path, dpi=72)
doc.annotate_images(images)
blocks = self.layout_predictor.predict(doc)
doc.annotate(blocks=blocks)
results = self.vila.predict(doc)
doc.annotate(results=results)
# Extract sections from VILA predictions and re-add boxes
vila_sections = []
for i, span_group in enumerate(doc.results):
if span_group.type != 4:
continue
# Boxes are not returned from VILA so reach into tokens
token_spans = [deepcopy(t.spans) for t in span_group.tokens]
token_spans = [span for l in token_spans for span in l] # Flatten list
# Maintain the text from VILA for each span group
metadata = deepcopy(span_group.metadata)
metadata.text = span_group.text
vila_sections.append(
SpanGroup(
spans=token_spans,
box_group=deepcopy(span_group.box_group),
id=i, # Ensure some ID is created
doc=None, # Allows calling doc.annotate(...)
metadata=metadata,
)
)
doc.annotate(sections=vila_sections)
nestings = self.predictor.predict(doc)
self.assertEqual(18, len(nestings))
for nesting in nestings:
self.assertIsNotNone(nesting.metadata.parent_id)
| 2,846 | 32.892857 | 83 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_dictionary_word_predictor.py
|
"""
Tests for DictionaryWordPredictor
@rauthur, @kylel
"""
import tempfile
import unittest
from typing import List, Optional, Set
from mmda.predictors.heuristic_predictors.dictionary_word_predictor import Dictionary
from mmda.predictors import DictionaryWordPredictor
from mmda.types import Document, SpanGroup, Span
def mock_document(symbols: str, spans: List[Span], rows: List[SpanGroup]) -> Document:
doc = Document(symbols=symbols)
doc.annotate(rows=rows)
doc.annotate(
tokens=[SpanGroup(id=i, spans=[span]) for i, span in enumerate(spans)]
)
return doc
# 'fine-tuning', 'sentence', 'word'
class TestDictionary(unittest.TestCase):
def setUp(self):
self.dict = Dictionary(words=[], punct='-!%')
def test_add_and_is_in(self):
self.dict.add('Fine-TuninG')
self.dict.add('--fine-tuning--')
self.assertTrue(self.dict.is_in('Fine-TuninG'))
self.assertTrue(self.dict.is_in('--fine-tuning--'))
self.assertTrue(self.dict.is_in('---FINE-TUNING----'))
self.assertTrue(self.dict.is_in('fine-tuning'))
self.assertFalse(self.dict.is_in('fine'))
self.assertFalse(self.dict.is_in('tuning'))
self.assertFalse(self.dict.is_in('finetuning'))
def test_strip_punct(self):
self.assertEqual(self.dict.strip_punct(text='fine-tuning'), 'fine-tuning')
self.assertEqual(self.dict.strip_punct(text='123fine-tuning123'), '123fine-tuning123')
self.assertEqual(self.dict.strip_punct(text='--fine-tuning--'), 'fine-tuning')
self.assertEqual(self.dict.strip_punct(text='!!--fine-tuning--!!'), 'fine-tuning')
self.assertEqual(self.dict.strip_punct(text='%!!--fine-tuning--!!%'), 'fine-tuning')
# because # is not part of the dictionary, stops stripping
self.assertEqual(self.dict.strip_punct(text='#--fine-tuning--#'), '#--fine-tuning--#')
self.assertEqual(self.dict.strip_punct(text='--#--fine-tuning--#--'), '#--fine-tuning--#')
# shouldnt break with a single punctuation character
self.assertEqual(self.dict.strip_punct(text='%'), '')
class TestDictionaryWordPredictor(unittest.TestCase):
def test_hyphenated_word_combines(self):
# fmt:off
# 0 10 20 30 40 50 60 70
# 01234567890123456789012345678901234567890123456789012345678901234567890123456789
text = "The goal of meta-learning is to train a model on a vari-\nety! of learning tasks."
# fmt:on
spans = [
Span(start=0, end=3), # The
Span(start=4, end=8), # goal
Span(start=9, end=11), # of
Span(start=12, end=16), # meta
Span(start=16, end=17), # -
Span(start=17, end=25), # learning
Span(start=26, end=28), # is
Span(start=29, end=31), # to
Span(start=32, end=37), # train
Span(start=38, end=39), # a
Span(start=40, end=45), # model
Span(start=46, end=48), # on
Span(start=49, end=50), # a
Span(start=51, end=55), # vari
Span(start=55, end=56), # -
Span(start=57, end=60), # ety
Span(start=60, end=61), # !
Span(start=62, end=64), # of
Span(start=65, end=73), # learning
Span(start=74, end=79), # tasks
Span(start=79, end=80), # .
]
rows = [SpanGroup(id=0, spans=spans[0:15]), SpanGroup(id=1, spans=spans[15:])]
document = mock_document(symbols=text, spans=spans, rows=rows)
with tempfile.NamedTemporaryFile() as f:
f.write("variety\n".encode("utf-8"))
f.flush()
predictor = DictionaryWordPredictor()
words = predictor.predict(document)
document.annotate(words=words)
self.assertEqual(
[w.text for w in words],
['The', 'goal', 'of', 'meta-learning', 'is', 'to', 'train', 'a', 'model',
'on', 'a', 'vari-ety', '!', 'of', 'learning', 'tasks', '.'])
def test_next_row_single_token(self):
# fmt:off
# 0 10
# 012345678901
text = "Many lin-es"
# fmt:on
spans = [
Span(start=0, end=4), # Many
Span(start=5, end=9), # lin-
Span(start=9, end=11), # es
]
rows = [
SpanGroup(id=1, spans=spans[0:2]),
SpanGroup(id=2, spans=spans[2:3]),
]
document = mock_document(symbols=text, spans=spans, rows=rows)
with tempfile.NamedTemporaryFile() as f:
f.write("".encode("utf-8"))
f.flush()
predictor = DictionaryWordPredictor(dictionary_file_path=f.name)
words = predictor.predict(document)
self.assertEqual([w.text for w in words], ['Many', 'lin-es'])
def test_single_token_rows(self):
predictor = DictionaryWordPredictor()
# simple case without punctuation
text = 'a b cdefg'
spans = [
Span(start=0, end=1),
Span(start=2, end=3),
Span(start=4, end=9)
]
rows = [
SpanGroup(id=1, spans=[spans[0]]),
SpanGroup(id=2, spans=[spans[1]]),
SpanGroup(id=3, spans=[spans[2]]),
]
document = mock_document(symbols=text, spans=spans, rows=rows)
words = predictor.predict(document)
self.assertEqual([w.text for w in words], ['a', 'b', 'cdefg'])
# now with punctuation
text = '- - cdefg'
spans = [
Span(start=0, end=1),
Span(start=2, end=3),
Span(start=4, end=9)
]
rows = [
SpanGroup(id=1, spans=[spans[0]]),
SpanGroup(id=2, spans=[spans[1]]),
SpanGroup(id=3, spans=[spans[2]]),
]
document = mock_document(symbols=text, spans=spans, rows=rows)
words = predictor.predict(document)
self.assertEqual([w.text for w in words], ['-', '-', 'cdefg'])
def test_words_with_surrounding_punct(self):
predictor = DictionaryWordPredictor()
# simple case without punctuation
text = '(abc)'
spans = [
Span(start=0, end=1),
Span(start=1, end=4),
Span(start=4, end=5)
]
rows = [
SpanGroup(id=1, spans=[spans[0]]),
SpanGroup(id=2, spans=[spans[1]]),
SpanGroup(id=3, spans=[spans[2]]),
]
document = mock_document(symbols=text, spans=spans, rows=rows)
words = predictor.predict(document)
self.assertEqual([w.text for w in words], ['(', 'abc', ')'])
def test_words_with_multiple_preceding_punct(self):
predictor = DictionaryWordPredictor()
text = ')/2'
spans = [
Span(start=0, end=1),
Span(start=1, end=2),
Span(start=2, end=3)
]
rows = [
SpanGroup(id=1, spans=[spans[0]]),
SpanGroup(id=2, spans=[spans[1]]),
SpanGroup(id=3, spans=[spans[2]]),
]
document = mock_document(symbols=text, spans=spans, rows=rows)
words = predictor.predict(document)
self.assertEqual([w.text for w in words], [')', '/', '2'])
| 7,345 | 34.148325 | 98 |
py
|
mmda
|
mmda-main/tests/test_predictors/test.json.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/tests/test_predictors/test_span_group_classification_predictor.py
|
"""
@kylel
"""
import unittest
import json
from mmda.types.annotation import Span, SpanGroup
from mmda.types.document import Document
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.hf_predictors.span_group_classification_predictor import (
SpanGroupClassificationPredictor
)
TEST_SCIBERT_WEIGHTS = 'allenai/scibert_scivocab_uncased'
# TEST_BIB_PARSER_WEIGHTS = '/Users/kylel/ai2/mmda/stefans/'
TEST_DOC_JSON = {"symbols": "modelling reward . In International Conference on\nLearning Representations ( ICLR ) .\nMarco Baroni ,\nGeorgiana Dinu ,\nand Germ\u00b4an\nKruszewski . 2014 .\nDon\u2019t count , predict !\nA\nsystematic comparison of context - counting vs .\ncontext - predicting semantic vectors . In Proceedings\nof the 52nd Annual Meeting of the Association for\nComputational Linguistics , ACL 2014 , June 22 - 27 ,\n2014 , Baltimore , MD , USA , Volume 1 : Long Papers ,\npages 238 \u2013 247 .\nYoshua Bengio , R\u00b4ejean Ducharme , Pascal Vincent , and\nChristian Janvin . 2003 . A neural probabilistic lan -\nguage model .\nJournal of Machine Learning Re -\nsearch , 3 : 1137 \u2013 1155 .\nAntoine Bordes , Nicolas Usunier , Alberto Garc\u00b4\u0131a -\nDur\u00b4an , Jason Weston , and Oksana Yakhnenko .\n2013 . Translating embeddings for modeling multi -\nrelational data . In Advances in Neural Information\nProcessing Systems 26 : 27th Annual Conference on\nNeural Information Processing Systems 2013 . Pro -\nceedings of a meeting held December 5 - 8 , 2013 ,\nLake Tahoe , Nevada , United States . , pages 2787 \u2013\n2795 .\nS . R . K . Branavan , David Silver , and Regina Barzi -\nlay . 2011 . Learning to win by reading manuals in a\nmonte - carlo framework . In The 49th Annual Meet -\ning of the Association for Computational Linguis -\ntics : Human Language Technologies , Proceedings\nof the Conference , 19 - 24 June , 2011 , Portland , Ore -\ngon , USA , pages 268 \u2013 277 .\nDanqi Chen , Adam Fisch , Jason Weston , and Antoine\nBordes . 2017 . Reading wikipedia to answer open -\ndomain questions . CoRR , abs / 1704 . 00051 .\nMaxime Chevalier - Boisvert ,\nDzmitry\nBahdanau ,\nSalem Lahlou , Lucas Willems , Chitwan Saharia ,\nThien Huu Nguyen , and Yoshua Bengio . 2018 .\nBabyai : First steps towards grounded language\nlearning with a human in the loop .\nCoRR ,\nabs / 1810 . 08272 .\nZihang Dai , Zhilin Yang , Yiming Yang , Jaime G .\nCarbonell , Quoc V . Le , and Ruslan Salakhutdi -\nnov . 2019 .\nTransformer - xl : Attentive language\nmodels beyond a \ufb01xed - length context .\nCoRR ,\nabs / 1901 . 02860 .\nYann N . Dauphin , Angela Fan , Michael Auli , and\nDavid Grangier . 2017 .\nLanguage modeling with\ngated convolutional networks . In Proceedings of the\n34th International Conference on Machine Learn -\ning , ICML 2017 , Sydney , NSW , Australia , 6 - 11 Au -\ngust 2017 , pages 933 \u2013 941 .\nJacob Devlin , Ming - Wei Chang , Kenton Lee , and\nKristina Toutanova . 2018a . BERT : pre - training of\ndeep bidirectional transformers for language under -\nstanding . CoRR , abs / 1810 . 04805 .\nJacob Devlin , Ming - Wei Chang , Kenton Lee , and\nKristina Toutanova . 2018b .\nBERT : Pre - training\nof Deep Bidirectional Transformers for Language\nUnderstanding .\narXiv : 1810 . 04805 [ cs ] .\nArXiv :\n1810 . 04805 .\nHady Elsahar , Pavlos Vougiouklis , Arslen Remaci ,\nChristophe Gravier , Jonathon Hare , Frederique\nLaforest , and Elena Simperl . 2018 . T - rex : A large\nscale alignment of natural language with knowledge\nbase triples . In Proceedings of the Eleventh Interna -\ntional Conference on Language Resources and Eval -\nuation ( LREC - 2018 ) .\nYoav Goldberg . 2019 . Assessing bert\u2019s syntactic abili -\nties . CoRR , abs / 1901 . 05287 .\nFelix Hill , Roi Reichart , and Anna Korhonen . 2015 .\nSimlex - 999 : Evaluating semantic models with ( gen -\nuine ) similarity estimation . Computational Linguis -\ntics , 41 ( 4 ) : 665 \u2013 695 .\nSepp Hochreiter and J\u00a8urgen Schmidhuber . 1997 .\nLong short - term memory .\nNeural Computation ,\n9 ( 8 ) : 1735 \u2013 1780 .\nTom Kwiatkowski , Jennimaria Palomaki , Olivia\nRhinehart , Michael Collins , Ankur Parikh , Chris Al -\nberti , Danielle Epstein , Illia Polosukhin , Matthew\nKelcey , Jacob Devlin , et al . 2019 . Natural questions :\na benchmark for question answering research .\nJelena Luketina , Nantas Nardelli , Gregory Farquhar ,\nJakob Foerster , Jacob Andreas , Edward Grefen -\nstette , Shimon Whiteson , and Tim Rockt\u00a8aschel .\n2019 .\nA Survey of Reinforcement Learning In -\nformed by Natural Language . In Proceedings of\nthe Twenty - Eighth International Joint Conference\non Arti\ufb01cial Intelligence , IJCAI 2019 , August 10 - 16\n2019 , Macao , China .\nRebecca Marvin and Tal Linzen . 2018 . Targeted syn -\ntactic evaluation of language models . In Proceed -\nings of the 2018 Conference on Empirical Methods\nin Natural Language Processing , Brussels , Belgium ,\nOctober 31 - November 4 , 2018 , pages 1192 \u2013 1202 .\nR . Thomas McCoy , Ellie Pavlick , and Tal Linzen .\n2019 . Right for the wrong reasons : Diagnosing syn -\ntactic heuristics in natural language inference .\nG\u00b4abor Melis , Chris Dyer , and Phil Blunsom . 2017 . On\nthe state of the art of evaluation in neural language\nmodels . CoRR , abs / 1707 . 05589 .\nStephen Merity , Caiming Xiong , James Bradbury , and\nRichard Socher . 2016 .\nPointer sentinel mixture\nmodels . CoRR , abs / 1609 . 07843 .\nTomas Mikolov and Geo \ufb00 rey Zweig . 2012 . Context\ndependent recurrent neural network language model .\nIn 2012 IEEE Spoken Language Technology Work -\nshop ( SLT ) , Miami , FL , USA , December 2 - 5 , 2012 ,\npages 234 \u2013 239 .\n", "pages": [{"spans": [{"start": 0, "end": 5056}]}], "tokens": [{"spans": [{"start": 0, "end": 9}]}, {"spans": [{"start": 10, "end": 16}]}, {"spans": [{"start": 17, "end": 18}]}, {"spans": [{"start": 19, "end": 21}]}, {"spans": [{"start": 22, "end": 35}]}, {"spans": [{"start": 36, "end": 46}]}, {"spans": [{"start": 47, "end": 49}]}, {"spans": [{"start": 50, "end": 58}]}, {"spans": [{"start": 59, "end": 74}]}, {"spans": [{"start": 75, "end": 76}]}, {"spans": [{"start": 77, "end": 81}]}, {"spans": [{"start": 82, "end": 83}]}, {"spans": [{"start": 84, "end": 85}]}, {"spans": [{"start": 86, "end": 91}]}, {"spans": [{"start": 92, "end": 98}]}, {"spans": [{"start": 99, "end": 100}]}, {"spans": [{"start": 101, "end": 110}]}, {"spans": [{"start": 111, "end": 115}]}, {"spans": [{"start": 116, "end": 117}]}, {"spans": [{"start": 118, "end": 121}]}, {"spans": [{"start": 122, "end": 129}]}, {"spans": [{"start": 130, "end": 140}]}, {"spans": [{"start": 141, "end": 142}]}, {"spans": [{"start": 143, "end": 147}]}, {"spans": [{"start": 148, "end": 149}]}, {"spans": [{"start": 150, "end": 155}]}, {"spans": [{"start": 156, "end": 161}]}, {"spans": [{"start": 162, "end": 163}]}, {"spans": [{"start": 164, "end": 171}]}, {"spans": [{"start": 172, "end": 173}]}, {"spans": [{"start": 174, "end": 175}]}, {"spans": [{"start": 176, "end": 186}]}, {"spans": [{"start": 187, "end": 197}]}, {"spans": [{"start": 198, "end": 200}]}, {"spans": [{"start": 201, "end": 208}]}, {"spans": [{"start": 209, "end": 210}]}, {"spans": [{"start": 211, "end": 219}]}, {"spans": [{"start": 220, "end": 222}]}, {"spans": [{"start": 223, "end": 224}]}, {"spans": [{"start": 225, "end": 232}]}, {"spans": [{"start": 233, "end": 234}]}, {"spans": [{"start": 235, "end": 245}]}, {"spans": [{"start": 246, "end": 254}]}, {"spans": [{"start": 255, "end": 262}]}, {"spans": [{"start": 263, "end": 264}]}, {"spans": [{"start": 265, "end": 267}]}, {"spans": [{"start": 268, "end": 279}]}, {"spans": [{"start": 280, "end": 282}]}, {"spans": [{"start": 283, "end": 286}]}, {"spans": [{"start": 287, "end": 291}]}, {"spans": [{"start": 292, "end": 298}]}, {"spans": [{"start": 299, "end": 306}]}, {"spans": [{"start": 307, "end": 309}]}, {"spans": [{"start": 310, "end": 313}]}, {"spans": [{"start": 314, "end": 325}]}, {"spans": [{"start": 326, "end": 329}]}, {"spans": [{"start": 330, "end": 343}]}, {"spans": [{"start": 344, "end": 355}]}, {"spans": [{"start": 356, "end": 357}]}, {"spans": [{"start": 358, "end": 361}]}, {"spans": [{"start": 362, "end": 366}]}, {"spans": [{"start": 367, "end": 368}]}, {"spans": [{"start": 369, "end": 373}]}, {"spans": [{"start": 374, "end": 376}]}, {"spans": [{"start": 377, "end": 378}]}, {"spans": [{"start": 379, "end": 381}]}, {"spans": [{"start": 382, "end": 383}]}, {"spans": [{"start": 384, "end": 388}]}, {"spans": [{"start": 389, "end": 390}]}, {"spans": [{"start": 391, "end": 400}]}, {"spans": [{"start": 401, "end": 402}]}, {"spans": [{"start": 403, "end": 405}]}, {"spans": [{"start": 406, "end": 407}]}, {"spans": [{"start": 408, "end": 411}]}, {"spans": [{"start": 412, "end": 413}]}, {"spans": [{"start": 414, "end": 420}]}, {"spans": [{"start": 421, "end": 422}]}, {"spans": [{"start": 423, "end": 424}]}, {"spans": [{"start": 425, "end": 429}]}, {"spans": [{"start": 430, "end": 436}]}, {"spans": [{"start": 437, "end": 438}]}, {"spans": [{"start": 439, "end": 444}]}, {"spans": [{"start": 445, "end": 448}]}, {"spans": [{"start": 449, "end": 450}]}, {"spans": [{"start": 451, "end": 454}]}, {"spans": [{"start": 455, "end": 456}]}, {"spans": [{"start": 457, "end": 463}]}, {"spans": [{"start": 464, "end": 470}]}, {"spans": [{"start": 471, "end": 472}]}, {"spans": [{"start": 473, "end": 480}]}, {"spans": [{"start": 481, "end": 489}]}, {"spans": [{"start": 490, "end": 491}]}, {"spans": [{"start": 492, "end": 498}]}, {"spans": [{"start": 499, "end": 506}]}, {"spans": [{"start": 507, "end": 508}]}, {"spans": [{"start": 509, "end": 512}]}, {"spans": [{"start": 513, "end": 522}]}, {"spans": [{"start": 523, "end": 529}]}, {"spans": [{"start": 530, "end": 531}]}, {"spans": [{"start": 532, "end": 536}]}, {"spans": [{"start": 537, "end": 538}]}, {"spans": [{"start": 539, "end": 540}]}, {"spans": [{"start": 541, "end": 547}]}, {"spans": [{"start": 548, "end": 561}]}, {"spans": [{"start": 562, "end": 565}]}, {"spans": [{"start": 566, "end": 567}]}, {"spans": [{"start": 568, "end": 573}]}, {"spans": [{"start": 574, "end": 579}]}, {"spans": [{"start": 580, "end": 581}]}, {"spans": [{"start": 582, "end": 589}]}, {"spans": [{"start": 590, "end": 592}]}, {"spans": [{"start": 593, "end": 600}]}, {"spans": [{"start": 601, "end": 609}]}, {"spans": [{"start": 610, "end": 612}]}, {"spans": [{"start": 613, "end": 614}]}, {"spans": [{"start": 615, "end": 621}]}, {"spans": [{"start": 622, "end": 623}]}, {"spans": [{"start": 624, "end": 625}]}, {"spans": [{"start": 626, "end": 627}]}, {"spans": [{"start": 628, "end": 632}]}, {"spans": [{"start": 633, "end": 634}]}, {"spans": [{"start": 635, "end": 639}]}, {"spans": [{"start": 640, "end": 641}]}, {"spans": [{"start": 642, "end": 649}]}, {"spans": [{"start": 650, "end": 656}]}, {"spans": [{"start": 657, "end": 658}]}, {"spans": [{"start": 659, "end": 666}]}, {"spans": [{"start": 667, "end": 674}]}, {"spans": [{"start": 675, "end": 676}]}, {"spans": [{"start": 677, "end": 684}]}, {"spans": [{"start": 685, "end": 692}]}, {"spans": [{"start": 693, "end": 694}]}, {"spans": [{"start": 695, "end": 701}]}, {"spans": [{"start": 702, "end": 703}]}, {"spans": [{"start": 704, "end": 709}]}, {"spans": [{"start": 710, "end": 716}]}, {"spans": [{"start": 717, "end": 718}]}, {"spans": [{"start": 719, "end": 722}]}, {"spans": [{"start": 723, "end": 729}]}, {"spans": [{"start": 730, "end": 739}]}, {"spans": [{"start": 740, "end": 741}]}, {"spans": [{"start": 742, "end": 746}]}, {"spans": [{"start": 747, "end": 748}]}, {"spans": [{"start": 749, "end": 760}]}, {"spans": [{"start": 761, "end": 771}]}, {"spans": [{"start": 772, "end": 775}]}, {"spans": [{"start": 776, "end": 784}]}, {"spans": [{"start": 785, "end": 790}]}, {"spans": [{"start": 791, "end": 792}]}, {"spans": [{"start": 793, "end": 803}]}, {"spans": [{"start": 804, "end": 808}]}, {"spans": [{"start": 809, "end": 810}]}, {"spans": [{"start": 811, "end": 813}]}, {"spans": [{"start": 814, "end": 822}]}, {"spans": [{"start": 823, "end": 825}]}, {"spans": [{"start": 826, "end": 832}]}, {"spans": [{"start": 833, "end": 844}]}, {"spans": [{"start": 845, "end": 855}]}, {"spans": [{"start": 856, "end": 863}]}, {"spans": [{"start": 864, "end": 866}]}, {"spans": [{"start": 867, "end": 868}]}, {"spans": [{"start": 869, "end": 873}]}, {"spans": [{"start": 874, "end": 880}]}, {"spans": [{"start": 881, "end": 891}]}, {"spans": [{"start": 892, "end": 894}]}, {"spans": [{"start": 895, "end": 901}]}, {"spans": [{"start": 902, "end": 913}]}, {"spans": [{"start": 914, "end": 924}]}, {"spans": [{"start": 925, "end": 932}]}, {"spans": [{"start": 933, "end": 937}]}, {"spans": [{"start": 938, "end": 939}]}, {"spans": [{"start": 940, "end": 943}]}, {"spans": [{"start": 944, "end": 945}]}, {"spans": [{"start": 946, "end": 954}]}, {"spans": [{"start": 955, "end": 957}]}, {"spans": [{"start": 958, "end": 959}]}, {"spans": [{"start": 960, "end": 967}]}, {"spans": [{"start": 968, "end": 972}]}, {"spans": [{"start": 973, "end": 981}]}, {"spans": [{"start": 982, "end": 983}]}, {"spans": [{"start": 984, "end": 985}]}, {"spans": [{"start": 986, "end": 987}]}, {"spans": [{"start": 988, "end": 989}]}, {"spans": [{"start": 990, "end": 994}]}, {"spans": [{"start": 995, "end": 996}]}, {"spans": [{"start": 997, "end": 1001}]}, {"spans": [{"start": 1002, "end": 1007}]}, {"spans": [{"start": 1008, "end": 1009}]}, {"spans": [{"start": 1010, "end": 1016}]}, {"spans": [{"start": 1017, "end": 1018}]}, {"spans": [{"start": 1019, "end": 1025}]}, {"spans": [{"start": 1026, "end": 1032}]}, {"spans": [{"start": 1033, "end": 1034}]}, {"spans": [{"start": 1035, "end": 1036}]}, {"spans": [{"start": 1037, "end": 1042}]}, {"spans": [{"start": 1043, "end": 1047}]}, {"spans": [{"start": 1048, "end": 1049}]}, {"spans": [{"start": 1050, "end": 1054}]}, {"spans": [{"start": 1055, "end": 1056}]}, {"spans": [{"start": 1057, "end": 1058}]}, {"spans": [{"start": 1059, "end": 1060}]}, {"spans": [{"start": 1061, "end": 1062}]}, {"spans": [{"start": 1063, "end": 1064}]}, {"spans": [{"start": 1065, "end": 1066}]}, {"spans": [{"start": 1067, "end": 1068}]}, {"spans": [{"start": 1069, "end": 1077}]}, {"spans": [{"start": 1078, "end": 1079}]}, {"spans": [{"start": 1080, "end": 1085}]}, {"spans": [{"start": 1086, "end": 1092}]}, {"spans": [{"start": 1093, "end": 1094}]}, {"spans": [{"start": 1095, "end": 1098}]}, {"spans": [{"start": 1099, "end": 1105}]}, {"spans": [{"start": 1106, "end": 1111}]}, {"spans": [{"start": 1112, "end": 1113}]}, {"spans": [{"start": 1114, "end": 1117}]}, {"spans": [{"start": 1118, "end": 1119}]}, {"spans": [{"start": 1120, "end": 1124}]}, {"spans": [{"start": 1125, "end": 1126}]}, {"spans": [{"start": 1127, "end": 1135}]}, {"spans": [{"start": 1136, "end": 1138}]}, {"spans": [{"start": 1139, "end": 1142}]}, {"spans": [{"start": 1143, "end": 1145}]}, {"spans": [{"start": 1146, "end": 1153}]}, {"spans": [{"start": 1154, "end": 1161}]}, {"spans": [{"start": 1162, "end": 1164}]}, {"spans": [{"start": 1165, "end": 1166}]}, {"spans": [{"start": 1167, "end": 1172}]}, {"spans": [{"start": 1173, "end": 1174}]}, {"spans": [{"start": 1175, "end": 1180}]}, {"spans": [{"start": 1181, "end": 1190}]}, {"spans": [{"start": 1191, "end": 1192}]}, {"spans": [{"start": 1193, "end": 1195}]}, {"spans": [{"start": 1196, "end": 1199}]}, {"spans": [{"start": 1200, "end": 1204}]}, {"spans": [{"start": 1205, "end": 1211}]}, {"spans": [{"start": 1212, "end": 1216}]}, {"spans": [{"start": 1217, "end": 1218}]}, {"spans": [{"start": 1219, "end": 1222}]}, {"spans": [{"start": 1223, "end": 1225}]}, {"spans": [{"start": 1226, "end": 1229}]}, {"spans": [{"start": 1230, "end": 1241}]}, {"spans": [{"start": 1242, "end": 1245}]}, {"spans": [{"start": 1246, "end": 1259}]}, {"spans": [{"start": 1260, "end": 1267}]}, {"spans": [{"start": 1268, "end": 1269}]}, {"spans": [{"start": 1270, "end": 1274}]}, {"spans": [{"start": 1275, "end": 1276}]}, {"spans": [{"start": 1277, "end": 1282}]}, {"spans": [{"start": 1283, "end": 1291}]}, {"spans": [{"start": 1292, "end": 1304}]}, {"spans": [{"start": 1305, "end": 1306}]}, {"spans": [{"start": 1307, "end": 1318}]}, {"spans": [{"start": 1319, "end": 1321}]}, {"spans": [{"start": 1322, "end": 1325}]}, {"spans": [{"start": 1326, "end": 1336}]}, {"spans": [{"start": 1337, "end": 1338}]}, {"spans": [{"start": 1339, "end": 1341}]}, {"spans": [{"start": 1342, "end": 1343}]}, {"spans": [{"start": 1344, "end": 1346}]}, {"spans": [{"start": 1347, "end": 1351}]}, {"spans": [{"start": 1352, "end": 1353}]}, {"spans": [{"start": 1354, "end": 1358}]}, {"spans": [{"start": 1359, "end": 1360}]}, {"spans": [{"start": 1361, "end": 1369}]}, {"spans": [{"start": 1370, "end": 1371}]}, {"spans": [{"start": 1372, "end": 1375}]}, {"spans": [{"start": 1376, "end": 1377}]}, {"spans": [{"start": 1378, "end": 1381}]}, {"spans": [{"start": 1382, "end": 1383}]}, {"spans": [{"start": 1384, "end": 1387}]}, {"spans": [{"start": 1388, "end": 1389}]}, {"spans": [{"start": 1390, "end": 1395}]}, {"spans": [{"start": 1396, "end": 1399}]}, {"spans": [{"start": 1400, "end": 1401}]}, {"spans": [{"start": 1402, "end": 1405}]}, {"spans": [{"start": 1406, "end": 1407}]}, {"spans": [{"start": 1408, "end": 1413}]}, {"spans": [{"start": 1414, "end": 1418}]}, {"spans": [{"start": 1419, "end": 1420}]}, {"spans": [{"start": 1421, "end": 1425}]}, {"spans": [{"start": 1426, "end": 1431}]}, {"spans": [{"start": 1432, "end": 1433}]}, {"spans": [{"start": 1434, "end": 1439}]}, {"spans": [{"start": 1440, "end": 1446}]}, {"spans": [{"start": 1447, "end": 1448}]}, {"spans": [{"start": 1449, "end": 1452}]}, {"spans": [{"start": 1453, "end": 1460}]}, {"spans": [{"start": 1461, "end": 1467}]}, {"spans": [{"start": 1468, "end": 1469}]}, {"spans": [{"start": 1470, "end": 1474}]}, {"spans": [{"start": 1475, "end": 1476}]}, {"spans": [{"start": 1477, "end": 1484}]}, {"spans": [{"start": 1485, "end": 1494}]}, {"spans": [{"start": 1495, "end": 1497}]}, {"spans": [{"start": 1498, "end": 1504}]}, {"spans": [{"start": 1505, "end": 1509}]}, {"spans": [{"start": 1510, "end": 1511}]}, {"spans": [{"start": 1512, "end": 1518}]}, {"spans": [{"start": 1519, "end": 1528}]}, {"spans": [{"start": 1529, "end": 1530}]}, {"spans": [{"start": 1531, "end": 1535}]}, {"spans": [{"start": 1536, "end": 1537}]}, {"spans": [{"start": 1538, "end": 1541}]}, {"spans": [{"start": 1542, "end": 1543}]}, {"spans": [{"start": 1544, "end": 1548}]}, {"spans": [{"start": 1549, "end": 1550}]}, {"spans": [{"start": 1551, "end": 1556}]}, {"spans": [{"start": 1557, "end": 1558}]}, {"spans": [{"start": 1559, "end": 1565}]}, {"spans": [{"start": 1566, "end": 1575}]}, {"spans": [{"start": 1576, "end": 1577}]}, {"spans": [{"start": 1578, "end": 1586}]}, {"spans": [{"start": 1587, "end": 1588}]}, {"spans": [{"start": 1589, "end": 1596}]}, {"spans": [{"start": 1597, "end": 1605}]}, {"spans": [{"start": 1606, "end": 1607}]}, {"spans": [{"start": 1608, "end": 1613}]}, {"spans": [{"start": 1614, "end": 1620}]}, {"spans": [{"start": 1621, "end": 1622}]}, {"spans": [{"start": 1623, "end": 1628}]}, {"spans": [{"start": 1629, "end": 1636}]}, {"spans": [{"start": 1637, "end": 1638}]}, {"spans": [{"start": 1639, "end": 1646}]}, {"spans": [{"start": 1647, "end": 1654}]}, {"spans": [{"start": 1655, "end": 1656}]}, {"spans": [{"start": 1657, "end": 1662}]}, {"spans": [{"start": 1663, "end": 1666}]}, {"spans": [{"start": 1667, "end": 1673}]}, {"spans": [{"start": 1674, "end": 1675}]}, {"spans": [{"start": 1676, "end": 1679}]}, {"spans": [{"start": 1680, "end": 1686}]}, {"spans": [{"start": 1687, "end": 1693}]}, {"spans": [{"start": 1694, "end": 1695}]}, {"spans": [{"start": 1696, "end": 1700}]}, {"spans": [{"start": 1701, "end": 1702}]}, {"spans": [{"start": 1703, "end": 1709}]}, {"spans": [{"start": 1710, "end": 1711}]}, {"spans": [{"start": 1712, "end": 1717}]}, {"spans": [{"start": 1718, "end": 1723}]}, {"spans": [{"start": 1724, "end": 1731}]}, {"spans": [{"start": 1732, "end": 1740}]}, {"spans": [{"start": 1741, "end": 1749}]}, {"spans": [{"start": 1750, "end": 1758}]}, {"spans": [{"start": 1759, "end": 1763}]}, {"spans": [{"start": 1764, "end": 1765}]}, {"spans": [{"start": 1766, "end": 1771}]}, {"spans": [{"start": 1772, "end": 1774}]}, {"spans": [{"start": 1775, "end": 1778}]}, {"spans": [{"start": 1779, "end": 1783}]}, {"spans": [{"start": 1784, "end": 1785}]}, {"spans": [{"start": 1786, "end": 1790}]}, {"spans": [{"start": 1791, "end": 1792}]}, {"spans": [{"start": 1793, "end": 1796}]}, {"spans": [{"start": 1797, "end": 1798}]}, {"spans": [{"start": 1799, "end": 1803}]}, {"spans": [{"start": 1804, "end": 1805}]}, {"spans": [{"start": 1806, "end": 1811}]}, {"spans": [{"start": 1812, "end": 1813}]}, {"spans": [{"start": 1814, "end": 1820}]}, {"spans": [{"start": 1821, "end": 1824}]}, {"spans": [{"start": 1825, "end": 1826}]}, {"spans": [{"start": 1827, "end": 1833}]}, {"spans": [{"start": 1834, "end": 1838}]}, {"spans": [{"start": 1839, "end": 1840}]}, {"spans": [{"start": 1841, "end": 1847}]}, {"spans": [{"start": 1848, "end": 1852}]}, {"spans": [{"start": 1853, "end": 1854}]}, {"spans": [{"start": 1855, "end": 1860}]}, {"spans": [{"start": 1861, "end": 1862}]}, {"spans": [{"start": 1863, "end": 1864}]}, {"spans": [{"start": 1865, "end": 1874}]}, {"spans": [{"start": 1875, "end": 1876}]}, {"spans": [{"start": 1877, "end": 1881}]}, {"spans": [{"start": 1882, "end": 1883}]}, {"spans": [{"start": 1884, "end": 1885}]}, {"spans": [{"start": 1886, "end": 1888}]}, {"spans": [{"start": 1889, "end": 1890}]}, {"spans": [{"start": 1891, "end": 1894}]}, {"spans": [{"start": 1895, "end": 1901}]}, {"spans": [{"start": 1902, "end": 1912}]}, {"spans": [{"start": 1913, "end": 1914}]}, {"spans": [{"start": 1915, "end": 1918}]}, {"spans": [{"start": 1919, "end": 1920}]}, {"spans": [{"start": 1921, "end": 1925}]}, {"spans": [{"start": 1926, "end": 1927}]}, {"spans": [{"start": 1928, "end": 1939}]}, {"spans": [{"start": 1940, "end": 1941}]}, {"spans": [{"start": 1942, "end": 1944}]}, {"spans": [{"start": 1945, "end": 1946}]}, {"spans": [{"start": 1947, "end": 1956}]}, {"spans": [{"start": 1957, "end": 1965}]}, {"spans": [{"start": 1966, "end": 1972}]}, {"spans": [{"start": 1973, "end": 1979}]}, {"spans": [{"start": 1980, "end": 1981}]}, {"spans": [{"start": 1982, "end": 1986}]}, {"spans": [{"start": 1987, "end": 1988}]}, {"spans": [{"start": 1989, "end": 1995}]}, {"spans": [{"start": 1996, "end": 2003}]}, {"spans": [{"start": 2004, "end": 2005}]}, {"spans": [{"start": 2006, "end": 2010}]}, {"spans": [{"start": 2011, "end": 2012}]}, {"spans": [{"start": 2013, "end": 2016}]}, {"spans": [{"start": 2017, "end": 2018}]}, {"spans": [{"start": 2019, "end": 2023}]}, {"spans": [{"start": 2024, "end": 2025}]}, {"spans": [{"start": 2026, "end": 2031}]}, {"spans": [{"start": 2032, "end": 2033}]}, {"spans": [{"start": 2034, "end": 2038}]}, {"spans": [{"start": 2039, "end": 2040}]}, {"spans": [{"start": 2041, "end": 2042}]}, {"spans": [{"start": 2043, "end": 2050}]}, {"spans": [{"start": 2051, "end": 2052}]}, {"spans": [{"start": 2053, "end": 2059}]}, {"spans": [{"start": 2060, "end": 2063}]}, {"spans": [{"start": 2064, "end": 2065}]}, {"spans": [{"start": 2066, "end": 2073}]}, {"spans": [{"start": 2074, "end": 2078}]}, {"spans": [{"start": 2079, "end": 2080}]}, {"spans": [{"start": 2081, "end": 2084}]}, {"spans": [{"start": 2085, "end": 2090}]}, {"spans": [{"start": 2091, "end": 2099}]}, {"spans": [{"start": 2100, "end": 2101}]}, {"spans": [{"start": 2102, "end": 2106}]}, {"spans": [{"start": 2107, "end": 2108}]}, {"spans": [{"start": 2109, "end": 2117}]}, {"spans": [{"start": 2118, "end": 2126}]}, {"spans": [{"start": 2127, "end": 2131}]}, {"spans": [{"start": 2132, "end": 2137}]}, {"spans": [{"start": 2138, "end": 2151}]}, {"spans": [{"start": 2152, "end": 2160}]}, {"spans": [{"start": 2161, "end": 2162}]}, {"spans": [{"start": 2163, "end": 2165}]}, {"spans": [{"start": 2166, "end": 2177}]}, {"spans": [{"start": 2178, "end": 2180}]}, {"spans": [{"start": 2181, "end": 2184}]}, {"spans": [{"start": 2185, "end": 2189}]}, {"spans": [{"start": 2190, "end": 2203}]}, {"spans": [{"start": 2204, "end": 2214}]}, {"spans": [{"start": 2215, "end": 2217}]}, {"spans": [{"start": 2218, "end": 2225}]}, {"spans": [{"start": 2226, "end": 2231}]}, {"spans": [{"start": 2232, "end": 2233}]}, {"spans": [{"start": 2234, "end": 2237}]}, {"spans": [{"start": 2238, "end": 2239}]}, {"spans": [{"start": 2240, "end": 2244}]}, {"spans": [{"start": 2245, "end": 2249}]}, {"spans": [{"start": 2250, "end": 2251}]}, {"spans": [{"start": 2252, "end": 2258}]}, {"spans": [{"start": 2259, "end": 2260}]}, {"spans": [{"start": 2261, "end": 2264}]}, {"spans": [{"start": 2265, "end": 2266}]}, {"spans": [{"start": 2267, "end": 2276}]}, {"spans": [{"start": 2277, "end": 2278}]}, {"spans": [{"start": 2279, "end": 2280}]}, {"spans": [{"start": 2281, "end": 2282}]}, {"spans": [{"start": 2283, "end": 2285}]}, {"spans": [{"start": 2286, "end": 2288}]}, {"spans": [{"start": 2289, "end": 2290}]}, {"spans": [{"start": 2291, "end": 2295}]}, {"spans": [{"start": 2296, "end": 2300}]}, {"spans": [{"start": 2301, "end": 2302}]}, {"spans": [{"start": 2303, "end": 2308}]}, {"spans": [{"start": 2309, "end": 2312}]}, {"spans": [{"start": 2313, "end": 2314}]}, {"spans": [{"start": 2315, "end": 2318}]}, {"spans": [{"start": 2319, "end": 2320}]}, {"spans": [{"start": 2321, "end": 2326}]}, {"spans": [{"start": 2327, "end": 2333}]}, {"spans": [{"start": 2334, "end": 2335}]}, {"spans": [{"start": 2336, "end": 2340}]}, {"spans": [{"start": 2341, "end": 2342}]}, {"spans": [{"start": 2343, "end": 2346}]}, {"spans": [{"start": 2347, "end": 2352}]}, {"spans": [{"start": 2353, "end": 2354}]}, {"spans": [{"start": 2355, "end": 2361}]}, {"spans": [{"start": 2362, "end": 2365}]}, {"spans": [{"start": 2366, "end": 2367}]}, {"spans": [{"start": 2368, "end": 2371}]}, {"spans": [{"start": 2372, "end": 2380}]}, {"spans": [{"start": 2381, "end": 2390}]}, {"spans": [{"start": 2391, "end": 2392}]}, {"spans": [{"start": 2393, "end": 2398}]}, {"spans": [{"start": 2399, "end": 2400}]}, {"spans": [{"start": 2401, "end": 2405}]}, {"spans": [{"start": 2406, "end": 2407}]}, {"spans": [{"start": 2408, "end": 2411}]}, {"spans": [{"start": 2412, "end": 2413}]}, {"spans": [{"start": 2414, "end": 2422}]}, {"spans": [{"start": 2423, "end": 2425}]}, {"spans": [{"start": 2426, "end": 2430}]}, {"spans": [{"start": 2431, "end": 2444}]}, {"spans": [{"start": 2445, "end": 2457}]}, {"spans": [{"start": 2458, "end": 2461}]}, {"spans": [{"start": 2462, "end": 2470}]}, {"spans": [{"start": 2471, "end": 2476}]}, {"spans": [{"start": 2477, "end": 2478}]}, {"spans": [{"start": 2479, "end": 2487}]}, {"spans": [{"start": 2488, "end": 2489}]}, {"spans": [{"start": 2490, "end": 2494}]}, {"spans": [{"start": 2495, "end": 2496}]}, {"spans": [{"start": 2497, "end": 2500}]}, {"spans": [{"start": 2501, "end": 2502}]}, {"spans": [{"start": 2503, "end": 2507}]}, {"spans": [{"start": 2508, "end": 2509}]}, {"spans": [{"start": 2510, "end": 2515}]}, {"spans": [{"start": 2516, "end": 2517}]}, {"spans": [{"start": 2518, "end": 2523}]}, {"spans": [{"start": 2524, "end": 2530}]}, {"spans": [{"start": 2531, "end": 2532}]}, {"spans": [{"start": 2533, "end": 2537}]}, {"spans": [{"start": 2538, "end": 2539}]}, {"spans": [{"start": 2540, "end": 2543}]}, {"spans": [{"start": 2544, "end": 2549}]}, {"spans": [{"start": 2550, "end": 2551}]}, {"spans": [{"start": 2552, "end": 2558}]}, {"spans": [{"start": 2559, "end": 2562}]}, {"spans": [{"start": 2563, "end": 2564}]}, {"spans": [{"start": 2565, "end": 2568}]}, {"spans": [{"start": 2569, "end": 2577}]}, {"spans": [{"start": 2578, "end": 2587}]}, {"spans": [{"start": 2588, "end": 2589}]}, {"spans": [{"start": 2590, "end": 2595}]}, {"spans": [{"start": 2596, "end": 2597}]}, {"spans": [{"start": 2598, "end": 2602}]}, {"spans": [{"start": 2603, "end": 2604}]}, {"spans": [{"start": 2605, "end": 2608}]}, {"spans": [{"start": 2609, "end": 2610}]}, {"spans": [{"start": 2611, "end": 2619}]}, {"spans": [{"start": 2620, "end": 2622}]}, {"spans": [{"start": 2623, "end": 2627}]}, {"spans": [{"start": 2628, "end": 2641}]}, {"spans": [{"start": 2642, "end": 2654}]}, {"spans": [{"start": 2655, "end": 2658}]}, {"spans": [{"start": 2659, "end": 2667}]}, {"spans": [{"start": 2668, "end": 2681}]}, {"spans": [{"start": 2682, "end": 2683}]}, {"spans": [{"start": 2684, "end": 2689}]}, {"spans": [{"start": 2690, "end": 2691}]}, {"spans": [{"start": 2692, "end": 2696}]}, {"spans": [{"start": 2697, "end": 2698}]}, {"spans": [{"start": 2699, "end": 2704}]}, {"spans": [{"start": 2705, "end": 2706}]}, {"spans": [{"start": 2707, "end": 2709}]}, {"spans": [{"start": 2710, "end": 2711}]}, {"spans": [{"start": 2712, "end": 2713}]}, {"spans": [{"start": 2714, "end": 2719}]}, {"spans": [{"start": 2720, "end": 2721}]}, {"spans": [{"start": 2722, "end": 2726}]}, {"spans": [{"start": 2727, "end": 2728}]}, {"spans": [{"start": 2729, "end": 2734}]}, {"spans": [{"start": 2735, "end": 2736}]}, {"spans": [{"start": 2737, "end": 2741}]}, {"spans": [{"start": 2742, "end": 2749}]}, {"spans": [{"start": 2750, "end": 2751}]}, {"spans": [{"start": 2752, "end": 2758}]}, {"spans": [{"start": 2759, "end": 2770}]}, {"spans": [{"start": 2771, "end": 2772}]}, {"spans": [{"start": 2773, "end": 2779}]}, {"spans": [{"start": 2780, "end": 2786}]}, {"spans": [{"start": 2787, "end": 2788}]}, {"spans": [{"start": 2789, "end": 2799}]}, {"spans": [{"start": 2800, "end": 2807}]}, {"spans": [{"start": 2808, "end": 2809}]}, {"spans": [{"start": 2810, "end": 2818}]}, {"spans": [{"start": 2819, "end": 2823}]}, {"spans": [{"start": 2824, "end": 2825}]}, {"spans": [{"start": 2826, "end": 2836}]}, {"spans": [{"start": 2837, "end": 2845}]}, {"spans": [{"start": 2846, "end": 2847}]}, {"spans": [{"start": 2848, "end": 2851}]}, {"spans": [{"start": 2852, "end": 2857}]}, {"spans": [{"start": 2858, "end": 2865}]}, {"spans": [{"start": 2866, "end": 2867}]}, {"spans": [{"start": 2868, "end": 2872}]}, {"spans": [{"start": 2873, "end": 2874}]}, {"spans": [{"start": 2875, "end": 2876}]}, {"spans": [{"start": 2877, "end": 2878}]}, {"spans": [{"start": 2879, "end": 2882}]}, {"spans": [{"start": 2883, "end": 2884}]}, {"spans": [{"start": 2885, "end": 2886}]}, {"spans": [{"start": 2887, "end": 2892}]}, {"spans": [{"start": 2893, "end": 2898}]}, {"spans": [{"start": 2899, "end": 2908}]}, {"spans": [{"start": 2909, "end": 2911}]}, {"spans": [{"start": 2912, "end": 2919}]}, {"spans": [{"start": 2920, "end": 2928}]}, {"spans": [{"start": 2929, "end": 2933}]}, {"spans": [{"start": 2934, "end": 2943}]}, {"spans": [{"start": 2944, "end": 2948}]}, {"spans": [{"start": 2949, "end": 2956}]}, {"spans": [{"start": 2957, "end": 2958}]}, {"spans": [{"start": 2959, "end": 2961}]}, {"spans": [{"start": 2962, "end": 2973}]}, {"spans": [{"start": 2974, "end": 2976}]}, {"spans": [{"start": 2977, "end": 2980}]}, {"spans": [{"start": 2981, "end": 2989}]}, {"spans": [{"start": 2990, "end": 2997}]}, {"spans": [{"start": 2998, "end": 2999}]}, {"spans": [{"start": 3000, "end": 3006}]}, {"spans": [{"start": 3007, "end": 3017}]}, {"spans": [{"start": 3018, "end": 3020}]}, {"spans": [{"start": 3021, "end": 3029}]}, {"spans": [{"start": 3030, "end": 3039}]}, {"spans": [{"start": 3040, "end": 3043}]}, {"spans": [{"start": 3044, "end": 3048}]}, {"spans": [{"start": 3049, "end": 3050}]}, {"spans": [{"start": 3051, "end": 3057}]}, {"spans": [{"start": 3058, "end": 3059}]}, {"spans": [{"start": 3060, "end": 3064}]}, {"spans": [{"start": 3065, "end": 3066}]}, {"spans": [{"start": 3067, "end": 3071}]}, {"spans": [{"start": 3072, "end": 3073}]}, {"spans": [{"start": 3074, "end": 3075}]}, {"spans": [{"start": 3076, "end": 3080}]}, {"spans": [{"start": 3081, "end": 3089}]}, {"spans": [{"start": 3090, "end": 3091}]}, {"spans": [{"start": 3092, "end": 3096}]}, {"spans": [{"start": 3097, "end": 3098}]}, {"spans": [{"start": 3099, "end": 3108}]}, {"spans": [{"start": 3109, "end": 3115}]}, {"spans": [{"start": 3116, "end": 3125}]}, {"spans": [{"start": 3126, "end": 3131}]}, {"spans": [{"start": 3132, "end": 3133}]}, {"spans": [{"start": 3134, "end": 3138}]}, {"spans": [{"start": 3139, "end": 3140}]}, {"spans": [{"start": 3141, "end": 3145}]}, {"spans": [{"start": 3146, "end": 3147}]}, {"spans": [{"start": 3148, "end": 3151}]}, {"spans": [{"start": 3152, "end": 3153}]}, {"spans": [{"start": 3154, "end": 3158}]}, {"spans": [{"start": 3159, "end": 3160}]}, {"spans": [{"start": 3161, "end": 3166}]}, {"spans": [{"start": 3167, "end": 3168}]}, {"spans": [{"start": 3169, "end": 3174}]}, {"spans": [{"start": 3175, "end": 3179}]}, {"spans": [{"start": 3180, "end": 3181}]}, {"spans": [{"start": 3182, "end": 3185}]}, {"spans": [{"start": 3186, "end": 3194}]}, {"spans": [{"start": 3195, "end": 3196}]}, {"spans": [{"start": 3197, "end": 3200}]}, {"spans": [{"start": 3201, "end": 3205}]}, {"spans": [{"start": 3206, "end": 3214}]}, {"spans": [{"start": 3215, "end": 3216}]}, {"spans": [{"start": 3217, "end": 3221}]}, {"spans": [{"start": 3222, "end": 3223}]}, {"spans": [{"start": 3224, "end": 3230}]}, {"spans": [{"start": 3231, "end": 3232}]}, {"spans": [{"start": 3233, "end": 3236}]}, {"spans": [{"start": 3237, "end": 3238}]}, {"spans": [{"start": 3239, "end": 3249}]}, {"spans": [{"start": 3250, "end": 3258}]}, {"spans": [{"start": 3259, "end": 3265}]}, {"spans": [{"start": 3266, "end": 3270}]}, {"spans": [{"start": 3271, "end": 3272}]}, {"spans": [{"start": 3273, "end": 3276}]}, {"spans": [{"start": 3277, "end": 3278}]}, {"spans": [{"start": 3279, "end": 3283}]}, {"spans": [{"start": 3284, "end": 3285}]}, {"spans": [{"start": 3286, "end": 3296}]}, {"spans": [{"start": 3297, "end": 3307}]}, {"spans": [{"start": 3308, "end": 3309}]}, {"spans": [{"start": 3310, "end": 3323}]}, {"spans": [{"start": 3324, "end": 3331}]}, {"spans": [{"start": 3332, "end": 3333}]}, {"spans": [{"start": 3334, "end": 3338}]}, {"spans": [{"start": 3339, "end": 3340}]}, {"spans": [{"start": 3341, "end": 3343}]}, {"spans": [{"start": 3344, "end": 3345}]}, {"spans": [{"start": 3346, "end": 3347}]}, {"spans": [{"start": 3348, "end": 3349}]}, {"spans": [{"start": 3350, "end": 3351}]}, {"spans": [{"start": 3352, "end": 3355}]}, {"spans": [{"start": 3356, "end": 3357}]}, {"spans": [{"start": 3358, "end": 3361}]}, {"spans": [{"start": 3362, "end": 3363}]}, {"spans": [{"start": 3364, "end": 3368}]}, {"spans": [{"start": 3369, "end": 3379}]}, {"spans": [{"start": 3380, "end": 3383}]}, {"spans": [{"start": 3384, "end": 3391}]}, {"spans": [{"start": 3392, "end": 3403}]}, {"spans": [{"start": 3404, "end": 3405}]}, {"spans": [{"start": 3406, "end": 3410}]}, {"spans": [{"start": 3411, "end": 3412}]}, {"spans": [{"start": 3413, "end": 3417}]}, {"spans": [{"start": 3418, "end": 3423}]}, {"spans": [{"start": 3424, "end": 3425}]}, {"spans": [{"start": 3426, "end": 3430}]}, {"spans": [{"start": 3431, "end": 3437}]}, {"spans": [{"start": 3438, "end": 3439}]}, {"spans": [{"start": 3440, "end": 3446}]}, {"spans": [{"start": 3447, "end": 3458}]}, {"spans": [{"start": 3459, "end": 3460}]}, {"spans": [{"start": 3461, "end": 3462}]}, {"spans": [{"start": 3463, "end": 3464}]}, {"spans": [{"start": 3465, "end": 3466}]}, {"spans": [{"start": 3467, "end": 3468}]}, {"spans": [{"start": 3469, "end": 3470}]}, {"spans": [{"start": 3471, "end": 3475}]}, {"spans": [{"start": 3476, "end": 3477}]}, {"spans": [{"start": 3478, "end": 3482}]}, {"spans": [{"start": 3483, "end": 3484}]}, {"spans": [{"start": 3485, "end": 3488}]}, {"spans": [{"start": 3489, "end": 3500}]}, {"spans": [{"start": 3501, "end": 3502}]}, {"spans": [{"start": 3503, "end": 3513}]}, {"spans": [{"start": 3514, "end": 3522}]}, {"spans": [{"start": 3523, "end": 3524}]}, {"spans": [{"start": 3525, "end": 3531}]}, {"spans": [{"start": 3532, "end": 3541}]}, {"spans": [{"start": 3542, "end": 3543}]}, {"spans": [{"start": 3544, "end": 3551}]}, {"spans": [{"start": 3552, "end": 3559}]}, {"spans": [{"start": 3560, "end": 3561}]}, {"spans": [{"start": 3562, "end": 3567}]}, {"spans": [{"start": 3568, "end": 3574}]}, {"spans": [{"start": 3575, "end": 3576}]}, {"spans": [{"start": 3577, "end": 3582}]}, {"spans": [{"start": 3583, "end": 3585}]}, {"spans": [{"start": 3586, "end": 3587}]}, {"spans": [{"start": 3588, "end": 3593}]}, {"spans": [{"start": 3594, "end": 3595}]}, {"spans": [{"start": 3596, "end": 3604}]}, {"spans": [{"start": 3605, "end": 3612}]}, {"spans": [{"start": 3613, "end": 3614}]}, {"spans": [{"start": 3615, "end": 3620}]}, {"spans": [{"start": 3621, "end": 3631}]}, {"spans": [{"start": 3632, "end": 3633}]}, {"spans": [{"start": 3634, "end": 3641}]}, {"spans": [{"start": 3642, "end": 3648}]}, {"spans": [{"start": 3649, "end": 3650}]}, {"spans": [{"start": 3651, "end": 3656}]}, {"spans": [{"start": 3657, "end": 3663}]}, {"spans": [{"start": 3664, "end": 3665}]}, {"spans": [{"start": 3666, "end": 3668}]}, {"spans": [{"start": 3669, "end": 3671}]}, {"spans": [{"start": 3672, "end": 3673}]}, {"spans": [{"start": 3674, "end": 3678}]}, {"spans": [{"start": 3679, "end": 3680}]}, {"spans": [{"start": 3681, "end": 3688}]}, {"spans": [{"start": 3689, "end": 3698}]}, {"spans": [{"start": 3699, "end": 3700}]}, {"spans": [{"start": 3701, "end": 3702}]}, {"spans": [{"start": 3703, "end": 3712}]}, {"spans": [{"start": 3713, "end": 3716}]}, {"spans": [{"start": 3717, "end": 3725}]}, {"spans": [{"start": 3726, "end": 3735}]}, {"spans": [{"start": 3736, "end": 3744}]}, {"spans": [{"start": 3745, "end": 3746}]}, {"spans": [{"start": 3747, "end": 3753}]}, {"spans": [{"start": 3754, "end": 3762}]}, {"spans": [{"start": 3763, "end": 3764}]}, {"spans": [{"start": 3765, "end": 3771}]}, {"spans": [{"start": 3772, "end": 3780}]}, {"spans": [{"start": 3781, "end": 3782}]}, {"spans": [{"start": 3783, "end": 3790}]}, {"spans": [{"start": 3791, "end": 3799}]}, {"spans": [{"start": 3800, "end": 3801}]}, {"spans": [{"start": 3802, "end": 3807}]}, {"spans": [{"start": 3808, "end": 3816}]}, {"spans": [{"start": 3817, "end": 3818}]}, {"spans": [{"start": 3819, "end": 3824}]}, {"spans": [{"start": 3825, "end": 3832}]}, {"spans": [{"start": 3833, "end": 3834}]}, {"spans": [{"start": 3835, "end": 3841}]}, {"spans": [{"start": 3842, "end": 3848}]}, {"spans": [{"start": 3849, "end": 3850}]}, {"spans": [{"start": 3851, "end": 3857}]}, {"spans": [{"start": 3858, "end": 3859}]}, {"spans": [{"start": 3860, "end": 3866}]}, {"spans": [{"start": 3867, "end": 3875}]}, {"spans": [{"start": 3876, "end": 3877}]}, {"spans": [{"start": 3878, "end": 3881}]}, {"spans": [{"start": 3882, "end": 3885}]}, {"spans": [{"start": 3886, "end": 3898}]}, {"spans": [{"start": 3899, "end": 3900}]}, {"spans": [{"start": 3901, "end": 3905}]}, {"spans": [{"start": 3906, "end": 3907}]}, {"spans": [{"start": 3908, "end": 3909}]}, {"spans": [{"start": 3910, "end": 3916}]}, {"spans": [{"start": 3917, "end": 3919}]}, {"spans": [{"start": 3920, "end": 3933}]}, {"spans": [{"start": 3934, "end": 3942}]}, {"spans": [{"start": 3943, "end": 3945}]}, {"spans": [{"start": 3946, "end": 3947}]}, {"spans": [{"start": 3948, "end": 3954}]}, {"spans": [{"start": 3955, "end": 3957}]}, {"spans": [{"start": 3958, "end": 3965}]}, {"spans": [{"start": 3966, "end": 3974}]}, {"spans": [{"start": 3975, "end": 3976}]}, {"spans": [{"start": 3977, "end": 3979}]}, {"spans": [{"start": 3980, "end": 3991}]}, {"spans": [{"start": 3992, "end": 3994}]}, {"spans": [{"start": 3995, "end": 3998}]}, {"spans": [{"start": 3999, "end": 4005}]}, {"spans": [{"start": 4006, "end": 4007}]}, {"spans": [{"start": 4008, "end": 4014}]}, {"spans": [{"start": 4015, "end": 4028}]}, {"spans": [{"start": 4029, "end": 4034}]}, {"spans": [{"start": 4035, "end": 4045}]}, {"spans": [{"start": 4046, "end": 4048}]}, {"spans": [{"start": 4049, "end": 4058}]}, {"spans": [{"start": 4059, "end": 4071}]}, {"spans": [{"start": 4072, "end": 4073}]}, {"spans": [{"start": 4074, "end": 4079}]}, {"spans": [{"start": 4080, "end": 4084}]}, {"spans": [{"start": 4085, "end": 4086}]}, {"spans": [{"start": 4087, "end": 4093}]}, {"spans": [{"start": 4094, "end": 4096}]}, {"spans": [{"start": 4097, "end": 4098}]}, {"spans": [{"start": 4099, "end": 4101}]}, {"spans": [{"start": 4102, "end": 4106}]}, {"spans": [{"start": 4107, "end": 4108}]}, {"spans": [{"start": 4109, "end": 4114}]}, {"spans": [{"start": 4115, "end": 4116}]}, {"spans": [{"start": 4117, "end": 4122}]}, {"spans": [{"start": 4123, "end": 4124}]}, {"spans": [{"start": 4125, "end": 4132}]}, {"spans": [{"start": 4133, "end": 4139}]}, {"spans": [{"start": 4140, "end": 4143}]}, {"spans": [{"start": 4144, "end": 4147}]}, {"spans": [{"start": 4148, "end": 4154}]}, {"spans": [{"start": 4155, "end": 4156}]}, {"spans": [{"start": 4157, "end": 4161}]}, {"spans": [{"start": 4162, "end": 4163}]}, {"spans": [{"start": 4164, "end": 4172}]}, {"spans": [{"start": 4173, "end": 4176}]}, {"spans": [{"start": 4177, "end": 4178}]}, {"spans": [{"start": 4179, "end": 4185}]}, {"spans": [{"start": 4186, "end": 4196}]}, {"spans": [{"start": 4197, "end": 4199}]}, {"spans": [{"start": 4200, "end": 4208}]}, {"spans": [{"start": 4209, "end": 4215}]}, {"spans": [{"start": 4216, "end": 4217}]}, {"spans": [{"start": 4218, "end": 4220}]}, {"spans": [{"start": 4221, "end": 4228}]}, {"spans": [{"start": 4229, "end": 4230}]}, {"spans": [{"start": 4231, "end": 4235}]}, {"spans": [{"start": 4236, "end": 4238}]}, {"spans": [{"start": 4239, "end": 4242}]}, {"spans": [{"start": 4243, "end": 4247}]}, {"spans": [{"start": 4248, "end": 4258}]}, {"spans": [{"start": 4259, "end": 4261}]}, {"spans": [{"start": 4262, "end": 4271}]}, {"spans": [{"start": 4272, "end": 4279}]}, {"spans": [{"start": 4280, "end": 4282}]}, {"spans": [{"start": 4283, "end": 4290}]}, {"spans": [{"start": 4291, "end": 4299}]}, {"spans": [{"start": 4300, "end": 4310}]}, {"spans": [{"start": 4311, "end": 4312}]}, {"spans": [{"start": 4313, "end": 4321}]}, {"spans": [{"start": 4322, "end": 4323}]}, {"spans": [{"start": 4324, "end": 4331}]}, {"spans": [{"start": 4332, "end": 4333}]}, {"spans": [{"start": 4334, "end": 4341}]}, {"spans": [{"start": 4342, "end": 4344}]}, {"spans": [{"start": 4345, "end": 4346}]}, {"spans": [{"start": 4347, "end": 4355}]}, {"spans": [{"start": 4356, "end": 4357}]}, {"spans": [{"start": 4358, "end": 4359}]}, {"spans": [{"start": 4360, "end": 4364}]}, {"spans": [{"start": 4365, "end": 4366}]}, {"spans": [{"start": 4367, "end": 4372}]}, {"spans": [{"start": 4373, "end": 4377}]}, {"spans": [{"start": 4378, "end": 4379}]}, {"spans": [{"start": 4380, "end": 4384}]}, {"spans": [{"start": 4385, "end": 4386}]}, {"spans": [{"start": 4387, "end": 4388}]}, {"spans": [{"start": 4389, "end": 4390}]}, {"spans": [{"start": 4391, "end": 4397}]}, {"spans": [{"start": 4398, "end": 4403}]}, {"spans": [{"start": 4404, "end": 4405}]}, {"spans": [{"start": 4406, "end": 4411}]}, {"spans": [{"start": 4412, "end": 4419}]}, {"spans": [{"start": 4420, "end": 4421}]}, {"spans": [{"start": 4422, "end": 4425}]}, {"spans": [{"start": 4426, "end": 4429}]}, {"spans": [{"start": 4430, "end": 4436}]}, {"spans": [{"start": 4437, "end": 4438}]}, {"spans": [{"start": 4439, "end": 4443}]}, {"spans": [{"start": 4444, "end": 4445}]}, {"spans": [{"start": 4446, "end": 4451}]}, {"spans": [{"start": 4452, "end": 4455}]}, {"spans": [{"start": 4456, "end": 4459}]}, {"spans": [{"start": 4460, "end": 4465}]}, {"spans": [{"start": 4466, "end": 4473}]}, {"spans": [{"start": 4474, "end": 4475}]}, {"spans": [{"start": 4476, "end": 4486}]}, {"spans": [{"start": 4487, "end": 4490}]}, {"spans": [{"start": 4491, "end": 4492}]}, {"spans": [{"start": 4493, "end": 4499}]}, {"spans": [{"start": 4500, "end": 4510}]}, {"spans": [{"start": 4511, "end": 4513}]}, {"spans": [{"start": 4514, "end": 4521}]}, {"spans": [{"start": 4522, "end": 4530}]}, {"spans": [{"start": 4531, "end": 4540}]}, {"spans": [{"start": 4541, "end": 4542}]}, {"spans": [{"start": 4543, "end": 4549}]}, {"spans": [{"start": 4550, "end": 4555}]}, {"spans": [{"start": 4556, "end": 4557}]}, {"spans": [{"start": 4558, "end": 4563}]}, {"spans": [{"start": 4564, "end": 4568}]}, {"spans": [{"start": 4569, "end": 4570}]}, {"spans": [{"start": 4571, "end": 4574}]}, {"spans": [{"start": 4575, "end": 4579}]}, {"spans": [{"start": 4580, "end": 4587}]}, {"spans": [{"start": 4588, "end": 4589}]}, {"spans": [{"start": 4590, "end": 4594}]}, {"spans": [{"start": 4595, "end": 4596}]}, {"spans": [{"start": 4597, "end": 4599}]}, {"spans": [{"start": 4600, "end": 4603}]}, {"spans": [{"start": 4604, "end": 4609}]}, {"spans": [{"start": 4610, "end": 4612}]}, {"spans": [{"start": 4613, "end": 4616}]}, {"spans": [{"start": 4617, "end": 4620}]}, {"spans": [{"start": 4621, "end": 4623}]}, {"spans": [{"start": 4624, "end": 4634}]}, {"spans": [{"start": 4635, "end": 4637}]}, {"spans": [{"start": 4638, "end": 4644}]}, {"spans": [{"start": 4645, "end": 4653}]}, {"spans": [{"start": 4654, "end": 4660}]}, {"spans": [{"start": 4661, "end": 4662}]}, {"spans": [{"start": 4663, "end": 4667}]}, {"spans": [{"start": 4668, "end": 4669}]}, {"spans": [{"start": 4670, "end": 4673}]}, {"spans": [{"start": 4674, "end": 4675}]}, {"spans": [{"start": 4676, "end": 4680}]}, {"spans": [{"start": 4681, "end": 4682}]}, {"spans": [{"start": 4683, "end": 4688}]}, {"spans": [{"start": 4689, "end": 4690}]}, {"spans": [{"start": 4691, "end": 4698}]}, {"spans": [{"start": 4699, "end": 4705}]}, {"spans": [{"start": 4706, "end": 4707}]}, {"spans": [{"start": 4708, "end": 4715}]}, {"spans": [{"start": 4716, "end": 4721}]}, {"spans": [{"start": 4722, "end": 4723}]}, {"spans": [{"start": 4724, "end": 4729}]}, {"spans": [{"start": 4730, "end": 4738}]}, {"spans": [{"start": 4739, "end": 4740}]}, {"spans": [{"start": 4741, "end": 4744}]}, {"spans": [{"start": 4745, "end": 4752}]}, {"spans": [{"start": 4753, "end": 4759}]}, {"spans": [{"start": 4760, "end": 4761}]}, {"spans": [{"start": 4762, "end": 4766}]}, {"spans": [{"start": 4767, "end": 4768}]}, {"spans": [{"start": 4769, "end": 4776}]}, {"spans": [{"start": 4777, "end": 4785}]}, {"spans": [{"start": 4786, "end": 4793}]}, {"spans": [{"start": 4794, "end": 4800}]}, {"spans": [{"start": 4801, "end": 4802}]}, {"spans": [{"start": 4803, "end": 4807}]}, {"spans": [{"start": 4808, "end": 4809}]}, {"spans": [{"start": 4810, "end": 4813}]}, {"spans": [{"start": 4814, "end": 4815}]}, {"spans": [{"start": 4816, "end": 4820}]}, {"spans": [{"start": 4821, "end": 4822}]}, {"spans": [{"start": 4823, "end": 4828}]}, {"spans": [{"start": 4829, "end": 4830}]}, {"spans": [{"start": 4831, "end": 4836}]}, {"spans": [{"start": 4837, "end": 4844}]}, {"spans": [{"start": 4845, "end": 4848}]}, {"spans": [{"start": 4849, "end": 4852}]}, {"spans": [{"start": 4853, "end": 4854}]}, {"spans": [{"start": 4855, "end": 4858}]}, {"spans": [{"start": 4859, "end": 4864}]}, {"spans": [{"start": 4865, "end": 4866}]}, {"spans": [{"start": 4867, "end": 4871}]}, {"spans": [{"start": 4872, "end": 4873}]}, {"spans": [{"start": 4874, "end": 4881}]}, {"spans": [{"start": 4882, "end": 4891}]}, {"spans": [{"start": 4892, "end": 4901}]}, {"spans": [{"start": 4902, "end": 4908}]}, {"spans": [{"start": 4909, "end": 4916}]}, {"spans": [{"start": 4917, "end": 4925}]}, {"spans": [{"start": 4926, "end": 4931}]}, {"spans": [{"start": 4932, "end": 4933}]}, {"spans": [{"start": 4934, "end": 4936}]}, {"spans": [{"start": 4937, "end": 4941}]}, {"spans": [{"start": 4942, "end": 4946}]}, {"spans": [{"start": 4947, "end": 4953}]}, {"spans": [{"start": 4954, "end": 4962}]}, {"spans": [{"start": 4963, "end": 4973}]}, {"spans": [{"start": 4974, "end": 4978}]}, {"spans": [{"start": 4979, "end": 4980}]}, {"spans": [{"start": 4981, "end": 4985}]}, {"spans": [{"start": 4986, "end": 4987}]}, {"spans": [{"start": 4988, "end": 4991}]}, {"spans": [{"start": 4992, "end": 4993}]}, {"spans": [{"start": 4994, "end": 4995}]}, {"spans": [{"start": 4996, "end": 5001}]}, {"spans": [{"start": 5002, "end": 5003}]}, {"spans": [{"start": 5004, "end": 5006}]}, {"spans": [{"start": 5007, "end": 5008}]}, {"spans": [{"start": 5009, "end": 5012}]}, {"spans": [{"start": 5013, "end": 5014}]}, {"spans": [{"start": 5015, "end": 5023}]}, {"spans": [{"start": 5024, "end": 5025}]}, {"spans": [{"start": 5026, "end": 5027}]}, {"spans": [{"start": 5028, "end": 5029}]}, {"spans": [{"start": 5030, "end": 5031}]}, {"spans": [{"start": 5032, "end": 5036}]}, {"spans": [{"start": 5037, "end": 5038}]}, {"spans": [{"start": 5039, "end": 5044}]}, {"spans": [{"start": 5045, "end": 5048}]}, {"spans": [{"start": 5049, "end": 5050}]}, {"spans": [{"start": 5051, "end": 5054}]}, {"spans": [{"start": 5055, "end": 5056}]}]}
class TestSpangroupClassificationPredictor(unittest.TestCase):
def setUp(self):
self.doc = Document.from_json(doc_dict=TEST_DOC_JSON)
sg1 = SpanGroup(spans=[Span(start=86, end=456)])
sg2 = SpanGroup(spans=[Span(start=457, end=641)])
self.doc.annotate(bibs=[sg1, sg2])
self.predictor = SpanGroupClassificationPredictor.from_pretrained(
model_name_or_path=TEST_SCIBERT_WEIGHTS,
span_group_name='tokens',
context_name='pages'
)
def test_predict_pages_tokens(self):
predictor = SpanGroupClassificationPredictor.from_pretrained(
model_name_or_path=TEST_SCIBERT_WEIGHTS,
span_group_name='tokens',
context_name='pages'
)
token_tags = predictor.predict(document=self.doc)
assert len(token_tags) == len([token for page in self.doc.pages for token in page.tokens])
self.doc.annotate(token_tags=token_tags)
for token_tag in token_tags:
assert isinstance(token_tag.metadata.label, str)
assert isinstance(token_tag.metadata.score, float)
def test_predict_bibs_tokens(self):
self.predictor.context_name = 'bibs'
token_tags = self.predictor.predict(document=self.doc)
assert len(token_tags) == len([token for bib in self.doc.bibs for token in bib.tokens])
def test_missing_fields(self):
self.predictor.span_group_name = 'OHNO'
with self.assertRaises(AssertionError) as e:
self.predictor.predict(document=self.doc)
assert 'OHNO' in e.exception
self.predictor.span_group_name = 'tokens'
self.predictor.context_name = 'BLABLA'
with self.assertRaises(AssertionError) as e:
self.predictor.predict(document=self.doc)
assert 'BLABLA' in e.exception
self.predictor.context_name = 'pages'
| 50,583 | 711.450704 | 48,239 |
py
|
mmda
|
mmda-main/tests/test_predictors/test_whitespace_predictor.py
|
"""
@kylel
"""
import unittest
from mmda.predictors import WhitespacePredictor
from mmda.types import Document, SpanGroup, Span
class TestWhitespacePredictor(unittest.TestCase):
def test_predict(self):
# fmt:off
#0 10 20 30 40 50 60 70
#01234567890123456789012345678901234567890123456789012345678901234567890123456789
symbols = "The goal of meta-learning is to train a model on a vari&ety of learning tasks"
# fmt:on
spans = [
Span(start=0, end=3), # The
Span(start=4, end=8), # goal
Span(start=9, end=11), # of
Span(start=12, end=16), # meta
Span(start=16, end=17), # -
Span(start=17, end=25), # learning
Span(start=26, end=28), # is
Span(start=29, end=31), # to
Span(start=32, end=37), # train
Span(start=38, end=39), # a
Span(start=40, end=45), # model
Span(start=46, end=48), # on
Span(start=49, end=50), # a
Span(start=51, end=56), # vari&
Span(start=56, end=59), # ety
Span(start=60, end=62), # of
Span(start=63, end=71), # learning
Span(start=72, end=77), # tasks
]
doc = Document(symbols=symbols)
doc.annotate(tokens=[SpanGroup(id=i, spans=[span]) for i, span in enumerate(spans)])
predictor = WhitespacePredictor()
ws_chunks = predictor.predict(doc)
doc.annotate(ws_chunks=ws_chunks)
self.assertEqual([c.text for c in doc.ws_chunks],
['The', 'goal', 'of', 'meta-learning', 'is', 'to', 'train', 'a', 'model',
'on', 'a', 'vari&ety', 'of', 'learning', 'tasks'])
self.assertEqual(' '.join([c.text for c in doc.ws_chunks]),
doc.symbols)
| 1,942 | 34.327273 | 98 |
py
|
mmda
|
mmda-main/tests/test_types/test_indexers.py
|
import unittest
from mmda.types import SpanGroup, Span
from mmda.types.indexers import SpanGroupIndexer
class TestSpanGroupIndexer(unittest.TestCase):
def test_overlap_within_single_spangroup_fails_checks(self):
span_groups = [
SpanGroup(
id=1,
spans=[
Span(0, 5),
Span(4, 7)
]
)
]
with self.assertRaises(ValueError):
SpanGroupIndexer(span_groups)
def test_overlap_between_spangroups_fails_checks(self):
span_groups = [
SpanGroup(
id=1,
spans=[
Span(0, 5),
Span(5, 8)
]
),
SpanGroup(
id=2,
spans=[Span(6, 10)]
)
]
with self.assertRaises(ValueError):
SpanGroupIndexer(span_groups)
def test_finds_matching_groups_in_doc_order(self):
span_groups_to_index = [
SpanGroup(
id=1,
spans=[
Span(0, 5),
Span(5, 8)
]
),
SpanGroup(
id=2,
spans=[Span(9, 10)]
),
SpanGroup(
id=3,
spans=[Span(100, 105)]
)
]
index = SpanGroupIndexer(span_groups_to_index)
# should intersect 1 and 2 but not 3
probe = SpanGroup(id=3, spans=[Span(1, 7), Span(9, 20)])
matches = index.find(probe)
self.assertEqual(len(matches), 2)
self.assertEqual(matches, [span_groups_to_index[0], span_groups_to_index[1]])
| 1,739 | 23.857143 | 85 |
py
|
mmda
|
mmda-main/tests/test_types/test_box.py
|
import unittest
from mmda.types import box as mmda_box
class TestBox(unittest.TestCase):
def setUp(cls) -> None:
cls.box_dict = {'left': 0.2,
'top': 0.09,
'width': 0.095,
'height': 0.017,
'page': 0}
cls.box = mmda_box.Box(l=0.2, t=0.09, w=0.095, h=0.017, page=0)
def test_from_json(self):
self.assertEqual(self.box.from_json(self.box_dict), self.box)
def test_to_json(self):
self.assertEqual(self.box.to_json(), self.box_dict)
| 571 | 29.105263 | 71 |
py
|
mmda
|
mmda-main/tests/test_types/test_document.py
|
import json
import unittest
import os
from mmda.types.annotation import SpanGroup
from mmda.types.document import Document
from mmda.types.names import MetadataField, SymbolsField
from ai2_internal import api
def resolve(file: str) -> str:
return os.path.join(os.path.dirname(__file__), "../fixtures/types", file)
class TestDocument(unittest.TestCase):
def test__empty_annotations_work(self):
doc = Document("This is a test document!")
annotations = []
doc.annotate(my_cool_field=annotations)
self.assertEqual(doc.my_cool_field, [])
def test_metadata_serializes(self):
metadata = {"a": {"b": "c"}}
symbols = "Hey there y'all!"
doc = Document(symbols=symbols)
doc.add_metadata(**metadata)
output_json = doc.to_json()
self.assertDictEqual(
{SymbolsField: symbols, MetadataField: metadata}, output_json
)
def test_metadata_deserializes(self):
metadata = {"a": {"b": "c"}}
symbols = "Hey again peeps!"
input_json = {SymbolsField: symbols, MetadataField: metadata}
doc = Document.from_json(input_json)
self.assertEqual(symbols, doc.symbols)
self.assertDictEqual(metadata, doc.metadata.to_json())
def test_metadata_deserializes_when_empty(self):
symbols = "That's all folks!"
input_json = {SymbolsField: symbols}
doc = Document.from_json(input_json)
self.assertEqual(symbols, doc.symbols)
self.assertEqual(0, len(doc.metadata))
def test_annotate_box_groups_gets_text(self):
# when token boxes are on box_groups
spp_plumber_doc = "spp-dag-0-0-4-doc.json"
doc_file = resolve(spp_plumber_doc)
with open(doc_file) as f:
spp_doc = Document.from_json(json.load(f))
with open(resolve("test_document_box_groups.json")) as f:
box_groups = [api.BoxGroup(**bg).to_mmda() for bg in json.load(f)["grobid_bibs_box_groups"]]
spp_doc.annotate(new_span_groups=box_groups)
assert spp_doc.new_span_groups[0].text.startswith("Gutman G, Rosenzweig D, Golan J")
# when token boxes are on spans
plumber_doc = "c8b53e2d9cd247e2d42719e337bfb13784d22bd2.json"
doc_file = resolve(plumber_doc)
with open(doc_file) as f:
doc = Document.from_json(json.load(f))
with open(resolve("test_document_box_groups.json")) as f:
box_groups = [api.BoxGroup(**bg).to_mmda() for bg in json.load(f)["grobid_bibs_box_groups"]]
doc.annotate(new_span_groups=box_groups)
assert doc.new_span_groups[0].text.startswith("Gutman G, Rosenzweig D, Golan J")
def test_annotate_box_groups_allocates_all_overlapping_tokens(self):
"""Regression test to verify annotating box groups onto a doc produces the same output as
a last-known-good fixture
"""
# basic doc annotated with pages and tokens, from pdfplumber parser split at punctuation
with open(resolve("20fdafb68d0e69d193527a9a1cbe64e7e69a3798__pdfplumber_doc.json"), "r") as f:
raw_json = f.read()
fixture_doc_json = json.loads(raw_json)
doc = Document.from_json(fixture_doc_json)
# spangroups derived from boxgroups of boxes drawn neatly around bib entries by calling `.annotate` on
# list of BoxGroups
fixture_span_groups = []
with open(resolve("20fdafb68d0e69d193527a9a1cbe64e7e69a3798__bib_entry_span_groups_from_box_groups.json"), "r") as f:
raw_json = f.read()
fixture_bib_entries_json = json.loads(raw_json)["bib_entry_span_groups_from_box_groups"]
# make box_groups to annotate from test fixture bib entry span groups, and save the
for bib_entry in fixture_bib_entries_json:
fixture_span_groups.append(SpanGroup.from_json(bib_entry))
fixture_box_groups = [sg.box_group for sg in fixture_span_groups]
# confirm we get the same SpanGroup spans by calling `.annotate` on the list of BoxGroups
# annotate fixture_span_groups to extract texts
doc.annotate(fixture_span_groups=fixture_span_groups)
# annotate fixture_box_groups to generate span_groups
doc.annotate(fixture_box_groups=fixture_box_groups)
for sg1, sg2 in zip(fixture_span_groups, doc.fixture_box_groups):
assert sg1.spans == sg2.spans
assert sg1.text == sg2.text
| 4,466 | 39.243243 | 125 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.