




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      :  List[Any]      						=						logging.get_logger(__name__)
class        __snake_case  (_a		):



				def __init__(      self      :		Dict		,	**_UpperCAmelCase      :		Union[str, Any]      )  ->    Optional[Any]:





								'''simple docstring'''




								requires_backends(self		,	["""bs4"""]      )
								super().__init__(**_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		int		,	_UpperCAmelCase      :		List[str]      )  ->    Tuple:





								'''simple docstring'''




								_lowerCAmelCase    :    Tuple										=      []
								_lowerCAmelCase    :    Optional[int]										=      []
								_lowerCAmelCase    :    str										=      element if element.name else element.parent
								for parent in child.parents:  # type: bs4.element.Tag
												_lowerCAmelCase    :    Optional[int]										=      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      )      )
												_lowerCAmelCase    :    int										=      parent
								xpath_tags.reverse()
								xpath_subscripts.reverse()
								return xpath_tags, xpath_subscripts



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]		,	_UpperCAmelCase      :		Dict      )  ->    Tuple:





								'''simple docstring'''




								_lowerCAmelCase    :    Union[str, Any]										=      BeautifulSoup(_UpperCAmelCase		,	"""html.parser"""      )

								_lowerCAmelCase    :    int										=      []
								_lowerCAmelCase    :    List[Any]										=      []
								_lowerCAmelCase    :    Optional[Any]										=      []

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

																_lowerCAmelCase    :    Dict										=      html.unescape(_UpperCAmelCase      ).strip()
																if not text_in_this_tag:
																				continue

																all_doc_strings.append(_UpperCAmelCase      )

																_lowerCAmelCase					,    _lowerCAmelCase    :    Any										=      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       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]		,	_UpperCAmelCase      :		int		,	_UpperCAmelCase      :		Optional[int]      )  ->    Optional[int]:





								'''simple docstring'''




								_lowerCAmelCase    :    List[Any]										=      """"""
								for tagname, subs in zip(_UpperCAmelCase		,	_UpperCAmelCase      ):
												xpath += f"/{tagname}"
												if subs != 0:
																xpath += f"[{subs}]"
								return xpath



				def __call__(      self      :		Any		,	_UpperCAmelCase      :		Tuple      )  ->    BatchFeature:





								'''simple docstring'''




								_lowerCAmelCase    :    Union[str, Any]										=      False

								# Check that strings has a valid type
								if isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ):
												_lowerCAmelCase    :    str										=      True
								elif isinstance(_UpperCAmelCase		,	(list, tuple)      ):
												if len(_UpperCAmelCase      ) == 0 or isinstance(html_strings[0]		,	_UpperCAmelCase      ):
																_lowerCAmelCase    :    List[str]										=      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      )}."      )

								_lowerCAmelCase    :    str										=      bool(isinstance(_UpperCAmelCase		,	(list, tuple)      ) and (isinstance(html_strings[0]		,	_UpperCAmelCase      ))      )

								if not is_batched:
												_lowerCAmelCase    :    Any										=      [html_strings]

								# Get nodes + xpaths
								_lowerCAmelCase    :    Tuple										=      []
								_lowerCAmelCase    :    Union[str, Any]										=      []
								for html_string in html_strings:
												_lowerCAmelCase					,    _lowerCAmelCase					,    _lowerCAmelCase    :    List[Any]										=      self.get_three_from_single(_UpperCAmelCase      )
												nodes.append(_UpperCAmelCase      )
												_lowerCAmelCase    :    Union[str, Any]										=      []
												for node, tag_list, sub_list in zip(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase      ):
																_lowerCAmelCase    :    List[str]										=      self.construct_xpath(_UpperCAmelCase		,	_UpperCAmelCase      )
																xpath_strings.append(_UpperCAmelCase      )
												xpaths.append(_UpperCAmelCase      )

								# return as Dict
								_lowerCAmelCase    :    Optional[Any]										=      {"""nodes""": nodes, """xpaths""": xpaths}
								_lowerCAmelCase    :    Dict										=      BatchFeature(data=_UpperCAmelCase		,	tensor_type=_UpperCAmelCase      )

								return encoded_inputs







import tempfile

import torch

from diffusers import PNDMScheduler

