
'''simple docstring'''

import argparse
import pathlib
from pathlib import Path
from tempfile import TemporaryDirectory

import esm as esm_module
import torch
from esm.esmfold.va.misc import batch_encode_sequences as esmfold_encode_sequences
from esm.esmfold.va.pretrained import esmfold_va

from transformers.models.esm.configuration_esm import EsmConfig, EsmFoldConfig
from transformers.models.esm.modeling_esm import (
    EsmForMaskedLM,
    EsmForSequenceClassification,
    EsmIntermediate,
    EsmLayer,
    EsmOutput,
    EsmSelfAttention,
    EsmSelfOutput,
)
from transformers.models.esm.modeling_esmfold import EsmForProteinFolding
from transformers.models.esm.tokenization_esm import EsmTokenizer
from transformers.utils import logging


logging.set_verbosity_info()
UpperCamelCase_     			=       logging.get_logger(__name__)

UpperCamelCase_     			=       [
    (
        """protein1""",
        """MNGTEGPNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQHKKLRTPLNYILLNLAVADLFMVLGGFTSTLYTSLHGYFVFGPTGCNLEGFFATLGGEIALWSLVVLAIERYVVVCKPMSNFRFGENHAIMGVAFTWVMALACAAPPLAGWSRYIPEGLQCSCGIDYYTLKPEVNNESFVIYMFVVHFTIPMIIIFFCYGQLVFTVKEAAAQQQESATTQKAEKEVTRMVIIMVIAFLICWVPYASVAFYIFTHQGSNFGPIFMTIPAFFAKSAAIYNPVIYIMMNKQFRNCMLTTICCGKNPLGDDEASATVSKTETSQVAPA""",
    ),
    ("""protein2""", """MKTVRQERLKSIVRILERSKEPVSGAQLAEELSVSRQVIVQDIAYLRSLGYNIVATPRGYVLA"""),
    ("""protein3""", """MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLAGG"""),
    ("""protein4""", """MKTVRQERLKSI<mask>RILERSKEPVSGAQLAEELS<mask>SRQVIVQDIAYLRSLGYN<mask>VATPRGYVLA"""),
]

UpperCamelCase_     			=       {
    """esm1b_t33_650M_UR50S""": esm_module.pretrained.esm1b_t33_650M_UR50S,
    """esm1v_t33_650M_UR90S_1""": esm_module.pretrained.esm1v_t33_650M_UR90S_1,
    """esm1v_t33_650M_UR90S_2""": esm_module.pretrained.esm1v_t33_650M_UR90S_2,
    """esm1v_t33_650M_UR90S_3""": esm_module.pretrained.esm1v_t33_650M_UR90S_3,
    """esm1v_t33_650M_UR90S_4""": esm_module.pretrained.esm1v_t33_650M_UR90S_4,
    """esm1v_t33_650M_UR90S_5""": esm_module.pretrained.esm1v_t33_650M_UR90S_5,
    """esm2_t48_15B_UR50D""": esm_module.pretrained.esm2_t48_15B_UR50D,
    """esm2_t36_3B_UR50D""": esm_module.pretrained.esm2_t36_3B_UR50D,
    """esm2_t33_650M_UR50D""": esm_module.pretrained.esm2_t33_650M_UR50D,
    """esm2_t30_150M_UR50D""": esm_module.pretrained.esm2_t30_150M_UR50D,
    """esm2_t12_35M_UR50D""": esm_module.pretrained.esm2_t12_35M_UR50D,
    """esm2_t6_8M_UR50D""": esm_module.pretrained.esm2_t6_8M_UR50D,
    """esmfold_v1""": esmfold_va,
}

UpperCamelCase_     			=       list("""ARNDCQEGHILKMFPSTWYV""")

UpperCamelCase_     			=       restypes + ["""X"""]
UpperCamelCase_     			=       restypes_with_x + ["""<pad>""", """<mask>""", """<cls>""", """<sep>""", """<eos>"""]


