
"""simple docstring"""




from collections import defaultdict
from typing import Optional

from ..image_utils import load_image
from ..utils import (
    add_end_docstrings,
    is_torch_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_torch_available():
  import torch

  from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING

A__   :					str							=   logging.get_logger(__name__)


@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       def __init__(     self ,				**A_       )     ->	Any:





         """simple docstring"""




         super().__init__(**A_       )
         requires_backends(self ,				'''vision'''       )
         requires_backends(self ,				'''torch'''       )

         if self.framework != "pt":
           raise ValueError(f'''The {self.__class__} is only available in PyTorch.'''       )

         self.check_model_type(A_       )
       def 							lowercase_							(     self ,				**A_       )     ->	str:





         """simple docstring"""




         _lowercase:			Optional[int]       =     {}
         _lowercase:			Dict       =     {}
         _lowercase:			int       =     {}
         # preprocess args
         if "points_per_batch" in kwargs:
           _lowercase:			Any       =     kwargs['''points_per_batch''']
         if "points_per_crop" in kwargs:
           _lowercase:			Optional[Any]       =     kwargs['''points_per_crop''']
         if "crops_n_layers" in kwargs:
           _lowercase:			Optional[Any]       =     kwargs['''crops_n_layers''']
         if "crop_overlap_ratio" in kwargs:
           _lowercase:			Tuple       =     kwargs['''crop_overlap_ratio''']
         if "crop_n_points_downscale_factor" in kwargs:
           _lowercase:			Dict       =     kwargs['''crop_n_points_downscale_factor''']
         # postprocess args
         if "pred_iou_thresh" in kwargs:
           _lowercase:			str       =     kwargs['''pred_iou_thresh''']
         if "stability_score_offset" in kwargs:
           _lowercase:			List[str]       =     kwargs['''stability_score_offset''']
         if "mask_threshold" in kwargs:
           _lowercase:			Dict       =     kwargs['''mask_threshold''']
         if "stability_score_thresh" in kwargs:
           _lowercase:			List[Any]       =     kwargs['''stability_score_thresh''']
         if "crops_nms_thresh" in kwargs:
           _lowercase:			Optional[Any]       =     kwargs['''crops_nms_thresh''']
         if "output_rle_mask" in kwargs:
           _lowercase:			Union[str, Any]       =     kwargs['''output_rle_mask''']
         if "output_bboxes_mask" in kwargs:
           _lowercase:			Dict       =     kwargs['''output_bboxes_mask''']
         return preprocess_kwargs, forward_params, postprocess_kwargs
       def __call__(     self ,				A_ ,				*A_ ,				A_=None ,				A_=None ,				**A_       )     ->	Dict:





         """simple docstring"""




         return super().__call__(A_ ,				*A_ ,				num_workers=A_ ,				batch_size=A_ ,				**A_       )
       def 							lowercase_							(     self ,				A_ ,				A_=64 ,				A_ = 0 ,				A_ = 512 / 1500 ,				A_ = 32 ,				A_ = 1 ,				)     ->	Optional[int]:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     load_image(A_       )
         _lowercase:			Dict       =     self.image_processor.size['''longest_edge''']
         _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Dict       =     self.image_processor.generate_crop_boxes(
             A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )
         _lowercase:			str       =     self.image_processor(images=A_ ,				return_tensors='''pt'''       )

         with self.device_placement():
           if self.framework == "pt":
             _lowercase:			Tuple       =     self.get_inference_context()
             with inference_context():
               _lowercase:			str       =     self._ensure_tensor_on_device(A_ ,				device=self.device       )
               _lowercase:			Dict       =     self.model.get_image_embeddings(model_inputs.pop('''pixel_values'''       )       )
               _lowercase:			Union[str, Any]       =     image_embeddings

         _lowercase:			List[Any]       =     grid_points.shape[1]
         _lowercase:			List[Any]       =     points_per_batch if points_per_batch is not None else n_points

         if points_per_batch <= 0:
           raise ValueError(
               '''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. '''
               '''To return all points at once, set points_per_batch to None'''       )

         for i in range(0 ,				A_ ,				A_       ):
           _lowercase:			int       =     grid_points[:, i : i + points_per_batch, :, :]
           _lowercase:			Any       =     input_labels[:, i : i + points_per_batch]
           _lowercase:			Any       =     i == n_points - points_per_batch
           yield {
               "input_points": batched_points,
               "input_labels": labels,
               "input_boxes": crop_boxes,
               "is_last": is_last,
               **model_inputs,
           }
       def 							lowercase_							(     self ,				A_ ,				A_=0.88 ,				A_=0.95 ,				A_=0 ,				A_=1 ,				)     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     model_inputs.pop('''input_boxes'''       )
         _lowercase:			Dict       =     model_inputs.pop('''is_last'''       )
         _lowercase:			Tuple       =     model_inputs.pop('''original_sizes'''       ).tolist()
         _lowercase:			Union[str, Any]       =     model_inputs.pop('''reshaped_input_sizes'''       ).tolist()

         _lowercase:			Dict       =     self.model(**A_       )

         # post processing happens here in order to avoid CPU GPU copies of ALL the masks
         _lowercase:			List[str]       =     model_outputs['''pred_masks''']
         _lowercase:			str       =     self.image_processor.post_process_masks(
             A_ ,				A_ ,				A_ ,				A_ ,				binarize=A_       )
         _lowercase:			List[Any]       =     model_outputs['''iou_scores''']
         _lowercase ,				_lowercase ,				_lowercase:			Optional[Any]       =     self.image_processor.filter_masks(
             masks[0] ,				iou_scores[0] ,				original_sizes[0] ,				input_boxes[0] ,				A_ ,				A_ ,				A_ ,				A_ ,				)
         return {
             "masks": masks,
             "is_last": is_last,
             "boxes": boxes,
             "iou_scores": iou_scores,
         }



       def 							lowercase_							(     self ,				A_ ,				A_=False ,				A_=False ,				A_=0.7 ,				)     ->	List[Any]:





         """simple docstring"""




         _lowercase:			str       =     []
         _lowercase:			List[Any]       =     []
         _lowercase:			List[Any]       =     []
         for model_output in model_outputs:
           all_scores.append(model_output.pop('''iou_scores'''       )       )
           all_masks.extend(model_output.pop('''masks'''       )       )
           all_boxes.append(model_output.pop('''boxes'''       )       )

         _lowercase:			Optional[Any]       =     torch.cat(A_       )
         _lowercase:			Optional[int]       =     torch.cat(A_       )
         _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Any       =     self.image_processor.post_process_for_mask_generation(
             A_ ,				A_ ,				A_ ,				A_       )

         _lowercase:			Any       =     defaultdict(A_       )
         for output in model_outputs:
           for k, v in output.items():
             extra[k].append(A_       )

         _lowercase:			Dict       =     {}
         if output_rle_mask:
           _lowercase:			Optional[Any]       =     rle_mask

         if output_bboxes_mask:
           _lowercase:			Dict       =     bounding_boxes

         return {"masks": output_masks, "scores": iou_scores, **optional, **extra}


"""simple docstring"""




import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


A__   :					List[Any]							=   datasets.utils.logging.get_logger(__name__)


@dataclass
class 			__magic_name__       (       datasets.BuilderConfig ):
       UpperCamelCase_   =		None
       UpperCamelCase_   =		"utf-8"
       UpperCamelCase_   =		None
       UpperCamelCase_   =		None
       UpperCamelCase_   =		True  # deprecated
       UpperCamelCase_   =		None  # deprecated
       UpperCamelCase_   =		10 << 20  # 10MB
       UpperCamelCase_   =		None


class 			__magic_name__       (       datasets.ArrowBasedBuilder ):
       UpperCamelCase_   =		JsonConfig
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         if self.config.block_size is not None:
           logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''       )
           _lowercase:			List[str]       =     self.config.block_size
         if self.config.use_threads is not True:
           logger.warning(
               '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'''       )
         if self.config.newlines_in_values is not None:
           raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported'''       )
         return datasets.DatasetInfo(features=self.config.features       )
       def 							lowercase_							(     self ,				A_       )     ->	Any:





         """simple docstring"""




         if not self.config.data_files:
           raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''       )
         _lowercase:			int       =     dl_manager.download_and_extract(self.config.data_files       )
         if isinstance(A_ ,				(str, list, tuple)       ):
           _lowercase:			Tuple       =     data_files
           if isinstance(A_ ,				A_       ):
             _lowercase:			Optional[Any]       =     [files]
           _lowercase:			Dict       =     [dl_manager.iter_files(A_       ) for file in files]
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,				gen_kwargs={'''files''': files}       )]
         _lowercase:			str       =     []
         for split_name, files in data_files.items():
           if isinstance(A_ ,				A_       ):
             _lowercase:			Optional[Any]       =     [files]
           _lowercase:			str       =     [dl_manager.iter_files(A_       ) for file in files]
           splits.append(datasets.SplitGenerator(name=A_ ,				gen_kwargs={'''files''': files}       )       )
         return splits
       def 							lowercase_							(     self ,				A_       )     ->	pa.Table:





         """simple docstring"""




         if self.config.features is not None:
           # adding missing columns
           for column_name in set(self.config.features       ) - set(pa_table.column_names       ):
             _lowercase:			Any       =     self.config.features.arrow_schema.field(A_       ).type
             _lowercase:			Optional[Any]       =     pa_table.append_column(A_ ,				pa.array([None] * len(A_       ) ,				type=A_       )       )
           # more expensive cast to support nested structures with keys in a different order
           # allows str <-> int/float or str to Audio for example
           _lowercase:			Optional[int]       =     table_cast(A_ ,				self.config.features.arrow_schema       )
         return pa_table



       def 							lowercase_							(     self ,				A_       )     ->	str:





         """simple docstring"""




         for file_idx, file in enumerate(itertools.chain.from_iterable(A_       )       ):
           # If the file is one json object and if we need to look at the list of items in one specific field
           if self.config.field is not None:
             with open(A_ ,				encoding=self.config.encoding ,				errors=self.config.encoding_errors       ) as f:
               _lowercase:			Optional[int]       =     json.load(A_       )

             # We keep only the field we are interested in
             _lowercase:			str       =     dataset[self.config.field]

             # We accept two format: a list of dicts or a dict of lists
             if isinstance(A_ ,				(list, tuple)       ):
               _lowercase:			Dict       =     set().union(*[row.keys() for row in dataset]       )
               _lowercase:			List[str]       =     {col: [row.get(A_       ) for row in dataset] for col in keys}
             else:
               _lowercase:			Dict       =     dataset
             _lowercase:			Union[str, Any]       =     pa.Table.from_pydict(A_       )
             yield file_idx, self._cast_table(A_       )

           # If the file has one json object per line
           else:
             with open(A_ ,				'''rb'''       ) as f:
               _lowercase:			int       =     0
               # Use block_size equal to the chunk size divided by 32 to leverage multithreading
               # Set a default minimum value of 16kB if the chunk size is really small
               _lowercase:			Optional[int]       =     max(self.config.chunksize // 32 ,				16 << 10       )
               _lowercase:			List[Any]       =     (
                   self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
               )
               while True:
                 _lowercase:			Union[str, Any]       =     f.read(self.config.chunksize       )
                 if not batch:
                   break
                 # Finish current line
                 try:
                   batch += f.readline()
                 except (AttributeError, io.UnsupportedOperation):
                   batch += readline(A_       )
                 # PyArrow only accepts utf-8 encoded bytes
                 if self.config.encoding != "utf-8":
                   _lowercase:			Any       =     batch.decode(self.config.encoding ,				errors=A_       ).encode('''utf-8'''       )
                 try:
                   while True:
                     try:
                       _lowercase:			Optional[int]       =     paj.read_json(
                           io.BytesIO(A_       ) ,				read_options=paj.ReadOptions(block_size=A_       )       )
                       break
                     except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                       if (
                           isinstance(A_ ,				pa.ArrowInvalid       )
                           and "straddling" not in str(A_       )
                           or block_size > len(A_       )
                       ):
                         raise
                       else:
                         # Increase the block size in case it was too small.
                         # The block size will be reset for the next file.
                         logger.debug(
                             f'''Batch of {len(A_       )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.'''       )
                         block_size *= 2
                 except pa.ArrowInvalid as e:
                   try:
                     with open(
                         A_ ,				encoding=self.config.encoding ,				errors=self.config.encoding_errors       ) as f:
                       _lowercase:			Optional[Any]       =     json.load(A_       )
                   except json.JSONDecodeError:
                     logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                     raise e
                   # If possible, parse the file as a list of json objects and exit the loop
                   if isinstance(A_ ,				A_       ):  # list is the only sequence type supported in JSON
                     try:
                       _lowercase:			Optional[int]       =     set().union(*[row.keys() for row in dataset]       )
                       _lowercase:			Tuple       =     {col: [row.get(A_       ) for row in dataset] for col in keys}
                       _lowercase:			str       =     pa.Table.from_pydict(A_       )
                     except (pa.ArrowInvalid, AttributeError) as e:
                       logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                       raise ValueError(f'''Not able to read records in the JSON file at {file}.'''       ) from None
                     yield file_idx, self._cast_table(A_       )
                     break
                   else:
                     logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                     raise ValueError(
                         f'''Not able to read records in the JSON file at {file}. '''
                         f'''You should probably indicate the field of the JSON file containing your records. '''
                         f'''This JSON file contain the following fields: {str(list(dataset.keys()       )       )}. '''
                         f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. '''       ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                 yield (file_idx, batch_idx), self._cast_table(A_       )
                 batch_idx += 1
