



"""simple docstring"""
import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length

def       _snake_case						(						UpperCamelCase						:		Optional[int]						):
 UpperCAmelCase	:					int	=	int(UpperCamelCase						)
 UpperCAmelCase	,		UpperCAmelCase	,		UpperCAmelCase	:					Optional[int]	=	t // 3600, (t // 60) % 60, t % 60
 return F"{h}:{m:02d}:{s:02d}" if h != 0 else F"{m:02d}:{s:02d}"

def       _snake_case						(						UpperCamelCase						:		Optional[int]			,		UpperCamelCase						:		Tuple			,		UpperCamelCase						:		Any			,		UpperCamelCase						:		Optional[int]			,		UpperCamelCase						:		int=300						):
 # docstyle-ignore
 return F"\n    <div>\n      {prefix}\n      <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>\n      {label}\n    </div>\n    "

def       _snake_case						(						UpperCamelCase						:		Dict						):
 UpperCAmelCase	:					str	=	"""<table border=\"1\" class=\"dataframe\">\n"""
 html_code += """  <thead>\n <tr style="text-align: left;">\n"""
 for i in items[0]:
  html_code += F"      <th>{i}</th>\n"
 html_code += "    </tr>\n  </thead>\n  <tbody>\n"
 for line in items[1:]:
  html_code += "    <tr>\n"
  for elt in line:
   UpperCAmelCase	:					Optional[Any]	=	F"{elt:.6f}" if isinstance(UpperCamelCase			,		UpperCamelCase						) else str(UpperCamelCase						)
   html_code += F"      <td>{elt}</td>\n"
  html_code += "    </tr>\n"
 html_code += "  </tbody>\n</table><p>"
 return html_code