from .test_schedulers import SchedulerCommonTest
class        __snake_case  (_a		):
				lowerCAmelCase__				=     (PNDMScheduler,)
				lowerCAmelCase__				=     (("num_inference_steps", 5_0),)



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]		,	**_UpperCAmelCase      :		Optional[int]      )  ->    str:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      {
								    """num_train_timesteps""": 1000,
								    """beta_start""": 0.0001,
								    """beta_end""": 0.02,
								    """beta_schedule""": """linear""",
								}

								config.update(**_UpperCAmelCase      )
								return config



				def       SCREAMING_SNAKE_CASE       (      self      :		Any		,	_UpperCAmelCase      :		Union[str, Any]=0		,	**_UpperCAmelCase      :		str      )  ->    Any:





								'''simple docstring'''




								_lowerCAmelCase    :    Union[str, Any]										=      dict(self.forward_default_kwargs      )
								_lowerCAmelCase    :    str										=      kwargs.pop("""num_inference_steps"""		,	_UpperCAmelCase      )
								_lowerCAmelCase    :    Optional[Any]										=      self.dummy_sample
								_lowerCAmelCase    :    List[str]										=      0.1 * sample
								_lowerCAmelCase    :    Tuple										=      [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

								for scheduler_class in self.scheduler_classes:
												_lowerCAmelCase    :    Any										=      self.get_scheduler_config(**_UpperCAmelCase      )
												_lowerCAmelCase    :    Optional[Any]										=      scheduler_class(**_UpperCAmelCase      )
												scheduler.set_timesteps(_UpperCAmelCase      )
												# copy over dummy past residuals
												_lowerCAmelCase    :    Tuple										=      dummy_past_residuals[:]

												with tempfile.TemporaryDirectory() as tmpdirname:
																scheduler.save_config(_UpperCAmelCase      )
																_lowerCAmelCase    :    str										=      scheduler_class.from_pretrained(_UpperCAmelCase      )
																new_scheduler.set_timesteps(_UpperCAmelCase      )
																# copy over dummy past residuals
																_lowerCAmelCase    :    Any										=      dummy_past_residuals[:]

												_lowerCAmelCase    :    int										=      scheduler.step_prk(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample
												_lowerCAmelCase    :    List[str]										=      new_scheduler.step_prk(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample

												assert torch.sum(torch.abs(output - new_output      )      ) < 1E-5, "Scheduler outputs are not identical"

												_lowerCAmelCase    :    Tuple										=      scheduler.step_plms(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample
												_lowerCAmelCase    :    Optional[int]										=      new_scheduler.step_plms(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample

												assert torch.sum(torch.abs(output - new_output      )      ) < 1E-5, "Scheduler outputs are not identical"



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]      )  ->    str:





								'''simple docstring'''




								pass



				def       SCREAMING_SNAKE_CASE       (      self      :		int		,	_UpperCAmelCase      :		Any=0		,	**_UpperCAmelCase      :		Optional[int]      )  ->    Any:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      dict(self.forward_default_kwargs      )
								_lowerCAmelCase    :    Any										=      kwargs.pop("""num_inference_steps"""		,	_UpperCAmelCase      )
								_lowerCAmelCase    :    List[Any]										=      self.dummy_sample
								_lowerCAmelCase    :    Dict										=      0.1 * sample
								_lowerCAmelCase    :    Dict										=      [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

								for scheduler_class in self.scheduler_classes:
												_lowerCAmelCase    :    Any										=      self.get_scheduler_config()
												_lowerCAmelCase    :    Optional[Any]										=      scheduler_class(**_UpperCAmelCase      )
												scheduler.set_timesteps(_UpperCAmelCase      )

												# copy over dummy past residuals (must be after setting timesteps)
												_lowerCAmelCase    :    str										=      dummy_past_residuals[:]

												with tempfile.TemporaryDirectory() as tmpdirname:
																scheduler.save_config(_UpperCAmelCase      )
																_lowerCAmelCase    :    List[Any]										=      scheduler_class.from_pretrained(_UpperCAmelCase      )
																# copy over dummy past residuals
																new_scheduler.set_timesteps(_UpperCAmelCase      )

																# copy over dummy past residual (must be after setting timesteps)
																_lowerCAmelCase    :    Any										=      dummy_past_residuals[:]

												_lowerCAmelCase    :    Tuple										=      scheduler.step_prk(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample
												_lowerCAmelCase    :    str										=      new_scheduler.step_prk(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample

												assert torch.sum(torch.abs(output - new_output      )      ) < 1E-5, "Scheduler outputs are not identical"

												_lowerCAmelCase    :    Any										=      scheduler.step_plms(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample
												_lowerCAmelCase    :    Any										=      new_scheduler.step_plms(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample

												assert torch.sum(torch.abs(output - new_output      )      ) < 1E-5, "Scheduler outputs are not identical"



				def       SCREAMING_SNAKE_CASE       (      self      :		Any		,	**_UpperCAmelCase      :		Dict      )  ->    List[str]:





								'''simple docstring'''




								_lowerCAmelCase    :    Tuple										=      self.scheduler_classes[0]
								_lowerCAmelCase    :    int										=      self.get_scheduler_config(**_UpperCAmelCase      )
								_lowerCAmelCase    :    List[str]										=      scheduler_class(**_UpperCAmelCase      )

								_lowerCAmelCase    :    List[Any]										=      10
								_lowerCAmelCase    :    Any										=      self.dummy_model()
								_lowerCAmelCase    :    Tuple										=      self.dummy_sample_deter
								scheduler.set_timesteps(_UpperCAmelCase      )

								for i, t in enumerate(scheduler.prk_timesteps      ):
												_lowerCAmelCase    :    List[Any]										=      model(_UpperCAmelCase		,	_UpperCAmelCase      )
												_lowerCAmelCase    :    Tuple										=      scheduler.step_prk(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase      ).prev_sample

								for i, t in enumerate(scheduler.plms_timesteps      ):
												_lowerCAmelCase    :    List[Any]										=      model(_UpperCAmelCase		,	_UpperCAmelCase      )
												_lowerCAmelCase    :    Dict										=      scheduler.step_plms(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase      ).prev_sample

								return sample



				def       SCREAMING_SNAKE_CASE       (      self      :		int      )  ->    List[str]:





								'''simple docstring'''




								_lowerCAmelCase    :    List[str]										=      dict(self.forward_default_kwargs      )

								_lowerCAmelCase    :    int										=      kwargs.pop("""num_inference_steps"""		,	_UpperCAmelCase      )

								for scheduler_class in self.scheduler_classes:
												_lowerCAmelCase    :    Tuple										=      self.get_scheduler_config()
												_lowerCAmelCase    :    Union[str, Any]										=      scheduler_class(**_UpperCAmelCase      )

												_lowerCAmelCase    :    str										=      self.dummy_sample
												_lowerCAmelCase    :    str										=      0.1 * sample

												if num_inference_steps is not None and hasattr(_UpperCAmelCase		,	"""set_timesteps"""      ):
																scheduler.set_timesteps(_UpperCAmelCase      )
												elif num_inference_steps is not None and not hasattr(_UpperCAmelCase		,	"""set_timesteps"""      ):
																_lowerCAmelCase    :    Tuple										=      num_inference_steps

												# copy over dummy past residuals (must be done after set_timesteps)
												_lowerCAmelCase    :    List[Any]										=      [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
												_lowerCAmelCase    :    List[str]										=      dummy_past_residuals[:]

												_lowerCAmelCase    :    Optional[int]										=      scheduler.step_prk(_UpperCAmelCase		,	0		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample
												_lowerCAmelCase    :    Optional[int]										=      scheduler.step_prk(_UpperCAmelCase		,	1		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample

												self.assertEqual(output_a.shape		,	sample.shape      )
												self.assertEqual(output_a.shape		,	output_a.shape      )

												_lowerCAmelCase    :    Tuple										=      scheduler.step_plms(_UpperCAmelCase		,	0		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample
												_lowerCAmelCase    :    Optional[Any]										=      scheduler.step_plms(_UpperCAmelCase		,	1		,	_UpperCAmelCase		,	**_UpperCAmelCase      ).prev_sample

												self.assertEqual(output_a.shape		,	sample.shape      )
												self.assertEqual(output_a.shape		,	output_a.shape      )



				def       SCREAMING_SNAKE_CASE       (      self      :		int      )  ->    List[Any]:





								'''simple docstring'''




								for timesteps in [100, 1000]:
												self.check_over_configs(num_train_timesteps=_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]      )  ->    Optional[int]:





								'''simple docstring'''




								for steps_offset in [0, 1]:
												self.check_over_configs(steps_offset=_UpperCAmelCase      )

								_lowerCAmelCase    :    Dict										=      self.scheduler_classes[0]
								_lowerCAmelCase    :    Any										=      self.get_scheduler_config(steps_offset=1      )
								_lowerCAmelCase    :    Any										=      scheduler_class(**_UpperCAmelCase      )
								scheduler.set_timesteps(10      )
								assert torch.equal(
								    scheduler.timesteps		,	torch.LongTensor(
								        [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]      )		,	)



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple      )  ->    List[Any]:





								'''simple docstring'''




								for beta_start, beta_end in zip([0.0001, 0.001]		,	[0.002, 0.02]      ):
												self.check_over_configs(beta_start=_UpperCAmelCase		,	beta_end=_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		List[Any]      )  ->    int:





								'''simple docstring'''




								for schedule in ["linear", "squaredcos_cap_v2"]:
												self.check_over_configs(beta_schedule=_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		str      )  ->    Union[str, Any]:





								'''simple docstring'''




								for prediction_type in ["epsilon", "v_prediction"]:
												self.check_over_configs(prediction_type=_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict      )  ->    List[str]:





								'''simple docstring'''




								for t in [1, 5, 10]:
												self.check_over_forward(time_step=_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]      )  ->    List[Any]:





								'''simple docstring'''




								for t, num_inference_steps in zip([1, 5, 10]		,	[10, 50, 100]      ):
												self.check_over_forward(num_inference_steps=_UpperCAmelCase      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict      )  ->    Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    Union[str, Any]										=      27

								for scheduler_class in self.scheduler_classes:
												_lowerCAmelCase    :    Optional[Any]										=      self.dummy_sample
												_lowerCAmelCase    :    Any										=      0.1 * sample

												_lowerCAmelCase    :    List[str]										=      self.get_scheduler_config()
												_lowerCAmelCase    :    Any										=      scheduler_class(**_UpperCAmelCase      )

												scheduler.set_timesteps(_UpperCAmelCase      )

												# before power of 3 fix, would error on first step, so we only need to do two
												for i, t in enumerate(scheduler.prk_timesteps[:2]      ):
																_lowerCAmelCase    :    List[Any]										=      scheduler.step_prk(_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase      ).prev_sample



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict      )  ->    Union[str, Any]:





								'''simple docstring'''




								with self.assertRaises(_UpperCAmelCase      ):
												_lowerCAmelCase    :    Tuple										=      self.scheduler_classes[0]
												_lowerCAmelCase    :    List[str]										=      self.get_scheduler_config()
												_lowerCAmelCase    :    Any										=      scheduler_class(**_UpperCAmelCase      )

												scheduler.step_plms(self.dummy_sample		,	1		,	self.dummy_sample      ).prev_sample



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple      )  ->    Any:





								'''simple docstring'''




								_lowerCAmelCase    :    Tuple										=      self.full_loop()
								_lowerCAmelCase    :    str										=      torch.sum(torch.abs(_UpperCAmelCase      )      )
								_lowerCAmelCase    :    List[Any]										=      torch.mean(torch.abs(_UpperCAmelCase      )      )

								assert abs(result_sum.item() - 198.1318      ) < 1E-2
								assert abs(result_mean.item() - 0.2580      ) < 1E-3



				def       SCREAMING_SNAKE_CASE       (      self      :		Union[str, Any]      )  ->    Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      self.full_loop(prediction_type="""v_prediction"""      )
								_lowerCAmelCase    :    Optional[int]										=      torch.sum(torch.abs(_UpperCAmelCase      )      )
								_lowerCAmelCase    :    Optional[int]										=      torch.mean(torch.abs(_UpperCAmelCase      )      )

								assert abs(result_sum.item() - 67.3986      ) < 1E-2
								assert abs(result_mean.item() - 0.0878      ) < 1E-3



				def       SCREAMING_SNAKE_CASE       (      self      :		List[Any]      )  ->    Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    str										=      self.full_loop(set_alpha_to_one=_UpperCAmelCase		,	beta_start=0.01      )
								_lowerCAmelCase    :    Any										=      torch.sum(torch.abs(_UpperCAmelCase      )      )
								_lowerCAmelCase    :    Optional[Any]										=      torch.mean(torch.abs(_UpperCAmelCase      )      )

								assert abs(result_sum.item() - 230.0399      ) < 1E-2
								assert abs(result_mean.item() - 0.2995      ) < 1E-3



				def       SCREAMING_SNAKE_CASE       (      self      :		str      )  ->    Union[str, Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      self.full_loop(set_alpha_to_one=_UpperCAmelCase		,	beta_start=0.01      )
								_lowerCAmelCase    :    List[Any]										=      torch.sum(torch.abs(_UpperCAmelCase      )      )
								_lowerCAmelCase    :    Tuple										=      torch.mean(torch.abs(_UpperCAmelCase      )      )

								assert abs(result_sum.item() - 186.9482      ) < 1E-2
								assert abs(result_mean.item() - 0.2434      ) < 1E-3

