# -*- coding: utf-8 -*-
# File: __init__.py

"""
Init file for deepdoctection package. This file is used to import all submodules and to set some environment variables
"""

import importlib.util

# Before doing anything else, check if the .env file exists and load it
if importlib.util.find_spec("dotenv") is not None:
    from dotenv import load_dotenv

    load_dotenv()


# pylint: disable=wrong-import-position
import sys
from typing import TYPE_CHECKING

from .utils.env_info import auto_select_pdf_render_framework, collect_env_info
from .utils.file_utils import _LazyModule, get_tf_version, pytorch_available, tf_available
from .utils.logger import LoggingRecord, logger

# pylint: enable=wrong-import-position

__version__ = "0.38"

_IMPORT_STRUCTURE = {
    "analyzer": ["config_sanity_checks", "get_dd_analyzer", "ServiceFactory"],
    "configs": [],
    "dataflow": [
        "DataFlowTerminated",
        "DataFlowResetStateNotCalled",
        "DataFlowReentrantGuard",
        "DataFlow",
        "RNGDataFlow",
        "ProxyDataFlow",
        "TestDataSpeed",
        "FlattenData",
        "MapData",
        "MapDataComponent",
        "RepeatedData",
        "ConcatData",
        "JoinData",
        "BatchData",
        "CacheData",
        "CustomDataFromList",
        "CustomDataFromIterable",
        "SerializerJsonlines",
        "SerializerTabsepFiles",
        "SerializerFiles",
        "CocoParser",
        "SerializerCoco",
        "SerializerPdfDoc",
        "MultiThreadMapData",
        "MultiProcessMapData",
        "DataFromList",
        "DataFromIterable",
        "FakeData",
        "PickleSerializer",
        "MeanFromDataFlow",
        "StdFromDataFlow",
    ],
    "datapoint": [
        "ann_from_dict",
        "AnnotationMap",
        "Annotation",
        "CategoryAnnotation",
        "ImageAnnotation",
        "SummaryAnnotation",
        "ContainerAnnotation",
        "coco_iou",
        "area",
        "intersection",
        "np_iou",
        "iou",
        "BoundingBoxError",
        "BoundingBox",
        "intersection_box",
        "crop_box_from_image",
        "local_to_global_coords",
        "global_to_local_coords",
        "merge_boxes",
        "rescale_coords",
        "intersection_boxes",
        "convert_b64_to_np_array",
        "convert_np_array_to_b64",
        "convert_np_array_to_b64_b",
        "convert_bytes_to_np_array",
        "convert_pdf_bytes_to_np_array_v2",
        "box_to_point4",
        "point4_to_box",
        "as_dict",
        "ImageAnnotationBaseView",
        "Image",
        "Word",
        "Layout",
        "Cell",
        "Table",
        "Page",
    ],
    "datasets": [
        "DatasetAdapter",
        "DatasetBase",
        "MergeDataset",
        "CustomDataset",
        "DataFlowBaseBuilder",
        "DatasetInfo",
        "DatasetCategories",
        "get_merged_categories",
        "dataset_registry",
        "get_dataset",
        "print_dataset_infos",
        "dataflow_to_json",
    ],
    "datasets.instances": [
        "DocLayNet",
        "DocLayNetSeq",
        "Fintabnet",
        "Funsd",
        "IIITar13K",
        "LayoutTest",
        "Publaynet",
        "Pubtables1MDet",
        "Pubtables1MStruct",
        "Pubtabnet",
        "Rvlcdip",
        "Xfund",
    ],
    "datasets.instances.xsl": [],
    "eval": [
        "AccuracyMetric",
        "ConfusionMetric",
        "PrecisionMetric",
        "RecallMetric",
        "F1Metric",
        "PrecisionMetricMicro",
        "RecallMetricMicro",
        "F1MetricMicro",
        "MetricBase",
        "CocoMetric",
        "Evaluator",
        "metric_registry",
        "get_metric",
        "TableTree",
        "CustomConfig",
        "TEDS",
        "TedsMetric",
        "EvalCallback",
    ],
    "extern": [
        "ModelCategories",
        "NerModelCategories",
        "PredictorBase",
        "DetectionResult",
        "ObjectDetector",
        "PdfMiner",
        "TextRecognizer",
        "TokenClassResult",
        "SequenceClassResult",
        "LMTokenClassifier",
        "LMSequenceClassifier",
        "LanguageDetector",
        "ImageTransformer",
        "InferenceResize",
        "D2FrcnnDetector",
        "D2FrcnnTracingDetector",
        "Jdeskewer",
        "DoctrTextlineDetector",
        "DoctrTextRecognizer",
        "DocTrRotationTransformer",
        "FasttextLangDetector",
        "HFDetrDerivedDetector",
        "get_tokenizer_from_architecture",
        "HFLayoutLmTokenClassifierBase",
        "HFLayoutLmTokenClassifier",
        "HFLayoutLmv2TokenClassifier",
        "HFLayoutLmv3TokenClassifier",
        "HFLayoutLmSequenceClassifier",
        "HFLayoutLmv2SequenceClassifier",
        "HFLayoutLmv3SequenceClassifier",
        "HFLiltTokenClassifier",
        "HFLiltSequenceClassifier",
        "HFLmSequenceClassifier",
        "ModelProfile",
        "ModelCatalog",
        "print_model_infos",
        "ModelDownloadManager",
        "PdfPlumberTextDetector",
        "Pdfmium2TextDetector",
        "TesseractOcrDetector",
        "TesseractRotationTransformer",
        "TextractOcrDetector",
        "TPFrcnnDetector",
    ],
    "extern.pt": ["set_torch_auto_device", "get_num_gpu", "batched_nms"],
    "extern.tp": ["disable_tfv2", "ModelDescWithConfig", "TensorpackPredictor"],
    "extern.tp.tpfrcnn": ["CustomResize", "anchors_and_labels", "augment"],
    "extern.tp.tpfrcnn.utils": ["area", "pairwise_intersection", "pairwise_iou"],
    "extern.tp.tpfrcnn.config": ["model_frcnn_config", "train_frcnn_config"],
    "extern.tp.tpfrcnn.modeling": ["ResNetFPNModel"],
    "mapper": [
        "cat_to_sub_cat",
        "re_assign_cat_ids",
        "filter_cat",
        "filter_summary",
        "image_to_cat_id",
        "remove_cats",
        "add_summary",
        "coco_to_image",
        "image_to_coco",
        "image_to_d2_frcnn_training",
        "pt_nms_image_annotations",
        "to_wandb_image",
        "image_to_hf_detr_training",
        "DetrDataCollator",
        "image_to_layoutlm",
        "image_to_raw_layoutlm_features",
        "raw_features_to_layoutlm_features",
        "LayoutLMDataCollator",
        "image_to_layoutlm_features",
        "DataCollator",
        "LayoutLMFeatures",
        "MappingContextManager",
        "DefaultMapper",
        "maybe_get_fake_score",
        "LabelSummarizer",
        "curry",
        "match_anns_by_intersection",
        "match_anns_by_distance",
        "to_image",
        "maybe_load_image",
        "maybe_remove_image",
        "maybe_remove_image_from_category",
        "image_ann_to_image",
        "maybe_ann_to_sub_image",
        "xml_to_dict",
        "to_page",
        "page_dict_to_page",
        "pascal_voc_dict_to_image",
        "prodigy_to_image",
        "image_to_prodigy",
        "pub_to_image_uncur",
        "pub_to_image",
        "image_to_tp_frcnn_training",
        "tf_nms_image_annotations",
        "xfund_to_image",
    ],
    "pipe": [
        "DatapointManager",
        "PipelineComponent",
        "PredictorPipelineComponent",
        "LanguageModelPipelineComponent",
        "ImageTransformPipelineComponent",
        "Pipeline",
        "DetectResultGenerator",
        "SubImageLayoutService",
        "ImageCroppingService",
        "IntersectionMatcher",
        "NeighbourMatcher",
        "MatchingService",
        "PageParsingService",
        "AnnotationNmsService",
        "MultiThreadPipelineComponent",
        "DoctectionPipe",
        "LanguageDetectionService",
        "ImageLayoutService",
        "LMTokenClassifierService",
        "LMSequenceClassifierService",
        "OrderGenerator",
        "TextLineGenerator",
        "TextLineService",
        "TextOrderService",
        "TableSegmentationRefinementService",
        "generate_html_string",
        "pipeline_component_registry",
        "TableSegmentationService",
        "PubtablesSegmentationService",
        "SegmentationResult",
        "TextExtractionService",
        "SimpleTransformService",
    ],
    "train": [
        "D2Trainer",
        "train_d2_faster_rcnn",
        "LayoutLMTrainer",
        "train_hf_layoutlm",
        "train_faster_rcnn",
        "DetrDerivedTrainer",
        "train_hf_detr",
    ],
    "utils": [
        "timeout_manager",
        "save_tmp_file",
        "timed_operation",
        "collect_env_info",
        "auto_select_viz_library",
        "auto_select_pdf_render_framework",
        "get_tensorflow_requirement",
        "tf_addons_available",
        "get_tf_addons_requirements",
        "tensorpack_available",
        "get_tensorpack_requirement",
        "pytorch_available",
        "get_pytorch_requirement",
        "lxml_available",
        "get_lxml_requirement",
        "apted_available",
        "get_apted_requirement",
        "distance_available",
        "get_distance_requirement",
        "transformers_available",
        "get_transformers_requirement",
        "detectron2_available",
        "get_detectron2_requirement",
        "tesseract_available",
        "set_tesseract_path",
        "get_tesseract_version",
        "get_tesseract_requirement",
        "pdf_to_ppm_available",
        "pdf_to_cairo_available",
        "get_poppler_requirement",
        "pdfplumber_available",
        "get_pdfplumber_requirement",
        "cocotools_available",
        "get_cocotools_requirement",
        "scipy_available",
        "sklearn_available",
        "get_sklearn_requirement",
        "qpdf_available",
        "boto3_available",
        "get_boto3_requirement",
        "aws_available",
        "get_aws_requirement",
        "doctr_available",
        "get_doctr_requirement",
        "fasttext_available",
        "get_fasttext_requirement",
        "wandb_available",
        "get_wandb_requirement",
        "opencv_available",
        "get_opencv_requirement",
        "pillow_available",
        "get_pillow_requirement",
        "spacy_available",
        "get_spacy_requirement",
        "load_image_from_file",
        "load_bytes_from_pdf_file",
        "get_load_image_func",
        "maybe_path_or_pdf",
        "download",
        "mkdir_p",
        "is_file_extension",
        "load_json",
        "FileExtensionError",
        "sub_path",
        "get_package_path",
        "get_configs_dir_path",
        "get_weights_dir_path",
        "get_dataset_dir_path",
        "maybe_copy_config_to_cache",
        "is_uuid_like",
        "get_uuid_from_str",
        "get_uuid",
        "logger",
        "set_logger_dir",
        "auto_set_dir",
        "get_logger_dir",
        "AttrDict",
        "set_config_by_yaml",
        "save_config_to_yaml",
        "config_to_cli_str",
        "decrypt_pdf_document",
        "decrypt_pdf_document_from_bytes",
        "get_pdf_file_reader",
        "get_pdf_file_writer",
        "PDFStreamer",
        "pdf_to_np_array",
        "split_pdf",
        "ObjectTypes",
        "TypeOrStr",
        "object_types_registry",
        "DefaultType",
        "PageType",
        "SummaryType",
        "DocumentType",
        "LayoutType",
        "TableType",
        "CellType",
        "WordType",
        "TokenClasses",
        "BioTag",
        "TokenClassWithTag",
        "Relationships",
        "Languages",
        "DatasetType",
        "update_all_types_dict",
        "get_type",
        "get_tqdm",
        "get_tqdm_default_kwargs",
        "ResizeTransform",
        "InferenceResize",
        "normalize_image",
        "pad_image",
        "PadTransform",
        "delete_keys_from_dict",
        "split_string",
        "string_to_dict",
        "to_bool",
        "call_only_once",
        "get_rng",
        "FileExtensionError",
        "is_file_extension",
        "draw_text",
        "draw_boxes",
        "interactive_imshow",
        "viz_handler",
    ],
}

# Setting some environment variables so that standard functions can be invoked with available hardware
env_info = collect_env_info()
logger.debug(LoggingRecord(msg=env_info))
auto_select_pdf_render_framework()

# Direct imports for type-checking
if TYPE_CHECKING:
    from .analyzer import *
    from .dataflow import *
    from .datapoint import *
    from .datasets import *  # type: ignore
    from .eval import *
    from .extern import *  # type: ignore
    from .mapper import *  # type: ignore
    from .pipe import *
    from .train import *
    from .utils import *

else:
    sys.modules[__name__] = _LazyModule(
        __name__,
        globals()["__file__"],
        _IMPORT_STRUCTURE,
        module_spec=__spec__,
        extra_objects={"__version__": __version__},
    )