class       SCREAMING_SNAKE_CASE__  :
   __lowerCAmelCase  :   Optional[int]						=						5
   __lowerCAmelCase  :   Tuple						=						0.2

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = True      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = 300      ,     )  ->      Dict:





    '''simple docstring'''




    UpperCAmelCase	:					str	=	total
    UpperCAmelCase	:					Optional[int]	=	"""""" if prefix is None else prefix
    UpperCAmelCase	:					Union[str, Any]	=	leave
    UpperCAmelCase	:					List[Any]	=	parent
    UpperCAmelCase	:					Dict	=	width
    UpperCAmelCase	:					int	=	None
    UpperCAmelCase	:					List[Any]	=	None
    UpperCAmelCase	:					Dict	=	None

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = None						)  ->      Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase	:					int	=	value
    if comment is not None:
     UpperCAmelCase	:					Dict	=	comment
    if self.last_value is None:
     UpperCAmelCase	:					List[str]	=	time.time()
     UpperCAmelCase	:					int	=	value
     UpperCAmelCase	:					List[Any]	=	None
     UpperCAmelCase	:					Union[str, Any]	=	self.warmup
     UpperCAmelCase	:					Any	=	1
     self.update_bar(_SCREAMING_SNAKE_CASE						)
    elif value <= self.last_value and not force_update:
     return
    elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for      ,     self.total						):
     if self.first_calls > 0:
      self.first_calls -= 1
     UpperCAmelCase	:					int	=	time.time()
     UpperCAmelCase	:					Dict	=	current_time - self.start_time
     # We could have value = self.start_value if the update is called twixe with the same start value.
     if value > self.start_value:
      UpperCAmelCase	:					Any	=	self.elapsed_time / (value - self.start_value)
     else:
      UpperCAmelCase	:					Any	=	None
     if value >= self.total:
      UpperCAmelCase	:					Tuple	=	self.total
      UpperCAmelCase	:					Dict	=	None
      if not self.leave:
       self.close()
     elif self.average_time_per_item is not None:
      UpperCAmelCase	:					Dict	=	self.average_time_per_item * (self.total - value)
     self.update_bar(_SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Any	=	value
     UpperCAmelCase	:					Union[str, Any]	=	current_time
     if self.average_time_per_item is None:
      UpperCAmelCase	:					List[Any]	=	1
     else:
      UpperCAmelCase	:					Dict	=	max(int(self.update_every / self.average_time_per_item						)      ,     1						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE=None						)  ->      List[Any]:





    '''simple docstring'''




    UpperCAmelCase	:					Any	=	""" """ * (len(str(self.total						)						) - len(str(_SCREAMING_SNAKE_CASE						)						)) + str(_SCREAMING_SNAKE_CASE						)
    if self.elapsed_time is None:
     UpperCAmelCase	:					List[Any]	=	F"[{spaced_value}/{self.total} : < :"
    elif self.predicted_remaining is None:
     UpperCAmelCase	:					Union[str, Any]	=	F"[{spaced_value}/{self.total} {format_time(self.elapsed_time						)}"
    else:
     UpperCAmelCase	:					Optional[int]	=	(
         F"[{spaced_value}/{self.total} {format_time(self.elapsed_time						)} <"
         F" {format_time(self.predicted_remaining						)}"
     )
     self.label += F", {1/self.average_time_per_item:.2f} it/s"
    self.label += "]" if self.comment is None or len(self.comment						) == 0 else F", {self.comment}]"
    self.display()

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    UpperCAmelCase	:					List[str]	=	html_progress_bar(self.value      ,     self.total      ,     self.prefix      ,     self.label      ,     self.width						)
    if self.parent is not None:
     # If this is a child bar, the parent will take care of the display.
     self.parent.display()
     return
    if self.output is None:
     UpperCAmelCase	:					Dict	=	disp.display(disp.HTML(self.html_code						)      ,     display_id=_SCREAMING_SNAKE_CASE						)
    else:
     self.output.update(disp.HTML(self.html_code						)						)




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





    '''simple docstring'''




    if self.parent is None and self.output is not None:
     self.output.update(disp.HTML(""""""						)						)



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE=None						)  ->      str:





    '''simple docstring'''




    super().__init__(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					List[Any]	=	None if column_names is None else [column_names]
    UpperCAmelCase	:					List[Any]	=	None

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





    '''simple docstring'''




    UpperCAmelCase	:					Optional[Any]	=	html_progress_bar(self.value      ,     self.total      ,     self.prefix      ,     self.label      ,     self.width						)
    if self.inner_table is not None:
     self.html_code += text_to_html_table(self.inner_table						)
    if self.child_bar is not None:
     self.html_code += self.child_bar.html_code
    if self.output is None:
     UpperCAmelCase	:					Any	=	disp.display(disp.HTML(self.html_code						)      ,     display_id=_SCREAMING_SNAKE_CASE						)
    else:
     self.output.update(disp.HTML(self.html_code						)						)

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





    '''simple docstring'''




    if self.inner_table is None:
     UpperCAmelCase	:					Tuple	=	[list(values.keys()						), list(values.values()						)]
    else:
     UpperCAmelCase	:					str	=	self.inner_table[0]
     if len(self.inner_table						) == 1:
      # We give a chance to update the column names at the first iteration
      for key in values.keys():
       if key not in columns:
        columns.append(_SCREAMING_SNAKE_CASE						)
      UpperCAmelCase	:					Optional[Any]	=	columns
     self.inner_table.append([values[c] for c in columns]						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE=None      ,     _SCREAMING_SNAKE_CASE=300						)  ->      List[Any]:





    '''simple docstring'''




    UpperCAmelCase	:					Tuple	=	NotebookProgressBar(_SCREAMING_SNAKE_CASE      ,     prefix=_SCREAMING_SNAKE_CASE      ,     parent=self      ,     width=_SCREAMING_SNAKE_CASE						)
    return self.child_bar




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





    '''simple docstring'''




    UpperCAmelCase	:					Tuple	=	None
    self.display()



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self						)  ->      Tuple:





    '''simple docstring'''




    UpperCAmelCase	:					List[Any]	=	None
    UpperCAmelCase	:					Any	=	None
    UpperCAmelCase	:					Any	=	False

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      List[Any]:





    '''simple docstring'''




    UpperCAmelCase	:					Dict	=	"""Epoch""" if args.evaluation_strategy == IntervalStrategy.EPOCH else """Step"""
    UpperCAmelCase	:					Optional[Any]	=	0
    UpperCAmelCase	:					Optional[int]	=	0
    UpperCAmelCase	:					int	=	[self.first_column] + ["""Training Loss"""]
    if args.evaluation_strategy != IntervalStrategy.NO:
     column_names.append("""Validation Loss"""						)
    UpperCAmelCase	:					int	=	NotebookTrainingTracker(state.max_steps      ,     _SCREAMING_SNAKE_CASE						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      int:





    '''simple docstring'''




    UpperCAmelCase	:					List[str]	=	int(state.epoch						) if int(state.epoch						) == state.epoch else F"{state.epoch:.2f}"
    self.training_tracker.update(
        state.global_step + 1      ,     comment=F"Epoch {epoch}/{state.num_train_epochs}"      ,     force_update=self._force_next_update      ,     )
    UpperCAmelCase	:					int	=	False

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE=None      ,     **_SCREAMING_SNAKE_CASE						)  ->      Optional[int]:





    '''simple docstring'''




    if not has_length(_SCREAMING_SNAKE_CASE						):
     return
    if self.prediction_bar is None:
     if self.training_tracker is not None:
      UpperCAmelCase	:					int	=	self.training_tracker.add_child(len(_SCREAMING_SNAKE_CASE						)						)
     else:
      UpperCAmelCase	:					Union[str, Any]	=	NotebookProgressBar(len(_SCREAMING_SNAKE_CASE						)						)
     self.prediction_bar.update(1						)
    else:
     self.prediction_bar.update(self.prediction_bar.value + 1						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      List[str]:





    '''simple docstring'''




    if self.prediction_bar is not None:
     self.prediction_bar.close()
    UpperCAmelCase	:					int	=	None

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE=None      ,     **_SCREAMING_SNAKE_CASE						)  ->      str:





    '''simple docstring'''




    if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
     UpperCAmelCase	:					List[Any]	=	{"""Training Loss""": logs["""loss"""]}
     # First column is necessarily Step sine we're not in epoch eval strategy
     UpperCAmelCase	:					Optional[Any]	=	state.global_step
     self.training_tracker.write_line(_SCREAMING_SNAKE_CASE						)

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE=None      ,     **_SCREAMING_SNAKE_CASE						)  ->      str:





    '''simple docstring'''




    if self.training_tracker is not None:
     UpperCAmelCase	:					Any	=	{"""Training Loss""": """No log""", """Validation Loss""": """No log"""}
     for log in reversed(state.log_history						):
      if "loss" in log:
       UpperCAmelCase	:					Optional[int]	=	log["""loss"""]
       break

     if self.first_column == "Epoch":
      UpperCAmelCase	:					Dict	=	int(state.epoch						)
     else:
      UpperCAmelCase	:					int	=	state.global_step
     UpperCAmelCase	:					Union[str, Any]	=	"""eval"""
     for k in metrics:
      if k.endswith("""_loss"""						):
       UpperCAmelCase	:					Optional[Any]	=	re.sub(r"""\_loss$"""      ,     """"""      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Tuple	=	metrics.pop("""total_flos"""      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Union[str, Any]	=	metrics.pop("""epoch"""      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Dict	=	metrics.pop(F"{metric_key_prefix}_runtime"      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Optional[int]	=	metrics.pop(F"{metric_key_prefix}_samples_per_second"      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					str	=	metrics.pop(F"{metric_key_prefix}_steps_per_second"      ,     _SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Optional[Any]	=	metrics.pop(F"{metric_key_prefix}_jit_compilation_time"      ,     _SCREAMING_SNAKE_CASE						)
     for k, v in metrics.items():
      if k == F"{metric_key_prefix}_loss":
       UpperCAmelCase	:					Tuple	=	v
      else:
       UpperCAmelCase	:					Union[str, Any]	=	k.split("""_"""						)
       UpperCAmelCase	:					List[str]	=	""" """.join([part.capitalize() for part in splits[1:]]						)
       UpperCAmelCase	:					List[str]	=	v
     self.training_tracker.write_line(_SCREAMING_SNAKE_CASE						)
     self.training_tracker.remove_child()
     UpperCAmelCase	:					Union[str, Any]	=	None
     # Evaluation takes a long time so we should force the next update.
     UpperCAmelCase	:					Union[str, Any]	=	True




   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE						)  ->      Tuple:





    '''simple docstring'''




    self.training_tracker.update(
        state.global_step      ,     comment=F"Epoch {int(state.epoch						)}/{state.num_train_epochs}"      ,     force_update=_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Optional[int]	=	None





'''simple docstring'''





from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
 from ..tf_utils import stable_softmax

_lowerCAmelCase      						=	logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE_     )
class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  def __init__(    self  ,**__UpperCAmelCase      )    ->		Tuple:
      super().__init__(**__UpperCAmelCase      )

      requires_backends(self  ,"""vision"""      )
      self.check_model_type(
          TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
          if self.framework == """tf"""
          else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING      )




  def __call__(    self  ,__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		str:
      return super().__call__(__UpperCAmelCase  ,**__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self  ,**__UpperCAmelCase      )    ->		str:
      lowerCAmelCase__ :  List[Any]							      =					{}
      if "candidate_labels" in kwargs:
          lowerCAmelCase__ :  int							      =					kwargs["""candidate_labels"""]
      if "hypothesis_template" in kwargs:
          lowerCAmelCase__ :  Optional[int]							      =					kwargs["""hypothesis_template"""]

      return preprocess_params, {}, {}




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=None  ,__UpperCAmelCase="This is a photo of {}."      )    ->		int:
      lowerCAmelCase__ :  str							      =					load_image(__UpperCAmelCase      )
      lowerCAmelCase__ :  Dict							      =					self.image_processor(images=[image]  ,return_tensors=self.framework      )
      lowerCAmelCase__ :  List[Any]							      =					candidate_labels
      lowerCAmelCase__ :  List[str]							      =					[hypothesis_template.format(__UpperCAmelCase      ) for x in candidate_labels]
      lowerCAmelCase__ :  Optional[Any]							      =					self.tokenizer(__UpperCAmelCase  ,return_tensors=self.framework  ,padding=__UpperCAmelCase      )
      lowerCAmelCase__ :  Tuple							      =					[text_inputs]
      return inputs




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Union[str, Any]:
      lowerCAmelCase__ :  Tuple							      =					model_inputs.pop("""candidate_labels"""      )
      lowerCAmelCase__ :  Union[str, Any]							      =					model_inputs.pop("""text_inputs"""      )
      if isinstance(text_inputs[0]  ,__UpperCAmelCase      ):
          lowerCAmelCase__ :  int							      =					text_inputs[0]
      else:
          # Batching case.
          lowerCAmelCase__ :  Dict							      =					text_inputs[0][0]

      lowerCAmelCase__ :  Any							      =					self.model(**__UpperCAmelCase  ,**__UpperCAmelCase      )

      lowerCAmelCase__ :  Union[str, Any]							      =					{
          """candidate_labels""": candidate_labels,
          """logits""": outputs.logits_per_image,
      }
      return model_outputs






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Any:
      lowerCAmelCase__ :  Union[str, Any]							      =					model_outputs.pop("""candidate_labels"""      )
      lowerCAmelCase__ :  List[str]							      =					model_outputs["""logits"""][0]
      if self.framework == "pt":
          lowerCAmelCase__ :  List[str]							      =					logits.softmax(dim=-1      ).squeeze(-1      )
          lowerCAmelCase__ :  Optional[Any]							      =					probs.tolist()
          if not isinstance(__UpperCAmelCase  ,__UpperCAmelCase      ):
              lowerCAmelCase__ :  Dict							      =					[scores]
      elif self.framework == "tf":
          lowerCAmelCase__ :  Any							      =					stable_softmax(__UpperCAmelCase  ,axis=-1      )
          lowerCAmelCase__ :  List[Any]							      =					probs.numpy().tolist()
      else:
          raise ValueError(F"""Unsupported framework: {self.framework}"""      )

      lowerCAmelCase__ :  Tuple							      =					[
          {"""score""": score, """label""": candidate_label}
          for score, candidate_label in sorted(zip(__UpperCAmelCase  ,__UpperCAmelCase      )  ,key=lambda __UpperCAmelCase      : -x[0]      )
      ]
      return result


