deepdoctection 0.44.1__py3-none-any.whl → 0.45.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of deepdoctection might be problematic. Click here for more details.

@@ -25,11 +25,10 @@ from .utils.logger import LoggingRecord, logger
25
25
 
26
26
  # pylint: enable=wrong-import-position
27
27
 
28
- __version__ = "0.44.1"
28
+ __version__ = "0.45.0"
29
29
 
30
30
  _IMPORT_STRUCTURE = {
31
- "analyzer": ["config_sanity_checks", "get_dd_analyzer", "ServiceFactory"],
32
- "configs": ["update_cfg_from_defaults"],
31
+ "analyzer": ["config_sanity_checks", "get_dd_analyzer", "ServiceFactory", "update_cfg_from_defaults"],
33
32
  "dataflow": [
34
33
  "DataFlowTerminated",
35
34
  "DataFlowResetStateNotCalled",
@@ -186,7 +185,9 @@ _IMPORT_STRUCTURE = {
186
185
  "HFLayoutLmv3SequenceClassifier",
187
186
  "HFLiltTokenClassifier",
188
187
  "HFLiltSequenceClassifier",
188
+ "HFLmTokenClassifier",
189
189
  "HFLmSequenceClassifier",
190
+ "HFLmLanguageDetector",
190
191
  "ModelProfile",
191
192
  "ModelCatalog",
192
193
  "print_model_infos",
@@ -520,6 +520,13 @@ cfg.USE_LAYOUT_LINK = False
520
520
  # (e.g., by grouping orphan text containers). Only applicable if list items were previously grouped.
521
521
  cfg.USE_LINE_MATCHER = False
522
522
 
523
+ # Enables a sequence classification pipeline component, e.g. a LayoutLM or a Bert-like model.
524
+ cfg.USE_LM_SEQUENCE_CLASS = False
525
+
526
+ # Enables a token classification pipeline component, e.g. a LayoutLM or Bert-like model
527
+ cfg.USE_LM_TOKEN_CLASS = False
528
+
529
+
523
530
  # Relevant when LIB = TF. Specifies the layout detection model.
524
531
  # This model should detect multiple or single objects across an entire page.
525
532
  # Currently, only one default model is supported.
@@ -899,6 +906,40 @@ cfg.LAYOUT_LINK.PARENTAL_CATEGORIES = [LayoutType.FIGURE, LayoutType.TABLE]
899
906
  # These are typically smaller or subordinate elements (e.g., captions).
900
907
  cfg.LAYOUT_LINK.CHILD_CATEGORIES = [LayoutType.CAPTION]
901
908
 
909
+
910
+ # Weights configuration for sequence classifier. This will be a fine-tuned version of a LayoutLM, LayoutLMv2,
911
+ # LayoutXLM, LayoutLMv3, LiLT or Roberta base model for sequence classification.
912
+ cfg.LM_SEQUENCE_CLASS.WEIGHTS = None
913
+
914
+ # When predicting document classes, it might be possible that some pages are empty or do not contain any text, in
915
+ # which case the model will be unable to predict anything. If set to `True` it will
916
+ # assign images with no features the category `TokenClasses.OTHER`.
917
+ cfg.LM_SEQUENCE_CLASS.USE_OTHER_AS_DEFAULT_CATEGORY = False
918
+
919
+ # Weights configuration for sequence classifier. This will be a fine-tuned version of a LayoutLM, LayoutLMv2,
920
+ # LayoutXLM, LayoutLMv3, LiLT or Roberta base model for token classification.
921
+ cfg.LM_TOKEN_CLASS.WEIGHTS = None
922
+
923
+ # When predicting token classes, it might be possible that some words might not get sent to the model because they are
924
+ # categorized as not eligible token (e.g. empty string). If set to `True` it will assign all words without token
925
+ # as `TokenClasses.OTHER`.
926
+ cfg.LM_TOKEN_CLASS.USE_OTHER_AS_DEFAULT_CATEGORY = False
927
+
928
+ # Using bounding boxes of segments instead of words might improve model accuracy
929
+ # for models that have been trained on segments rather than words (e.g. LiLT, LayoutLMv3).
930
+ # Choose a single or a sequence of layout segments to use their bounding boxes. Note,
931
+ # that the layout segments need to have a child-relationship with words. If a word
932
+ # does not appear as child, it will use the word bounding box.
933
+ cfg.LM_TOKEN_CLASS.SEGMENT_POSITIONS = None
934
+
935
+ # If the output of the `tokenizer` exceeds the `max_length` sequence length, a
936
+ # sliding window will be created with each window having `max_length` sequence
937
+ # input. When using `SLIDING_WINDOW_STRIDE=0` no strides will be created,
938
+ # otherwise it will create slides with windows shifted `SLIDING_WINDOW_STRIDE` to
939
+ # the right.
940
+ cfg.LM_TOKEN_CLASS.SLIDING_WINDOW_STRIDE = 0
941
+
942
+
902
943
  # Freezes the configuration to make it immutable.
903
944
  # This prevents accidental modification at runtime.
904
945
  cfg.freeze()
@@ -19,9 +19,10 @@
19
19
  `ServiceFactory` for building analyzers
20
20
  """
21
21
 
22
+ from __future__ import annotations
22
23
 
23
24
  from os import environ
24
- from typing import Union
25
+ from typing import TYPE_CHECKING, Union
25
26
 
26
27
  from lazy_imports import try_import
27
28
 
@@ -29,6 +30,18 @@ from ..extern.base import ImageTransformer, ObjectDetector, PdfMiner
29
30
  from ..extern.d2detect import D2FrcnnDetector, D2FrcnnTracingDetector
30
31
  from ..extern.doctrocr import DoctrTextlineDetector, DoctrTextRecognizer
31
32
  from ..extern.hfdetr import HFDetrDerivedDetector
33
+ from ..extern.hflayoutlm import (
34
+ HFLayoutLmSequenceClassifier,
35
+ HFLayoutLmTokenClassifier,
36
+ HFLayoutLmv2SequenceClassifier,
37
+ HFLayoutLmv2TokenClassifier,
38
+ HFLayoutLmv3SequenceClassifier,
39
+ HFLayoutLmv3TokenClassifier,
40
+ HFLiltSequenceClassifier,
41
+ HFLiltTokenClassifier,
42
+ get_tokenizer_from_model_class,
43
+ )
44
+ from ..extern.hflm import HFLmSequenceClassifier, HFLmTokenClassifier
32
45
  from ..extern.model import ModelCatalog, ModelDownloadManager
33
46
  from ..extern.pdftext import PdfPlumberTextDetector
34
47
  from ..extern.tessocr import TesseractOcrDetector, TesseractRotationTransformer
@@ -45,6 +58,7 @@ from ..pipe.common import (
45
58
  )
46
59
  from ..pipe.doctectionpipe import DoctectionPipe
47
60
  from ..pipe.layout import ImageLayoutService, skip_if_category_or_service_extracted
61
+ from ..pipe.lm import LMSequenceClassifierService, LMTokenClassifierService
48
62
  from ..pipe.order import TextOrderService
49
63
  from ..pipe.refine import TableSegmentationRefinementService
50
64
  from ..pipe.segment import PubtablesSegmentationService, TableSegmentationService
@@ -60,6 +74,10 @@ from ..utils.transform import PadTransform
60
74
  with try_import() as image_guard:
61
75
  from botocore.config import Config # type: ignore
62
76
 
77
+ if TYPE_CHECKING:
78
+ from ..extern.hflayoutlm import LayoutSequenceModels, LayoutTokenModels
79
+ from ..extern.hflm import LmSequenceModels, LmTokenModels
80
+
63
81
 
64
82
  __all__ = [
65
83
  "ServiceFactory",
@@ -841,6 +859,226 @@ class ServiceFactory:
841
859
  """
842
860
  return ServiceFactory._build_text_order_service(config)
843
861
 
862
+ @staticmethod
863
+ def _build_sequence_classifier(config: AttrDict) -> Union[LayoutSequenceModels, LmSequenceModels]:
864
+ """
865
+ Builds and returns a sequence classifier instance.
866
+
867
+ Args:
868
+ config: Configuration object that determines the type of sequence classifier to construct.
869
+
870
+ Returns:
871
+ A sequence classifier instance constructed according to the specified configuration.
872
+ """
873
+ config_path = ModelCatalog.get_full_path_configs(config.LM_SEQUENCE_CLASS.WEIGHTS)
874
+ weights_path = ModelDownloadManager.maybe_download_weights_and_configs(config.LM_SEQUENCE_CLASS.WEIGHTS)
875
+ profile = ModelCatalog.get_profile(config.LM_SEQUENCE_CLASS.WEIGHTS)
876
+ categories = profile.categories if profile.categories is not None else {}
877
+ use_xlm_tokenizer = "xlm_tokenizer" == profile.architecture
878
+
879
+ if profile.model_wrapper in ("HFLayoutLmSequenceClassifier",):
880
+ return HFLayoutLmSequenceClassifier(
881
+ path_config_json=config_path,
882
+ path_weights=weights_path,
883
+ categories=categories,
884
+ device=config.DEVICE,
885
+ use_xlm_tokenizer=use_xlm_tokenizer,
886
+ )
887
+ if profile.model_wrapper in ("HFLayoutLmv2SequenceClassifier",):
888
+ return HFLayoutLmv2SequenceClassifier(
889
+ path_config_json=config_path,
890
+ path_weights=weights_path,
891
+ categories=categories,
892
+ device=config.DEVICE,
893
+ use_xlm_tokenizer=use_xlm_tokenizer,
894
+ )
895
+ if profile.model_wrapper in ("HFLayoutLmv3SequenceClassifier",):
896
+ return HFLayoutLmv3SequenceClassifier(
897
+ path_config_json=config_path,
898
+ path_weights=weights_path,
899
+ categories=categories,
900
+ device=config.DEVICE,
901
+ use_xlm_tokenizer=use_xlm_tokenizer,
902
+ )
903
+ if profile.model_wrapper in ("HFLiltSequenceClassifier",):
904
+ return HFLiltSequenceClassifier(
905
+ path_config_json=config_path,
906
+ path_weights=weights_path,
907
+ categories=categories,
908
+ device=config.DEVICE,
909
+ use_xlm_tokenizer=use_xlm_tokenizer,
910
+ )
911
+ if profile.model_wrapper in ("HFLmSequenceClassifier",):
912
+ return HFLmSequenceClassifier(
913
+ path_config_json=config_path,
914
+ path_weights=weights_path,
915
+ categories=categories,
916
+ device=config.DEVICE,
917
+ use_xlm_tokenizer=use_xlm_tokenizer,
918
+ )
919
+ raise ValueError(f"Unsupported model wrapper: {profile.model_wrapper}")
920
+
921
+ @staticmethod
922
+ def build_sequence_classifier(config: AttrDict) -> Union[LayoutSequenceModels, LmSequenceModels]:
923
+ """
924
+ Builds and returns a sequence classifier instance.
925
+
926
+ Args:
927
+ config: Configuration object that determines the type of sequence classifier to construct.
928
+
929
+ Returns:
930
+ A sequence classifier instance constructed according to the specified configuration.
931
+ """
932
+ return ServiceFactory._build_sequence_classifier(config)
933
+
934
+ @staticmethod
935
+ def _build_sequence_classifier_service(
936
+ config: AttrDict, sequence_classifier: Union[LayoutSequenceModels, LmSequenceModels]
937
+ ) -> LMSequenceClassifierService:
938
+ """
939
+ Building a sequence classifier service.
940
+
941
+ Args:
942
+ config: Configuration object.
943
+ sequence_classifier: Sequence classifier instance.
944
+
945
+ Returns:
946
+ LMSequenceClassifierService: Text order service instance.
947
+ """
948
+ tokenizer_fast = get_tokenizer_from_model_class(
949
+ sequence_classifier.model.__class__.__name__, sequence_classifier.use_xlm_tokenizer
950
+ )
951
+
952
+ return LMSequenceClassifierService(
953
+ tokenizer=tokenizer_fast,
954
+ language_model=sequence_classifier,
955
+ use_other_as_default_category=config.LM_SEQUENCE_CLASS.USE_OTHER_AS_DEFAULT_CATEGORY,
956
+ )
957
+
958
+ @staticmethod
959
+ def build_sequence_classifier_service(
960
+ config: AttrDict, sequence_classifier: Union[LayoutSequenceModels, LmSequenceModels]
961
+ ) -> LMSequenceClassifierService:
962
+ """
963
+ Building a sequence classifier service.
964
+
965
+ Args:
966
+ config: Configuration object.
967
+ sequence_classifier: Sequence classifier instance.
968
+
969
+ Returns:
970
+ LMSequenceClassifierService: Text order service instance.
971
+ """
972
+ return ServiceFactory._build_sequence_classifier_service(config, sequence_classifier)
973
+
974
+ @staticmethod
975
+ def _build_token_classifier(config: AttrDict) -> Union[LayoutTokenModels, LmTokenModels]:
976
+ """
977
+ Builds and returns a token classifier model.
978
+
979
+ Args:
980
+ config: Configuration object.
981
+
982
+ Returns:
983
+ The instantiated token classifier model.
984
+ """
985
+ config_path = ModelCatalog.get_full_path_configs(config.LM_TOKEN_CLASS.WEIGHTS)
986
+ weights_path = ModelDownloadManager.maybe_download_weights_and_configs(config.LM_TOKEN_CLASS.WEIGHTS)
987
+ profile = ModelCatalog.get_profile(config.LM_TOKEN_CLASS.WEIGHTS)
988
+ categories = profile.categories if profile.categories is not None else {}
989
+ use_xlm_tokenizer = "xlm_tokenizer" == profile.architecture
990
+ if profile.model_wrapper in ("HFLayoutLmTokenClassifier",):
991
+ return HFLayoutLmTokenClassifier(
992
+ path_config_json=config_path,
993
+ path_weights=weights_path,
994
+ categories=categories,
995
+ device=config.DEVICE,
996
+ use_xlm_tokenizer=use_xlm_tokenizer,
997
+ )
998
+ if profile.model_wrapper in ("HFLayoutLmv2TokenClassifier",):
999
+ return HFLayoutLmv2TokenClassifier(
1000
+ path_config_json=config_path,
1001
+ path_weights=weights_path,
1002
+ categories=categories,
1003
+ device=config.DEVICE,
1004
+ )
1005
+ if profile.model_wrapper in ("HFLayoutLmv3TokenClassifier",):
1006
+ return HFLayoutLmv3TokenClassifier(
1007
+ path_config_json=config_path,
1008
+ path_weights=weights_path,
1009
+ categories=categories,
1010
+ device=config.DEVICE,
1011
+ )
1012
+ if profile.model_wrapper in ("HFLiltTokenClassifier",):
1013
+ return HFLiltTokenClassifier(
1014
+ path_config_json=config_path,
1015
+ path_weights=weights_path,
1016
+ categories=categories,
1017
+ device=config.DEVICE,
1018
+ )
1019
+ if profile.model_wrapper in ("HFLmTokenClassifier",):
1020
+ return HFLmTokenClassifier(
1021
+ path_config_json=config_path,
1022
+ path_weights=weights_path,
1023
+ categories=categories,
1024
+ )
1025
+ raise ValueError(f"Unsupported model wrapper: {profile.model_wrapper}")
1026
+
1027
+ @staticmethod
1028
+ def build_token_classifier(config: AttrDict) -> Union[LayoutTokenModels, LmTokenModels]:
1029
+ """
1030
+ Builds and returns a token classifier model.
1031
+
1032
+ Args:
1033
+ config: Configuration object.
1034
+
1035
+ Returns:
1036
+ The instantiated token classifier model.
1037
+ """
1038
+ return ServiceFactory._build_token_classifier(config)
1039
+
1040
+ @staticmethod
1041
+ def _build_token_classifier_service(
1042
+ config: AttrDict, token_classifier: Union[LayoutTokenModels, LmTokenModels]
1043
+ ) -> LMTokenClassifierService:
1044
+ """
1045
+ Building a token classifier service.
1046
+
1047
+ Args:
1048
+ config: Configuration object.
1049
+ token_classifier: Token classifier instance.
1050
+
1051
+ Returns:
1052
+ A LMTokenClassifierService instance.
1053
+ """
1054
+ tokenizer_fast = get_tokenizer_from_model_class(
1055
+ token_classifier.model.__class__.__name__, token_classifier.use_xlm_tokenizer
1056
+ )
1057
+
1058
+ return LMTokenClassifierService(
1059
+ tokenizer=tokenizer_fast,
1060
+ language_model=token_classifier,
1061
+ use_other_as_default_category=config.LM_TOKEN_CLASS.USE_OTHER_AS_DEFAULT_CATEGORY,
1062
+ segment_positions=config.LM_TOKEN_CLASS.SEGMENT_POSITIONS,
1063
+ sliding_window_stride=config.LM_TOKEN_CLASS.SLIDING_WINDOW_STRIDE,
1064
+ )
1065
+
1066
+ @staticmethod
1067
+ def build_token_classifier_service(
1068
+ config: AttrDict, token_classifier: Union[LayoutTokenModels, LmTokenModels]
1069
+ ) -> LMTokenClassifierService:
1070
+ """
1071
+ Building a token classifier service.
1072
+
1073
+ Args:
1074
+ config: Configuration object.
1075
+ token_classifier: Token classifier instance.
1076
+
1077
+ Returns:
1078
+ A LMTokenClassifierService instance.
1079
+ """
1080
+ return ServiceFactory._build_token_classifier_service(config, token_classifier)
1081
+
844
1082
  @staticmethod
845
1083
  def _build_page_parsing_service(config: AttrDict) -> PageParsingService:
846
1084
  """
@@ -955,6 +1193,16 @@ class ServiceFactory:
955
1193
  line_list_matching_service = ServiceFactory.build_line_matching_service(config)
956
1194
  pipe_component_list.append(line_list_matching_service)
957
1195
 
1196
+ if config.USE_LM_SEQUENCE_CLASS:
1197
+ sequence_classifier = ServiceFactory.build_sequence_classifier(config)
1198
+ sequence_classifier_service = ServiceFactory.build_sequence_classifier_service(config, sequence_classifier)
1199
+ pipe_component_list.append(sequence_classifier_service)
1200
+
1201
+ if config.USE_LM_TOKEN_CLASS:
1202
+ token_classifier = ServiceFactory.build_token_classifier(config)
1203
+ token_classifier_service = ServiceFactory.build_token_classifier_service(config, token_classifier)
1204
+ pipe_component_list.append(token_classifier_service)
1205
+
958
1206
  page_parsing_service = ServiceFactory.build_page_parsing_service(config)
959
1207
 
960
1208
  return DoctectionPipe(pipeline_component_list=pipe_component_list, page_parsing_service=page_parsing_service)
@@ -30,4 +30,5 @@
30
30
  {"name": "Felix92/doctr-torch-parseq-multilingual-v1/pytorch_model.bin", "description": "", "size": [63286381], "tp_model": false, "config": "Felix92/doctr-torch-parseq-multilingual-v1/config.json", "preprocessor_config": null, "hf_repo_id": "Felix92/doctr-torch-parseq-multilingual-v1", "hf_model_name": "pytorch_model.bin", "hf_config_file": ["config.json"], "urls": null, "categories": {}, "categories_orig": null, "dl_library": "PT", "model_wrapper": "DoctrTextRecognizer", "architecture": "parseq", "padding": null}
31
31
  {"name": "doctr/crnn_vgg16_bn/pt/master-fde31e4a.pt", "description": "MASTER", "size": [63286381], "tp_model": false, "config": null, "preprocessor_config": null, "hf_repo_id": null, "hf_model_name": null, "hf_config_file": null, "urls": ["https://doctr-static.mindee.com/models?id=v0.7.0/master-fde31e4a.pt&src=0"], "categories": {}, "categories_orig": null, "dl_library": "PT", "model_wrapper": "DoctrTextRecognizer", "architecture": "master", "padding": null}
32
32
  {"name": "Aryn/deformable-detr-DocLayNet/model.safetensors", "description": "Deformable DEtection TRansformer (DETR), trained on DocLayNet (including 80k annotated pages in 11 classes).", "size": [115511753], "tp_model": false, "config": "Aryn/deformable-detr-DocLayNet/config.json", "preprocessor_config": "Aryn/deformable-detr-DocLayNet/preprocessor_config.json", "hf_repo_id": "Aryn/deformable-detr-DocLayNet", "hf_model_name": "model.safetensors", "hf_config_file": ["config.json", "preprocessor_config.json"], "urls": null, "categories": {"1": "default_type", "2": "caption", "11": "text", "12": "title", "3": "footnote", "4": "formula", "5": "list_item", "6": "page_footer", "7": "page_header", "8": "figure", "9": "section_header", "10": "table"}, "categories_orig": null, "dl_library": "PT", "model_wrapper": "HFDetrDerivedDetector", "architecture": null, "padding": null}
33
- {"name": "deepdoctection/tatr_tab_struct_v2/model.safetensors", "description": "Table Transformer (DETR) model trained on PubTables1M. It was introduced in the paper Aligning benchmark datasets for table structure recognition by Smock et al. This model is devoted to table structure recognition and assumes to receive a slightly croppedtable as input. It will predict rows, column and spanning cells. Use a padding of around 5 pixels. This artefact has been converted from deepdoctection/tatr_tab_struct_v2/pytorch_model.bin and should be used to reduce security issues", "size": [115511753], "tp_model": false, "config": "deepdoctection/tatr_tab_struct_v2/config.json", "preprocessor_config": "deepdoctection/tatr_tab_struct_v2/preprocessor_config.json", "hf_repo_id": "deepdoctection/tatr_tab_struct_v2", "hf_model_name": "model.safetensors", "hf_config_file": ["config.json", "preprocessor_config.json"], "urls": null, "categories": {"1": "table", "2": "column", "3": "row", "4": "column_header", "5": "projected_row_header", "6": "spanning"}, "categories_orig": null, "dl_library": "PT", "model_wrapper": "HFDetrDerivedDetector", "architecture": null, "padding": null}
33
+ {"name": "deepdoctection/tatr_tab_struct_v2/model.safetensors", "description": "Table Transformer (DETR) model trained on PubTables1M. It was introduced in the paper Aligning benchmark datasets for table structure recognition by Smock et al. This model is devoted to table structure recognition and assumes to receive a slightly croppedtable as input. It will predict rows, column and spanning cells. Use a padding of around 5 pixels. This artefact has been converted from deepdoctection/tatr_tab_struct_v2/pytorch_model.bin and should be used to reduce security issues", "size": [115511753], "tp_model": false, "config": "deepdoctection/tatr_tab_struct_v2/config.json", "preprocessor_config": "deepdoctection/tatr_tab_struct_v2/preprocessor_config.json", "hf_repo_id": "deepdoctection/tatr_tab_struct_v2", "hf_model_name": "model.safetensors", "hf_config_file": ["config.json", "preprocessor_config.json"], "urls": null, "categories": {"1": "table", "2": "column", "3": "row", "4": "column_header", "5": "projected_row_header", "6": "spanning"}, "categories_orig": null, "dl_library": "PT", "model_wrapper": "HFDetrDerivedDetector", "architecture": null, "padding": null}
34
+ {"name": "papluca/xlm-roberta-base-language-detection/model.safetensors", "description": "This model is an XLM-RoBERTa transformer model with a classification head on top (i.e. a linear layer on top of the pooled output). For additional information please refer to the xlm-roberta-base model card or to the paper Unsupervised Cross-lingual Representation Learning at Scale by Conneau et al.", "size": [101971449], "tp_model": false, "config": "papluca/xlm-roberta-base-language-detection/config.json", "preprocessor_config": null, "hf_repo_id": "papluca/xlm-roberta-base-language-detection", "hf_model_name": "model.safetensors", "hf_config_file": ["config.json"], "urls": null, "categories": {"1": "jpn", "2": "dut", "3": "ara", "4": "pol", "5": "deu", "6": "ita", "7": "por", "8": "tur", "9": "spa", "10": "hin", "11": "gre", "12": "urd", "13": "bul", "14": "eng", "15": "fre", "16": "chi", "17": "rus", "18": "tha", "19": "swa", "20": "vie"}, "categories_orig": null, "dl_library": "PT", "model_wrapper": "HFLmLanguageDetector", "architecture": null, "padding": null}
@@ -319,29 +319,32 @@ class Layout(ImageAnnotationBaseView):
319
319
  token_tag_ann_ids,
320
320
  token_classes_ids,
321
321
  token_tag_ids,
322
- ) = map(list, zip(
323
- *[
324
- (
325
- word.characters,
326
- word.annotation_id,
327
- word.token_class,
328
- word.get_sub_category(WordType.TOKEN_CLASS).annotation_id
329
- if WordType.TOKEN_CLASS in word.sub_categories
330
- else None,
331
- word.token_tag,
332
- word.get_sub_category(WordType.TOKEN_TAG).annotation_id
333
- if WordType.TOKEN_TAG in word.sub_categories
334
- else None,
335
- word.get_sub_category(WordType.TOKEN_CLASS).category_id
336
- if WordType.TOKEN_CLASS in word.sub_categories
337
- else None,
338
- word.get_sub_category(WordType.TOKEN_TAG).category_id
339
- if WordType.TOKEN_TAG in word.sub_categories
340
- else None,
341
- )
342
- for word in words
343
- ]
344
- ))
322
+ ) = map(
323
+ list,
324
+ zip(
325
+ *[
326
+ (
327
+ word.characters,
328
+ word.annotation_id,
329
+ word.token_class,
330
+ word.get_sub_category(WordType.TOKEN_CLASS).annotation_id
331
+ if WordType.TOKEN_CLASS in word.sub_categories
332
+ else None,
333
+ word.token_tag,
334
+ word.get_sub_category(WordType.TOKEN_TAG).annotation_id
335
+ if WordType.TOKEN_TAG in word.sub_categories
336
+ else None,
337
+ word.get_sub_category(WordType.TOKEN_CLASS).category_id
338
+ if WordType.TOKEN_CLASS in word.sub_categories
339
+ else None,
340
+ word.get_sub_category(WordType.TOKEN_TAG).category_id
341
+ if WordType.TOKEN_TAG in word.sub_categories
342
+ else None,
343
+ )
344
+ for word in words
345
+ ]
346
+ ),
347
+ )
345
348
  else:
346
349
  (
347
350
  characters,
@@ -364,18 +367,17 @@ class Layout(ImageAnnotationBaseView):
364
367
  )
365
368
 
366
369
  return Text_(
367
- text=" ".join(characters), # type: ignore
368
- words=characters, # type: ignore
369
- ann_ids=ann_ids, # type: ignore
370
- token_classes=token_classes, # type: ignore
371
- token_class_ann_ids=token_class_ann_ids, # type: ignore
372
- token_tags=token_tags, # type: ignore
373
- token_tag_ann_ids=token_tag_ann_ids, # type: ignore
374
- token_class_ids=token_classes_ids, # type: ignore
375
- token_tag_ids=token_tag_ids, # type: ignore
370
+ text=" ".join(characters), # type: ignore
371
+ words=characters, # type: ignore
372
+ ann_ids=ann_ids, # type: ignore
373
+ token_classes=token_classes, # type: ignore
374
+ token_class_ann_ids=token_class_ann_ids, # type: ignore
375
+ token_tags=token_tags, # type: ignore
376
+ token_tag_ann_ids=token_tag_ann_ids, # type: ignore
377
+ token_class_ids=token_classes_ids, # type: ignore
378
+ token_tag_ids=token_tag_ids, # type: ignore
376
379
  )
377
380
 
378
-
379
381
  def get_attribute_names(self) -> set[str]:
380
382
  attr_names = (
381
383
  {"words", "text"}
@@ -464,9 +466,9 @@ class Table(Layout):
464
466
  A list of a table cells.
465
467
  """
466
468
  cell_anns: list[Cell] = []
467
- for row_number in range(1, self.number_of_rows + 1): # type: ignore
468
- cell_anns.extend(self.row(row_number)) # type: ignore
469
-
469
+ if self.number_of_rows:
470
+ for row_number in range(1, self.number_of_rows + 1): # type: ignore
471
+ cell_anns.extend(self.row(row_number)) # type: ignore
470
472
  return cell_anns
471
473
 
472
474
  @property
@@ -731,7 +733,6 @@ class Table(Layout):
731
733
  token_tag_ids=token_tag_ids,
732
734
  )
733
735
 
734
-
735
736
  @property
736
737
  def words(self) -> list[ImageAnnotationBaseView]:
737
738
  """
@@ -1175,7 +1176,6 @@ class Page(Image):
1175
1176
  token_tag_ids=token_tag_ann_ids,
1176
1177
  )
1177
1178
 
1178
-
1179
1179
  def get_layout_context(self, annotation_id: str, context_size: int = 3) -> list[ImageAnnotationBaseView]:
1180
1180
  """
1181
1181
  For a given `annotation_id` get a list of `ImageAnnotation` that are nearby in terms of `reading_order`.
@@ -26,6 +26,7 @@ from .doctrocr import *
26
26
  from .fastlang import *
27
27
  from .hfdetr import *
28
28
  from .hflayoutlm import *
29
+ from .hflm import *
29
30
  from .model import *
30
31
  from .pdftext import *
31
32
  from .tessocr import *
@@ -91,7 +91,7 @@ def d2_predict_image(
91
91
  """
92
92
  height, width = np_img.shape[:2]
93
93
  resized_img = resizer.get_transform(np_img).apply_image(np_img)
94
- image = torch.as_tensor(resized_img.astype("float32").transpose(2, 0, 1))
94
+ image = torch.as_tensor(resized_img.astype(np.float32).transpose(2, 0, 1))
95
95
 
96
96
  with torch.no_grad():
97
97
  inputs = {"image": image, "height": height, "width": width}
@@ -36,7 +36,7 @@ from ..utils.types import PathLikeOrStr
36
36
  from .base import DetectionResult, LanguageDetector, ModelCategories
37
37
 
38
38
  with try_import() as import_guard:
39
- from fasttext import load_model # type: ignore
39
+ from fasttext import load_model # type: ignore # pylint: disable=E0401
40
40
 
41
41
 
42
42
  class FasttextLangDetectorMixin(LanguageDetector, ABC):
@@ -62,7 +62,7 @@ class FasttextLangDetectorMixin(LanguageDetector, ABC):
62
62
  Returns:
63
63
  `DetectionResult` filled with `text` and `score`
64
64
  """
65
- return DetectionResult(text=self.categories_orig[output[0][0]], score=output[1][0])
65
+ return DetectionResult(class_name=self.categories_orig[output[0][0]], score=output[1][0])
66
66
 
67
67
  @staticmethod
68
68
  def get_name(path_weights: PathLikeOrStr) -> str:
@@ -126,10 +126,13 @@ def get_tokenizer_from_model_class(model_class: str, use_xlm_tokenizer: bool) ->
126
126
  ("XLMRobertaForSequenceClassification", True): XLMRobertaTokenizerFast.from_pretrained(
127
127
  "FacebookAI/xlm-roberta-base"
128
128
  ),
129
+ ("XLMRobertaForTokenClassification", True): XLMRobertaTokenizerFast.from_pretrained(
130
+ "FacebookAI/xlm-roberta-base"
131
+ ),
129
132
  }[(model_class, use_xlm_tokenizer)]
130
133
 
131
134
 
132
- def predict_token_classes(
135
+ def predict_token_classes_from_layoutlm(
133
136
  uuids: list[list[str]],
134
137
  input_ids: torch.Tensor,
135
138
  attention_mask: torch.Tensor,
@@ -192,7 +195,7 @@ def predict_token_classes(
192
195
  return all_token_classes
193
196
 
194
197
 
195
- def predict_sequence_classes(
198
+ def predict_sequence_classes_from_layoutlm(
196
199
  input_ids: torch.Tensor,
197
200
  attention_mask: torch.Tensor,
198
201
  token_type_ids: torch.Tensor,
@@ -462,7 +465,7 @@ class HFLayoutLmTokenClassifier(HFLayoutLmTokenClassifierBase):
462
465
 
463
466
  ann_ids, _, input_ids, attention_mask, token_type_ids, boxes, tokens = self._validate_encodings(**encodings)
464
467
 
465
- results = predict_token_classes(
468
+ results = predict_token_classes_from_layoutlm(
466
469
  ann_ids, input_ids, attention_mask, token_type_ids, boxes, tokens, self.model, None
467
470
  )
468
471
 
@@ -586,7 +589,7 @@ class HFLayoutLmv2TokenClassifier(HFLayoutLmTokenClassifierBase):
586
589
  images = images.to(self.device)
587
590
  else:
588
591
  raise ValueError(f"images must be list but is {type(images)}")
589
- results = predict_token_classes(
592
+ results = predict_token_classes_from_layoutlm(
590
593
  ann_ids, input_ids, attention_mask, token_type_ids, boxes, tokens, self.model, images
591
594
  )
592
595
 
@@ -710,7 +713,7 @@ class HFLayoutLmv3TokenClassifier(HFLayoutLmTokenClassifierBase):
710
713
  images = images.to(self.device)
711
714
  else:
712
715
  raise ValueError(f"images must be list but is {type(images)}")
713
- results = predict_token_classes(
716
+ results = predict_token_classes_from_layoutlm(
714
717
  ann_ids, input_ids, attention_mask, token_type_ids, boxes, tokens, self.model, images
715
718
  )
716
719
 
@@ -909,7 +912,7 @@ class HFLayoutLmSequenceClassifier(HFLayoutLmSequenceClassifierBase):
909
912
  """
910
913
  input_ids, attention_mask, token_type_ids, boxes = self._validate_encodings(**encodings)
911
914
 
912
- result = predict_sequence_classes(
915
+ result = predict_sequence_classes_from_layoutlm(
913
916
  input_ids,
914
917
  attention_mask,
915
918
  token_type_ids,
@@ -1021,7 +1024,12 @@ class HFLayoutLmv2SequenceClassifier(HFLayoutLmSequenceClassifierBase):
1021
1024
  else:
1022
1025
  raise ValueError(f"images must be list but is {type(images)}")
1023
1026
 
1024
- result = predict_sequence_classes(input_ids, attention_mask, token_type_ids, boxes, self.model, images)
1027
+ result = predict_sequence_classes_from_layoutlm(input_ids,
1028
+ attention_mask,
1029
+ token_type_ids,
1030
+ boxes,
1031
+ self.model,
1032
+ images)
1025
1033
 
1026
1034
  result.class_id += 1
1027
1035
  result.class_name = self.categories.categories[result.class_id]
@@ -1115,7 +1123,12 @@ class HFLayoutLmv3SequenceClassifier(HFLayoutLmSequenceClassifierBase):
1115
1123
  else:
1116
1124
  raise ValueError(f"images must be list but is {type(images)}")
1117
1125
 
1118
- result = predict_sequence_classes(input_ids, attention_mask, token_type_ids, boxes, self.model, images)
1126
+ result = predict_sequence_classes_from_layoutlm(input_ids,
1127
+ attention_mask,
1128
+ token_type_ids,
1129
+ boxes,
1130
+ self.model,
1131
+ images)
1119
1132
 
1120
1133
  result.class_id += 1
1121
1134
  result.class_name = self.categories.categories[result.class_id]
@@ -1245,7 +1258,7 @@ class HFLiltTokenClassifier(HFLayoutLmTokenClassifierBase):
1245
1258
 
1246
1259
  ann_ids, _, input_ids, attention_mask, token_type_ids, boxes, tokens = self._validate_encodings(**encodings)
1247
1260
 
1248
- results = predict_token_classes(
1261
+ results = predict_token_classes_from_layoutlm(
1249
1262
  ann_ids, input_ids, attention_mask, token_type_ids, boxes, tokens, self.model, None
1250
1263
  )
1251
1264
 
@@ -1323,7 +1336,7 @@ class HFLiltSequenceClassifier(HFLayoutLmSequenceClassifierBase):
1323
1336
  def predict(self, **encodings: Union[list[list[str]], torch.Tensor]) -> SequenceClassResult:
1324
1337
  input_ids, attention_mask, token_type_ids, boxes = self._validate_encodings(**encodings)
1325
1338
 
1326
- result = predict_sequence_classes(
1339
+ result = predict_sequence_classes_from_layoutlm(
1327
1340
  input_ids,
1328
1341
  attention_mask,
1329
1342
  token_type_ids,