
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 		UpperCamelCase	(      lowercase_   )		->	str:


  '''simple docstring'''






  lowercase__  :   Any    		=      int(lowercase_   )
  lowercase__		,    lowercase__		,    lowercase__  :   List[str]    		=      t // 36_00, (t // 60) % 60, t % 60
  return F'{h}:{m:02d}:{s:02d}' if h != 0 else F'{m:02d}:{s:02d}'

def 		UpperCamelCase	(      lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_=3_00   )		->	Optional[Any]:


  '''simple docstring'''






  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 		UpperCamelCase	(      lowercase_   )		->	Tuple:


  '''simple docstring'''






  lowercase__  :   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:
      lowercase__  :   Any    		=      F'{elt:.6f}' if isinstance(lowercase_ , lowercase_   ) else str(lowercase_   )
      html_code += F'      <td>{elt}</td>\n'
    html_code += "    </tr>\n"
  html_code += "  </tbody>\n</table><p>"
  return html_code



class       _snake_case   :
 __lowerCAmelCase  :     Tuple        =			5
 __lowerCAmelCase  :     int        =			0.2


 def __init__(					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_ = None					,  SCREAMING_SNAKE_CASE_ = True					,  SCREAMING_SNAKE_CASE_ = None					,  SCREAMING_SNAKE_CASE_ = 3_00					,  ):


   '''simple docstring'''




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


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_ = False					,  SCREAMING_SNAKE_CASE_ = None):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      value
   if comment is not None:
     lowercase__  :   List[str]    		=      comment
   if self.last_value is None:
     lowercase__  :   Tuple    		=      time.time()
     lowercase__  :   Optional[int]    		=      value
     lowercase__  :   Union[str, Any]    		=      None
     lowercase__  :   Tuple    		=      self.warmup
     lowercase__  :   Union[str, 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
     lowercase__  :   Dict    		=      time.time()
     lowercase__  :   Any    		=      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:
       lowercase__  :   List[Any]    		=      self.elapsed_time / (value - self.start_value)
     else:
       lowercase__  :   Optional[Any]    		=      None
     if value >= self.total:
       lowercase__  :   Any    		=      self.total
       lowercase__  :   Dict    		=      None
       if not self.leave:
         self.close()
     elif self.average_time_per_item is not None:
       lowercase__  :   Dict    		=      self.average_time_per_item * (self.total - value)
     self.update_bar(SCREAMING_SNAKE_CASE_)
     lowercase__  :   List[Any]    		=      value
     lowercase__  :   List[str]    		=      current_time
     if self.average_time_per_item is None:
       lowercase__  :   Any    		=      1
     else:
       lowercase__  :   List[str]    		=      max(int(self.update_every / self.average_time_per_item)					,  1)


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=None):


   '''simple docstring'''




   lowercase__  :   Dict    		=      """ """ * (len(str(self.total)) - len(str(SCREAMING_SNAKE_CASE_))) + str(SCREAMING_SNAKE_CASE_)
   if self.elapsed_time is None:
     lowercase__  :   Dict    		=      f'[{spaced_value}/{self.total} : < :'
   elif self.predicted_remaining is None:
     lowercase__  :   Tuple    		=      f'[{spaced_value}/{self.total} {format_time(self.elapsed_time)}'
   else:
     lowercase__  :   Optional[Any]    		=      (
         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      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   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:
     lowercase__  :   Optional[int]    		=      disp.display(disp.HTML(self.html_code)					,  display_id=SCREAMING_SNAKE_CASE_)
   else:
     self.output.update(disp.HTML(self.html_code))



 def      lowercase__     (					self):


   '''simple docstring'''




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



class       _snake_case   (	UpperCAmelCase_							):


 def __init__(					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=None):


   '''simple docstring'''




   super().__init__(SCREAMING_SNAKE_CASE_)
   lowercase__  :   Any    		=      None if column_names is None else [column_names]
   lowercase__  :   Optional[Any]    		=      None


 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   str    		=      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:
     lowercase__  :   Tuple    		=      disp.display(disp.HTML(self.html_code)					,  display_id=SCREAMING_SNAKE_CASE_)
   else:
     self.output.update(disp.HTML(self.html_code))


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if self.inner_table is None:
     lowercase__  :   Tuple    		=      [list(values.keys()), list(values.values())]
   else:
     lowercase__  :   Tuple    		=      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_)
       lowercase__  :   Optional[int]    		=      columns
     self.inner_table.append([values[c] for c in columns])


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=None					,  SCREAMING_SNAKE_CASE_=3_00):


   '''simple docstring'''




   lowercase__  :   int    		=      NotebookProgressBar(SCREAMING_SNAKE_CASE_					,  prefix=SCREAMING_SNAKE_CASE_					,  parent=self					,  width=SCREAMING_SNAKE_CASE_)
   return self.child_bar



 def      lowercase__     (					self):


   '''simple docstring'''




   lowercase__  :   Optional[int]    		=      None
   self.display()



