
import os
import string
import sys


__lowerCAmelCase     :	str       			=  1 << 8

__lowerCAmelCase     :	Optional[Any]       			=  {
    'tab': ord('\t'),
    'newline': ord('\r'),
    'esc': 27,
    'up': 65 + ARROW_KEY_FLAG,
    'down': 66 + ARROW_KEY_FLAG,
    'right': 67 + ARROW_KEY_FLAG,
    'left': 68 + ARROW_KEY_FLAG,
    'mod_int': 91,
    'undefined': sys.maxsize,
    'interrupt': 3,
    'insert': 50,
    'delete': 51,
    'pg_up': 53,
    'pg_down': 54,
}

__lowerCAmelCase     :	Dict       			=  KEYMAP['up']
__lowerCAmelCase     :	Any       			=  KEYMAP['left']

if sys.platform == "win32":
    __lowerCAmelCase     :	str       			=  []
    __lowerCAmelCase     :	Union[str, Any]       			=  {
        b'\xe0H': KEYMAP['up'] - ARROW_KEY_FLAG,
        b'\x00H': KEYMAP['up'] - ARROW_KEY_FLAG,
        b'\xe0P': KEYMAP['down'] - ARROW_KEY_FLAG,
        b'\x00P': KEYMAP['down'] - ARROW_KEY_FLAG,
        b'\xe0M': KEYMAP['right'] - ARROW_KEY_FLAG,
        b'\x00M': KEYMAP['right'] - ARROW_KEY_FLAG,
        b'\xe0K': KEYMAP['left'] - ARROW_KEY_FLAG,
        b'\x00K': KEYMAP['left'] - ARROW_KEY_FLAG,
    }

for i in range(10):
    __lowerCAmelCase     :	Any       			=  ord(str(i))

def a__       (			):






  '''simple docstring'''





  if os.name == "nt":
    import msvcrt

    __magic_name__								=			"""mbcs"""
    # Flush the keyboard buffer
    while msvcrt.kbhit():
      msvcrt.getch()
    if len(A_   ) == 0:
      # Read the keystroke
      __magic_name__								=			msvcrt.getch()

      # If it is a prefix char, get second part
      if ch in (b"\x00", b"\xe0"):
        __magic_name__								=			ch + msvcrt.getch()
        # Translate actual Win chars to bullet char types
        try:
          __magic_name__								=			chr(WIN_KEYMAP[cha]   )
          WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""]   )   )
          WIN_CH_BUFFER.append(A_   )
          if ord(A_   ) in (
              KEYMAP["insert"] - 1 << 9,
              KEYMAP["delete"] - 1 << 9,
              KEYMAP["pg_up"] - 1 << 9,
              KEYMAP["pg_down"] - 1 << 9,
          ):
            WIN_CH_BUFFER.append(chr(126   )   )
          __magic_name__								=			chr(KEYMAP["""esc"""]   )
        except KeyError:
          __magic_name__								=			cha[1]
      else:
        __magic_name__								=			ch.decode(A_   )
    else:
      __magic_name__								=			WIN_CH_BUFFER.pop(0   )
  elif os.name == "posix":
    import termios
    import tty

    __magic_name__								=			sys.stdin.fileno()
    __magic_name__								=			termios.tcgetattr(A_   )
    try:
      tty.setraw(A_   )
      __magic_name__								=			sys.stdin.read(1   )
    finally:
      termios.tcsetattr(A_,	termios.TCSADRAIN,	A_   )
  return ch