def 	_UpperCAmelCase				(  )    ->						Dict:
  with TemporaryDirectory() as tempdir:
    _lowerCAmelCase       :  Union[str, Any]   				=					"""\n""".join(_lowerCamelCase		)
    _lowerCAmelCase       :  str   				=					Path(_lowerCamelCase		) / """vocab.txt"""
    vocab_file.write_text(_lowerCamelCase		)
    _lowerCAmelCase       :  List[str]   				=					EsmTokenizer(vocab_file=str(_lowerCamelCase		)		)
  _lowerCAmelCase       :  Tuple   				=					0  # Overlaps with 'A' but that seems to be what they want
  return hf_tokenizer


def 	_UpperCAmelCase				(  _lowerCamelCase						:       List[Any]  ,      _lowerCamelCase						:       Any		)    ->						Any:
  _lowerCAmelCase       :  Dict   				=					our_module.load_state_dict(original_module.state_dict()		)
  if status.missing_keys:
    raise ValueError(f'Missing keys: {status.missing_keys}'		)
  if status.unexpected_keys:
    raise ValueError(f'Unexpected keys: {status.unexpected_keys}'		)


def 	_UpperCAmelCase				(  _lowerCamelCase						:       str  ,      _lowerCamelCase						:       str  ,      _lowerCamelCase						:       bool  ,      _lowerCamelCase						:       str  ,      _lowerCamelCase						:       str		)    ->						Optional[Any]:
  if model.startswith("""esmfold"""		):
    _lowerCAmelCase       :  List[str]   				=					MODEL_MAPPING[model]()
  else:
    _lowerCAmelCase       :  List[Any]   				=					MODEL_MAPPING[model]()
  esm.eval()  # disable dropout

  if model.startswith("""esmfold"""		):
    _lowerCAmelCase       :  Optional[int]   				=					esm.esm.embed_dim
    _lowerCAmelCase       :  Any   				=					esm.esm.num_layers
    _lowerCAmelCase       :  Tuple   				=					esm.esm.attention_heads
    _lowerCAmelCase       :  Tuple   				=					4 * embed_dim
    _lowerCAmelCase       :  Optional[Any]   				=					esm.esm.token_dropout
    _lowerCAmelCase       :  Tuple   				=					False  # This code path does not exist in ESM-2
    _lowerCAmelCase       :  List[Any]   				=					"""rotary"""
    _lowerCAmelCase       :  List[str]   				=					True
    _lowerCAmelCase       :  Tuple   				=					EsmFoldConfig()
    for key, val in esm.cfg.items():
      if hasattr(_lowerCamelCase  ,      _lowerCamelCase		) and key != "trunk":
        setattr(_lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase		)
    for key, val in esm.cfg.trunk.items():
      if hasattr(esmfold_config.trunk  ,      _lowerCamelCase		) and key != "structure_module":
        setattr(esmfold_config.trunk  ,      _lowerCamelCase  ,      _lowerCamelCase		)
    for key, val in esm.cfg.trunk.structure_module.items():
      if hasattr(esmfold_config.trunk.structure_module  ,      _lowerCamelCase		):
        setattr(esmfold_config.trunk.structure_module  ,      _lowerCamelCase  ,      _lowerCamelCase		)
  elif hasattr(_lowerCamelCase  ,      """args"""		):
    # Indicates an ESM-1b or ESM-1v model
    _lowerCAmelCase       :  Optional[Any]   				=					esm.args.embed_dim
    _lowerCAmelCase       :  Optional[int]   				=					esm.args.layers
    _lowerCAmelCase       :  Optional[Any]   				=					esm.args.attention_heads
    _lowerCAmelCase       :  Dict   				=					esm.args.ffn_embed_dim
    _lowerCAmelCase       :  List[Any]   				=					esm.args.token_dropout
    _lowerCAmelCase       :  int   				=					True if esm.emb_layer_norm_before else False
    _lowerCAmelCase       :  Dict   				=					"""absolute"""
    _lowerCAmelCase       :  Optional[Any]   				=					False
    _lowerCAmelCase       :  Optional[int]   				=					None
  else:
    # Indicates an ESM-2 model
    _lowerCAmelCase       :  int   				=					esm.embed_dim
    _lowerCAmelCase       :  str   				=					esm.num_layers
    _lowerCAmelCase       :  Dict   				=					esm.attention_heads
    _lowerCAmelCase       :  Union[str, Any]   				=					4 * embed_dim  # This is hardcoded in ESM-2
    _lowerCAmelCase       :  int   				=					esm.token_dropout
    _lowerCAmelCase       :  List[Any]   				=					False  # This code path does not exist in ESM-2
    _lowerCAmelCase       :  Any   				=					"""rotary"""
    _lowerCAmelCase       :  Any   				=					False
    _lowerCAmelCase       :  Optional[Any]   				=					None

  if is_folding_model:
    _lowerCAmelCase       :  str   				=					esm.esm.alphabet
  _lowerCAmelCase       :  int   				=					tuple(alphabet.all_toks		)
  _lowerCAmelCase       :  Union[str, Any]   				=					alphabet.mask_idx
  _lowerCAmelCase       :  Optional[Any]   				=					alphabet.padding_idx

  if is_folding_model:
    _lowerCAmelCase       :  int   				=					esm.esm
  else:
    _lowerCAmelCase       :  Tuple   				=					esm

  _lowerCAmelCase       :  Optional[Any]   				=					EsmConfig(
      vocab_size=original_esm_model.embed_tokens.num_embeddings  ,      mask_token_id=_lowerCamelCase  ,      hidden_size=_lowerCamelCase  ,      num_hidden_layers=_lowerCamelCase  ,      num_attention_heads=_lowerCamelCase  ,      intermediate_size=_lowerCamelCase  ,      max_position_embeddings=10_26  ,      layer_norm_eps=1e-5  ,      attention_probs_dropout_prob=0.0  ,      hidden_dropout_prob=0.0  ,      pad_token_id=_lowerCamelCase  ,      emb_layer_norm_before=_lowerCamelCase  ,      token_dropout=_lowerCamelCase  ,      position_embedding_type=_lowerCamelCase  ,      is_folding_model=_lowerCamelCase  ,      esmfold_config=_lowerCamelCase  ,      vocab_list=_lowerCamelCase  ,      )
  if classification_head:
    _lowerCAmelCase       :  Union[str, Any]   				=					esm.classification_heads["""mnli"""].out_proj.weight.shape[0]
  print("""Our ESM config:"""  ,      _lowerCamelCase		)

  if model.startswith("""esmfold"""		):
    _lowerCAmelCase       :  Optional[int]   				=					EsmForProteinFolding
  elif classification_head:
    _lowerCAmelCase       :  List[Any]   				=					EsmForSequenceClassification
  else:
    _lowerCAmelCase       :  int   				=					EsmForMaskedLM
  _lowerCAmelCase       :  Union[str, Any]   				=					model_class(_lowerCamelCase		)
  model.eval()

  # Now let's copy all the weights.
  # Embeddings
  _lowerCAmelCase       :  int   				=					original_esm_model.embed_tokens.weight
  if position_embedding_type == "absolute":
    _lowerCAmelCase       :  Any   				=					original_esm_model.embed_positions.weight

  if config.emb_layer_norm_before:
    _lowerCAmelCase       :  List[Any]   				=					original_esm_model.emb_layer_norm_before.weight
    _lowerCAmelCase       :  str   				=					original_esm_model.emb_layer_norm_before.bias

  _lowerCAmelCase       :  str   				=					original_esm_model.emb_layer_norm_after.weight
  _lowerCAmelCase       :  Optional[int]   				=					original_esm_model.emb_layer_norm_after.bias

  for i in range(config.num_hidden_layers		):
    # Encoder: start of layer
    _lowerCAmelCase       :  EsmLayer   				=					model.esm.encoder.layer[i]
    # esm_layer: TransformerSentenceEncoderLayer = original_esm_model.layers[i]
    _lowerCAmelCase       :  Tuple   				=					original_esm_model.layers[i]

    # self attention
    _lowerCAmelCase       :  EsmSelfAttention   				=					layer.attention.self
    assert (
        esm_layer.self_attn.k_proj.weight.data.shape
        == esm_layer.self_attn.q_proj.weight.data.shape
        == esm_layer.self_attn.v_proj.weight.data.shape
        == torch.Size((config.hidden_size, config.hidden_size)		)
    )

    _lowerCAmelCase       :  List[str]   				=					esm_layer.self_attn.q_proj.weight
    _lowerCAmelCase       :  int   				=					esm_layer.self_attn.q_proj.bias
    _lowerCAmelCase       :  int   				=					esm_layer.self_attn.k_proj.weight
    _lowerCAmelCase       :  List[str]   				=					esm_layer.self_attn.k_proj.bias
    _lowerCAmelCase       :  Tuple   				=					esm_layer.self_attn.v_proj.weight
    _lowerCAmelCase       :  Optional[int]   				=					esm_layer.self_attn.v_proj.bias

    if getattr(esm_layer.self_attn  ,      """rot_emb"""  ,      _lowerCamelCase		) is not None:
      # Matt: Although inv_freq is not a trainable weight, it is computed at model init and cached.
      # During the training of ESM-2 the model was converted to float16 precision, which also converts
      # the inv_freq tensor, and the loss of precision remains even if the model is loaded later as float32.
      # If we recompute inv_freq without this loss of precision then we will get subtly different rotary
      # embeddings, which are enough to cause significant discrepancies in model outputs. To avoid this,
      # we make sure the new model copies the data from the old inv_freq.
      _lowerCAmelCase       :  List[Any]   				=					esm_layer.self_attn.rot_emb.inv_freq

    # LayerNorm changes for pre-activation
    _lowerCAmelCase       :  Dict   				=					esm_layer.self_attn_layer_norm.weight
    _lowerCAmelCase       :  str   				=					esm_layer.self_attn_layer_norm.bias
    _lowerCAmelCase       :  List[Any]   				=					esm_layer.final_layer_norm.weight
    _lowerCAmelCase       :  List[str]   				=					esm_layer.final_layer_norm.bias

    # self-attention output
    _lowerCAmelCase       :  EsmSelfOutput   				=					layer.attention.output
    assert self_output.dense.weight.shape == esm_layer.self_attn.out_proj.weight.shape
    _lowerCAmelCase       :  Optional[Any]   				=					esm_layer.self_attn.out_proj.weight
    _lowerCAmelCase       :  str   				=					esm_layer.self_attn.out_proj.bias

    # intermediate
    _lowerCAmelCase       :  EsmIntermediate   				=					layer.intermediate
    assert intermediate.dense.weight.shape == esm_layer.fca.weight.shape
    _lowerCAmelCase       :  str   				=					esm_layer.fca.weight
    _lowerCAmelCase       :  Dict   				=					esm_layer.fca.bias

    # output
    _lowerCAmelCase       :  EsmOutput   				=					layer.output
    assert bert_output.dense.weight.shape == esm_layer.fca.weight.shape
    _lowerCAmelCase       :  Optional[int]   				=					esm_layer.fca.weight
    _lowerCAmelCase       :  List[Any]   				=					esm_layer.fca.bias
    # end of layer

  if is_folding_model:
    _lowerCAmelCase       :  Optional[Any]   				=					esm.esm_s_combine.data
    _lowerCAmelCase       :  int   				=					esm.afa_to_esm.data
    transfer_and_check_weights(esm.embedding  ,      model.embedding		)
    transfer_and_check_weights(esm.esm_s_mlp  ,      model.esm_s_mlp		)
    transfer_and_check_weights(esm.trunk  ,      model.trunk		)
    transfer_and_check_weights(esm.distogram_head  ,      model.distogram_head		)
    transfer_and_check_weights(esm.ptm_head  ,      model.ptm_head		)
    transfer_and_check_weights(esm.lm_head  ,      model.lm_head		)
    transfer_and_check_weights(esm.lddt_head  ,      model.lddt_head		)

  elif classification_head:
    _lowerCAmelCase       :  List[str]   				=					esm.esm.classification_heads["""mnli"""].dense.weight
    _lowerCAmelCase       :  int   				=					esm.classification_heads["""mnli"""].dense.bias
    _lowerCAmelCase       :  List[str]   				=					esm.classification_heads["""mnli"""].out_proj.weight
    _lowerCAmelCase       :  Tuple   				=					esm.classification_heads["""mnli"""].out_proj.bias
  else:
    # LM Head
    _lowerCAmelCase       :  int   				=					esm.lm_head.dense.weight
    _lowerCAmelCase       :  List[Any]   				=					esm.lm_head.dense.bias
    _lowerCAmelCase       :  Tuple   				=					esm.lm_head.layer_norm.weight
    _lowerCAmelCase       :  Union[str, Any]   				=					esm.lm_head.layer_norm.bias
    _lowerCAmelCase       :  Dict   				=					esm.lm_head.weight
    _lowerCAmelCase       :  List[Any]   				=					esm.lm_head.bias

  # Contact prediction head
  transfer_and_check_weights(esm.contact_head  ,      model.esm.contact_head		)

  # Prepare data (first 2 sequences from ESMStructuralSplitDataset superfamily / 4)
  if is_folding_model:
    # Folding models aren't trained on masked inputs and don't like mask tokens.
    _lowerCAmelCase       :  Any   				=					SAMPLE_DATA[:2]
  else:
    _lowerCAmelCase       :  Tuple   				=					SAMPLE_DATA

  if is_folding_model:
    _lowerCAmelCase       :  str   				=					get_esmfold_tokenizer()
    _lowerCAmelCase       :  Dict   				=					hf_tokenizer(
        [row[1] for row in sample_data]  ,      return_tensors="""pt"""  ,      padding=_lowerCamelCase  ,      add_special_tokens=_lowerCamelCase		)
    _lowerCAmelCase       :  Optional[int]   				=					esmfold_encode_sequences([row[1] for row in sample_data]		)
    _lowerCAmelCase       :  int   				=					torch.all(hf_tokens["""input_ids"""] == esmfold_aas		) and torch.all(
        hf_tokens["""attention_mask"""] == esmfold_mask		)
  else:
    # Let's check that we get the same results.
    _lowerCAmelCase       :  List[Any]   				=					alphabet.get_batch_converter()
    _lowerCAmelCase       :  List[Any]   				=					batch_converter(_lowerCamelCase		)
    # Prepare tokenizer and make sure it matches
    with TemporaryDirectory() as tempdir:
      _lowerCAmelCase       :  List[str]   				=					"""\n""".join(alphabet.all_toks		)
      _lowerCAmelCase       :  Any   				=					Path(_lowerCamelCase		) / """vocab.txt"""
      vocab_file.write_text(_lowerCamelCase		)
      _lowerCAmelCase       :  Dict   				=					EsmTokenizer(vocab_file=str(_lowerCamelCase		)		)

    _lowerCAmelCase       :  str   				=					hf_tokenizer([row[1] for row in sample_data]  ,      return_tensors="""pt"""  ,      padding=_lowerCamelCase		)
    _lowerCAmelCase       :  Optional[Any]   				=					torch.all(hf_tokens["""input_ids"""] == batch_tokens		)

  print("""Do both models tokenizers output the same tokens?"""  ,      """🔥""" if success else """💩"""		)
  if not success:
    raise Exception("""Tokenization does not match!"""		)

  with torch.no_grad():
    if is_folding_model:
      # Let's test the model in parts
      # ESMFold always converts the ESM stem to float16, which requires float16 ops
      # that don't exist on CPU. Therefore, to test it we need to run it on GPU. However,
      # ESMFold is what we in the community call a "big boy" and so we desperately avoid putting both the
      # original and the converted model on the GPU at the same time.
      _lowerCAmelCase       :  Tuple   				=					esm.cuda().infer([row[1] for row in sample_data]		)
      _lowerCAmelCase       :  List[Any]   				=					model.cuda()(
          input_ids=hf_tokens["""input_ids"""].cuda()  ,      attention_mask=hf_tokens["""attention_mask"""].cuda()		)
    else:
      _lowerCAmelCase       :  Tuple   				=					model(**_lowerCamelCase  ,      output_hidden_states=_lowerCamelCase		)
      _lowerCAmelCase       :  List[str]   				=					our_output["""logits"""]
      if classification_head:
        _lowerCAmelCase       :  int   				=					esm.model.classification_heads["""mnli"""](esm.extract_features(_lowerCamelCase		)		)
      else:
        _lowerCAmelCase       :  Optional[int]   				=					esm(hf_tokens["""input_ids"""]  ,      repr_layers=list(range(9_99		)		)		)
        _lowerCAmelCase       :  int   				=					their_output["""logits"""]

    if is_folding_model:
      _lowerCAmelCase       :  Optional[Any]   				=					torch.max(torch.abs(our_output["""positions"""] - their_output["""positions"""]		)		).item()
      _lowerCAmelCase       :  Dict   				=					torch.allclose(our_output["""positions"""]  ,      their_output["""positions"""]  ,      atol=1e-5		)
    else:
      _lowerCAmelCase       :  str   				=					torch.max(torch.abs(our_output - their_output		)		).item()
      _lowerCAmelCase       :  str   				=					torch.allclose(_lowerCamelCase  ,      _lowerCamelCase  ,      atol=1e-5		)

    print(f'max_absolute_diff = {max_absolute_diff}'		)  # ~ 1e-5
    print("""Do both models output the same tensors?"""  ,      """🔥""" if success else """💩"""		)

    if not success:
      raise Exception("""Something went wRoNg"""		)

    if not is_folding_model:
      # Let's check contact prediction too
      _lowerCAmelCase       :  str   				=					model.predict_contacts(hf_tokens["""input_ids"""]  ,      hf_tokens["""attention_mask"""]		)
      _lowerCAmelCase       :  Tuple   				=					esm.predict_contacts(hf_tokens["""input_ids"""]		)
      _lowerCAmelCase       :  int   				=					torch.max(torch.abs(our_output - their_output		)		).item()
      _lowerCAmelCase       :  Union[str, Any]   				=					torch.allclose(_lowerCamelCase  ,      _lowerCamelCase  ,      atol=1e-5		)

      print("""Contact prediction testing:"""		)
      print(f'max_absolute_diff = {max_absolute_diff}'		)  # ~ 1e-5
      print("""Do both models output the same tensors?"""  ,      """🔥""" if success else """💩"""		)

      if not success:
        raise Exception("""Something went wRoNg"""		)

    pathlib.Path(_lowerCamelCase		).mkdir(parents=_lowerCamelCase  ,      exist_ok=_lowerCamelCase		)
    print(f'Saving model to {pytorch_dump_folder_path}'		)
    model.save_pretrained(_lowerCamelCase		)

    del esm  # Free up some memory before continuing

  print(f'Saving tokenizer to {pytorch_dump_folder_path}'		)
  hf_tokenizer.save_pretrained(_lowerCamelCase		)

  if push_to_repo:
    model.push_to_hub(repo_id=_lowerCamelCase  ,      use_auth_token=_lowerCamelCase		)
    hf_tokenizer.push_to_hub(repo_id=_lowerCamelCase  ,      use_auth_token=_lowerCamelCase		)