class       _snake_case   (	UpperCAmelCase_							):


 def __init__(					self):


   '''simple docstring'''




   lowercase__  :   List[Any]    		=      None
   lowercase__  :   Union[str, Any]    		=      None
   lowercase__  :   str    		=      False


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




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


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Any    		=      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					,  )
   lowercase__  :   Union[str, Any]    		=      False


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=None					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if not has_length(SCREAMING_SNAKE_CASE_):
     return
   if self.prediction_bar is None:
     if self.training_tracker is not None:
       lowercase__  :   int    		=      self.training_tracker.add_child(len(SCREAMING_SNAKE_CASE_))
     else:
       lowercase__  :   Any    		=      NotebookProgressBar(len(SCREAMING_SNAKE_CASE_))
     self.prediction_bar.update(1)
   else:
     self.prediction_bar.update(self.prediction_bar.value + 1)


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   if self.prediction_bar is not None:
     self.prediction_bar.close()
   lowercase__  :   Tuple    		=      None


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=None					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




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


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_=None					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




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

     if self.first_column == "Epoch":
       lowercase__  :   Optional[int]    		=      int(state.epoch)
     else:
       lowercase__  :   Union[str, Any]    		=      state.global_step
     lowercase__  :   Optional[Any]    		=      """eval"""
     for k in metrics:
       if k.endswith("""_loss"""):
         lowercase__  :   str    		=      re.sub(R"""\_loss$"""					,  """"""					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   List[Any]    		=      metrics.pop("""total_flos"""					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   List[str]    		=      metrics.pop("""epoch"""					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   List[Any]    		=      metrics.pop(f'{metric_key_prefix}_runtime'					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   Tuple    		=      metrics.pop(f'{metric_key_prefix}_samples_per_second'					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   Optional[Any]    		=      metrics.pop(f'{metric_key_prefix}_steps_per_second'					,  SCREAMING_SNAKE_CASE_)
     lowercase__  :   List[str]    		=      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':
         lowercase__  :   Union[str, Any]    		=      v
       else:
         lowercase__  :   List[str]    		=      k.split("""_""")
         lowercase__  :   Tuple    		=      """ """.join([part.capitalize() for part in splits[1:]])
         lowercase__  :   Any    		=      v
     self.training_tracker.write_line(SCREAMING_SNAKE_CASE_)
     self.training_tracker.remove_child()
     lowercase__  :   Optional[int]    		=      None
     # Evaluation takes a long time so we should force the next update.
     lowercase__  :   Optional[Any]    		=      True



 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   self.training_tracker.update(
       state.global_step					,  comment=f'Epoch {int(state.epoch)}/{state.num_train_epochs}'					,  force_update=SCREAMING_SNAKE_CASE_)
   lowercase__  :   str    		=      None








# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

import torch

from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
     from PIL import Image



class       _snake_case   (	UpperCAmelCase_							):
 __lowerCAmelCase  :     Any        =			'dandelin/vilt-b32-finetuned-vqa'
 __lowerCAmelCase  :     Union[str, Any]        =			(
     'This is a tool that answers a question about an image. It takes an input named `image` which should be the '
     'image containing the information, as well as a `question` which should be the question in English. It '
     'returns a text that is the answer to the question.'
 )
 __lowerCAmelCase  :     str        =			'image_qa'
 __lowerCAmelCase  :     int        =			AutoProcessor
 __lowerCAmelCase  :     Optional[Any]        =			AutoModelForVisualQuestionAnswering

 __lowerCAmelCase  :     str        =			['image', 'text']
 __lowerCAmelCase  :     Optional[int]        =			['text']


 def __init__(					self					,  *SCREAMING_SNAKE_CASE_					,  **SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   requires_backends(self					,  ["""vision"""])
   super().__init__(*SCREAMING_SNAKE_CASE_					,  **SCREAMING_SNAKE_CASE_)


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   return self.pre_processor(SCREAMING_SNAKE_CASE_					,  SCREAMING_SNAKE_CASE_					,  return_tensors="""pt""")


 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   with torch.no_grad():
     return self.model(**SCREAMING_SNAKE_CASE_).logits



 def      lowercase__     (					self					,  SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__  :   Dict    		=      outputs.argmax(-1).item()
   return self.model.config.idalabel[idx]