def a__       (			):






  '''simple docstring'''





  __magic_name__								=			get_raw_chars()
  if ord(A_   ) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
    return char

  elif ord(A_   ) == KEYMAP["esc"]:
    __magic_name__								=			get_raw_chars()
    if ord(A_   ) == KEYMAP["mod_int"]:
      __magic_name__								=			get_raw_chars()
      if ord(A_   ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(A_   ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
        return chr(ord(A_   ) + ARROW_KEY_FLAG   )
      else:
        return KEYMAP["undefined"]
    else:
      return get_raw_chars()

  else:
    if char in string.printable:
      return char
    else:
      return KEYMAP["undefined"]



import html

from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...utils import is_bsa_available, logging, requires_backends


if is_bsa_available():
    import bsa
    from bsa import BeautifulSoup


__lowerCAmelCase     :	int       			=  logging.get_logger(__name__)




class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  def __init__(					self     :					Union[str, Any]     ,				**UpperCamelCase__     :					Union[str, Any]       )     ->      Union[str, Any]:







    """simple docstring"""






    requires_backends(self     ,				["""bs4"""]       )
    super().__init__(**UpperCamelCase__       )
  def 				_lowercase				(					self     :					Dict     ,				UpperCamelCase__     :					Union[str, Any]       )     ->      Optional[Any]:







    """simple docstring"""






    __magic_name__								=			[]
    __magic_name__								=			[]
    __magic_name__								=			element if element.name else element.parent
    for parent in child.parents:  # type: bs4.element.Tag
      __magic_name__								=			parent.find_all(child.name     ,				recursive=UpperCamelCase__       )
      xpath_tags.append(child.name       )
      xpath_subscripts.append(
          0 if 1 == len(UpperCamelCase__       ) else next(i for i, s in enumerate(UpperCamelCase__     ,				1       ) if s is child       )       )
      __magic_name__								=			parent
    xpath_tags.reverse()
    xpath_subscripts.reverse()
    return xpath_tags, xpath_subscripts
  def 				_lowercase				(					self     :					Union[str, Any]     ,				UpperCamelCase__     :					List[Any]       )     ->      str:







    """simple docstring"""






    __magic_name__								=			BeautifulSoup(UpperCamelCase__     ,				"""html.parser"""       )

    __magic_name__								=			[]
    __magic_name__								=			[]
    __magic_name__								=			[]

    for element in html_code.descendants:
      if type(UpperCamelCase__       ) == bsa.element.NavigableString:
        if type(element.parent       ) != bsa.element.Tag:
          continue

        __magic_name__								=			html.unescape(UpperCamelCase__       ).strip()
        if not text_in_this_tag:
          continue

        all_doc_strings.append(UpperCamelCase__       )

        __magic_name__	,       __magic_name__								=			self.xpath_soup(UpperCamelCase__       )
        stringaxtag_seq.append(UpperCamelCase__       )
        stringaxsubs_seq.append(UpperCamelCase__       )

    if len(UpperCamelCase__       ) != len(UpperCamelCase__       ):
      raise ValueError("""Number of doc strings and xtags does not correspond"""       )
    if len(UpperCamelCase__       ) != len(UpperCamelCase__       ):
      raise ValueError("""Number of doc strings and xsubs does not correspond"""       )

    return all_doc_strings, stringaxtag_seq, stringaxsubs_seq
  def 				_lowercase				(					self     :					List[Any]     ,				UpperCamelCase__     :					Dict     ,				UpperCamelCase__     :					List[Any]       )     ->      Optional[Any]:







    """simple docstring"""






    __magic_name__								=			""""""
    for tagname, subs in zip(UpperCamelCase__     ,				UpperCamelCase__       ):
      xpath += F'''/{tagname}'''
      if subs != 0:
        xpath += F'''[{subs}]'''
    return xpath





  def __call__(					self     :					str     ,				UpperCamelCase__     :					Tuple       )     ->      BatchFeature:







    """simple docstring"""






    __magic_name__								=			False

    # Check that strings has a valid type
    if isinstance(UpperCamelCase__     ,				UpperCamelCase__       ):
      __magic_name__								=			True
    elif isinstance(UpperCamelCase__     ,				(list, tuple)       ):
      if len(UpperCamelCase__       ) == 0 or isinstance(html_strings[0]     ,				UpperCamelCase__       ):
        __magic_name__								=			True

    if not valid_strings:
      raise ValueError(
          """HTML strings must of type `str`, `List[str]` (batch of examples), """
          F'''but is of type {type(UpperCamelCase__       )}.'''       )

    __magic_name__								=			bool(isinstance(UpperCamelCase__     ,				(list, tuple)       ) and (isinstance(html_strings[0]     ,				UpperCamelCase__       ))       )

    if not is_batched:
      __magic_name__								=			[html_strings]

    # Get nodes + xpaths
    __magic_name__								=			[]
    __magic_name__								=			[]
    for html_string in html_strings:
      __magic_name__	,       __magic_name__	,       __magic_name__								=			self.get_three_from_single(UpperCamelCase__       )
      nodes.append(UpperCamelCase__       )
      __magic_name__								=			[]
      for node, tag_list, sub_list in zip(UpperCamelCase__     ,				UpperCamelCase__     ,				UpperCamelCase__       ):
        __magic_name__								=			self.construct_xpath(UpperCamelCase__     ,				UpperCamelCase__       )
        xpath_strings.append(UpperCamelCase__       )
      xpaths.append(UpperCamelCase__       )

    # return as Dict
    __magic_name__								=			{"""nodes""": nodes, """xpaths""": xpaths}
    __magic_name__								=			BatchFeature(data=UpperCamelCase__     ,				tensor_type=UpperCamelCase__       )

    return encoded_inputs