if __name__ == "__main__":
     UpperCamelCase_     			=       argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         """--pytorch_dump_folder_path""", type=str, required=True, help="""Path to the output PyTorch model."""
     )
     parser.add_argument(
         """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head."""
     )
     parser.add_argument("""--model""", default=None, type=str, required=True, help="""Name of model to convert.""")
     parser.add_argument("""--push_to_repo""", type=str, help="""Repo to upload to (including username!).""")
     parser.add_argument("""--auth_token""", type=str, help="""HuggingFace auth token.""")
     UpperCamelCase_     			=       parser.parse_args()
     convert_esm_checkpoint_to_pytorch(
         args.model, args.pytorch_dump_folder_path, args.classification_head, args.push_to_repo, args.auth_token
     )




'''simple docstring'''

import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


class   a_  (TensorFormatter[Mapping, np.ndarray, Mapping]    ):




       def __init__(     self   ,   snake_case_=None   ,   **snake_case_  ):
         super().__init__(features=snake_case_  )
         _lowerCAmelCase       :  Any   				=					np_array_kwargs




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         if isinstance(snake_case_   ,   snake_case_  ):
           if column and all(
               isinstance(snake_case_   ,   np.ndarray  ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column  ):
             return np.stack(snake_case_  )
           else:
             # don't use np.array(column, dtype=object)
             # since it fails in certain cases
             # see https://stackoverflow.com/q/51005699
             _lowerCAmelCase       :  str   				=					np.empty(len(snake_case_  )   ,   dtype=snake_case_  )
             _lowerCAmelCase       :  List[Any]   				=					column
             return out
         return column




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         if isinstance(snake_case_   ,   (str, bytes, type(snake_case_  ))  ):
           return value
         elif isinstance(snake_case_   ,   (np.character, np.ndarray)  ) and np.issubdtype(value.dtype   ,   np.character  ):
           return value
         elif isinstance(snake_case_   ,   np.number  ):
           return value

         _lowerCAmelCase       :  List[Any]   				=					{}

         if isinstance(snake_case_   ,   np.ndarray  ) and np.issubdtype(value.dtype   ,   np.integer  ):
           _lowerCAmelCase       :  Union[str, Any]   				=					{"""dtype""": np.intaa}
         elif isinstance(snake_case_   ,   np.ndarray  ) and np.issubdtype(value.dtype   ,   np.floating  ):
           _lowerCAmelCase       :  Tuple   				=					{"""dtype""": np.floataa}
         elif config.PIL_AVAILABLE and "PIL" in sys.modules:
           import PIL.Image

           if isinstance(snake_case_   ,   PIL.Image.Image  ):
             return np.asarray(snake_case_   ,   **self.np_array_kwargs  )

         return np.asarray(snake_case_   ,   **{**default_dtype, **self.np_array_kwargs}  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         # support for torch, tf, jax etc.
         if config.TORCH_AVAILABLE and "torch" in sys.modules:
           import torch

           if isinstance(snake_case_   ,   torch.Tensor  ):
             return self._tensorize(data_struct.detach().cpu().numpy()[()]  )
         if hasattr(snake_case_   ,   """__array__"""  ) and not isinstance(snake_case_   ,   (np.ndarray, np.character, np.number)  ):
           _lowerCAmelCase       :  List[Any]   				=					data_struct.__array__()
         # support for nested types like struct of list of struct
         if isinstance(snake_case_   ,   np.ndarray  ):
           if data_struct.dtype == object:
             return self._consolidate([self.recursive_tensorize(snake_case_  ) for substruct in data_struct]  )
         if isinstance(snake_case_   ,   (list, tuple)  ):
           return self._consolidate([self.recursive_tensorize(snake_case_  ) for substruct in data_struct]  )
         return self._tensorize(snake_case_  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         return map_nested(self._recursive_tensorize   ,   snake_case_   ,   map_list=snake_case_  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         _lowerCAmelCase       :  Optional[Any]   				=					self.numpy_arrow_extractor().extract_row(snake_case_  )
         _lowerCAmelCase       :  Any   				=					self.python_features_decoder.decode_row(snake_case_  )
         return self.recursive_tensorize(snake_case_  )




       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         _lowerCAmelCase       :  List[Any]   				=					self.numpy_arrow_extractor().extract_column(snake_case_  )
         _lowerCAmelCase       :  Tuple   				=					self.python_features_decoder.decode_column(snake_case_   ,   pa_table.column_names[0]  )
         _lowerCAmelCase       :  Optional[int]   				=					self.recursive_tensorize(snake_case_  )
         _lowerCAmelCase       :  Optional[Any]   				=					self._consolidate(snake_case_  )
         return column







       def 							__UpperCamelCase       (     self   ,   snake_case_  ):
         _lowerCAmelCase       :  List[Any]   				=					self.numpy_arrow_extractor().extract_batch(snake_case_  )
         _lowerCAmelCase       :  str   				=					self.python_features_decoder.decode_batch(snake_case_  )
         _lowerCAmelCase       :  Dict   				=					self.recursive_tensorize(snake_case_  )
         for column_name in batch:
           _lowerCAmelCase       :  int   				=					self._consolidate(batch[column_name]  )
         return batch


