

'''simple docstring'''
from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder







@dataclass
class 							A__    (       A__  ):
  A__		 =				42







class 							A__    (       A__     ,   A__  ):
  A__		 =				True





  @register_to_config
  def __init__(		self      :	List[str]							,					_a      :	int = 3							,					_a      :	int = 3							,					_a      :	Tuple[str] = ("DownEncoderBlock2D",)							,					_a      :	Tuple[str] = ("UpDecoderBlock2D",)							,					_a      :	Tuple[int] = (64,)							,					_a      :	int = 1							,					_a      :	str = "silu"							,					_a      :	int = 4							,					_a      :	int = 32							,					_a      :	int = 32							,					_a      :	float = 0.1_82_15							,					)	->    Dict:





       '''simple docstring'''






       super().__init__()

       # pass init params to Encoder
       _SCREAMING_SNAKE_CASE							    =Encoder(
           in_channels=_a							,					out_channels=_a							,					down_block_types=_a							,					block_out_channels=_a							,					layers_per_block=_a							,					act_fn=_a							,					norm_num_groups=_a							,					double_z=_a							,					)

       # pass init params to Decoder
       _SCREAMING_SNAKE_CASE							    =Decoder(
           in_channels=_a							,					out_channels=_a							,					up_block_types=_a							,					block_out_channels=_a							,					layers_per_block=_a							,					norm_num_groups=_a							,					act_fn=_a							,					)

       _SCREAMING_SNAKE_CASE							    =nn.Convad(2 * latent_channels							,					2 * latent_channels							,					1 )
       _SCREAMING_SNAKE_CASE							    =nn.Convad(_a							,					_a							,					1 )

       _SCREAMING_SNAKE_CASE							    =False
       _SCREAMING_SNAKE_CASE							    =False

       # only relevant if vae tiling is enabled
       _SCREAMING_SNAKE_CASE							    =self.config.sample_size
       _SCREAMING_SNAKE_CASE							    =(
           self.config.sample_size[0]
           if isinstance(self.config.sample_size							,					(list, tuple) )
           else self.config.sample_size
       )
       _SCREAMING_SNAKE_CASE							    =int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) )
       _SCREAMING_SNAKE_CASE							    =0.25





  def 						A  (		self      :	Union[str, Any]							,					_a      :	Any							,					_a      :	List[str]=False )	->    Optional[int]:





       '''simple docstring'''






       if isinstance(_a							,					(Encoder, Decoder) ):
            _SCREAMING_SNAKE_CASE							    =value





  def 						A  (		self      :	Optional[Any]							,					_a      :	bool = True )	->    Optional[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =use_tiling





  def 						A  (		self      :	Optional[int] )	->    Tuple:





       '''simple docstring'''






       self.enable_tiling(_a )





  def 						A  (		self      :	List[str] )	->    Any:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =True





  def 						A  (		self      :	str )	->    str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =False





  @property
  # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
  def 						A  (		self      :	List[str] )	->    Dict[str, AttentionProcessor]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    ={}

       def fn_recursive_add_processors(_a      :	str							,					_a      :	torch.nn.Module							,					_a      :	Dict[str, AttentionProcessor] ):
            if hasattr(_a							,					'set_processor' ):
                 _SCREAMING_SNAKE_CASE							    =module.processor

            for sub_name, child in module.named_children():
                 fn_recursive_add_processors(f"{name}.{sub_name}"							,					_a							,					_a )

            return processors

       for name, module in self.named_children():
            fn_recursive_add_processors(_a							,					_a							,					_a )

       return processors





  def 						A  (		self      :	Any							,					_a      :	Union[AttentionProcessor, Dict[str, AttentionProcessor]] )	->    List[Any]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =len(self.attn_processors.keys() )

       if isinstance(_a							,					_a ) and len(_a ) != count:
            raise ValueError(
                f"A dict of processors was passed, but the number of processors {len(_a )} does not match the"
                f" number of attention layers: {count}. Please make sure to pass {count} processor classes." )

       def fn_recursive_attn_processor(_a      :	str							,					_a      :	torch.nn.Module							,					_a      :	Union[str, Any] ):
            if hasattr(_a							,					'set_processor' ):
                 if not isinstance(_a							,					_a ):
                      module.set_processor(_a )
                 else:
                      module.set_processor(processor.pop(f"{name}.processor" ) )

            for sub_name, child in module.named_children():
                 fn_recursive_attn_processor(f"{name}.{sub_name}"							,					_a							,					_a )

       for name, module in self.named_children():
            fn_recursive_attn_processor(_a							,					_a							,					_a )





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





       '''simple docstring'''






       self.set_attn_processor(AttnProcessor() )





  @apply_forward_hook
  def 						A  (		self      :	Optional[Any]							,					_a      :	torch.FloatTensor							,					_a      :	bool = True )	->    AutoencoderKLOutput:





       '''simple docstring'''






       if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
            return self.tiled_encode(_a							,					return_dict=_a )

       if self.use_slicing and x.shape[0] > 1:
            _SCREAMING_SNAKE_CASE							    =[self.encoder(_a ) for x_slice in x.split(1 )]
            _SCREAMING_SNAKE_CASE							    =torch.cat(_a )
       else:
            _SCREAMING_SNAKE_CASE							    =self.encoder(_a )

       _SCREAMING_SNAKE_CASE							    =self.quant_conv(_a )
       _SCREAMING_SNAKE_CASE							    =DiagonalGaussianDistribution(_a )

       if not return_dict:
            return (posterior,)

       return AutoencoderKLOutput(latent_dist=_a )





  def 						A  (		self      :	str							,					_a      :	torch.FloatTensor							,					_a      :	bool = True )	->    Union[DecoderOutput, torch.FloatTensor]:





       '''simple docstring'''






       if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
            return self.tiled_decode(_a							,					return_dict=_a )

       _SCREAMING_SNAKE_CASE							    =self.post_quant_conv(_a )
       _SCREAMING_SNAKE_CASE							    =self.decoder(_a )

       if not return_dict:
            return (dec,)

       return DecoderOutput(sample=_a )





  @apply_forward_hook
  def 						A  (		self      :	str							,					_a      :	torch.FloatTensor							,					_a      :	bool = True )	->    Union[DecoderOutput, torch.FloatTensor]:





       '''simple docstring'''






       if self.use_slicing and z.shape[0] > 1:
            _SCREAMING_SNAKE_CASE							    =[self._decode(_a ).sample for z_slice in z.split(1 )]
            _SCREAMING_SNAKE_CASE							    =torch.cat(_a )
       else:
            _SCREAMING_SNAKE_CASE							    =self._decode(_a ).sample

       if not return_dict:
            return (decoded,)

       return DecoderOutput(sample=_a )





  def 						A  (		self      :	Tuple							,					_a      :	Tuple							,					_a      :	int							,					_a      :	Optional[Any] )	->    str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =min(a.shape[2]							,					b.shape[2]							,					_a )
       for y in range(_a ):
            _SCREAMING_SNAKE_CASE							    =a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
       return b





  def 						A  (		self      :	Dict							,					_a      :	Union[str, Any]							,					_a      :	Optional[Any]							,					_a      :	Optional[Any] )	->    str:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =min(a.shape[3]							,					b.shape[3]							,					_a )
       for x in range(_a ):
            _SCREAMING_SNAKE_CASE							    =a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
       return b





  def 						A  (		self      :	Union[str, Any]							,					_a      :	torch.FloatTensor							,					_a      :	bool = True )	->    AutoencoderKLOutput:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) )
       _SCREAMING_SNAKE_CASE							    =int(self.tile_latent_min_size * self.tile_overlap_factor )
       _SCREAMING_SNAKE_CASE							    =self.tile_latent_min_size - blend_extent

       # Split the image into 512x512 tiles and encode them separately.
       _SCREAMING_SNAKE_CASE							    =[]
       for i in range(0							,					x.shape[2]							,					_a ):
            _SCREAMING_SNAKE_CASE							    =[]
            for j in range(0							,					x.shape[3]							,					_a ):
                 _SCREAMING_SNAKE_CASE							    =x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
                 _SCREAMING_SNAKE_CASE							    =self.encoder(_a )
                 _SCREAMING_SNAKE_CASE							    =self.quant_conv(_a )
                 row.append(_a )
            rows.append(_a )
       _SCREAMING_SNAKE_CASE							    =[]
       for i, row in enumerate(_a ):
            _SCREAMING_SNAKE_CASE							    =[]
            for j, tile in enumerate(_a ):
                 # blend the above tile and the left tile
                 # to the current tile and add the current tile to the result row
                 if i > 0:
                      _SCREAMING_SNAKE_CASE							    =self.blend_v(rows[i - 1][j]							,					_a							,					_a )
                 if j > 0:
                      _SCREAMING_SNAKE_CASE							    =self.blend_h(row[j - 1]							,					_a							,					_a )
                 result_row.append(tile[:, :, :row_limit, :row_limit] )
            result_rows.append(torch.cat(_a							,					dim=3 ) )

       _SCREAMING_SNAKE_CASE							    =torch.cat(_a							,					dim=2 )
       _SCREAMING_SNAKE_CASE							    =DiagonalGaussianDistribution(_a )

       if not return_dict:
            return (posterior,)

       return AutoencoderKLOutput(latent_dist=_a )





  def 						A  (		self      :	Optional[int]							,					_a      :	torch.FloatTensor							,					_a      :	bool = True )	->    Union[DecoderOutput, torch.FloatTensor]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) )
       _SCREAMING_SNAKE_CASE							    =int(self.tile_sample_min_size * self.tile_overlap_factor )
       _SCREAMING_SNAKE_CASE							    =self.tile_sample_min_size - blend_extent

       # Split z into overlapping 64x64 tiles and decode them separately.
       # The tiles have an overlap to avoid seams between tiles.
       _SCREAMING_SNAKE_CASE							    =[]
       for i in range(0							,					z.shape[2]							,					_a ):
            _SCREAMING_SNAKE_CASE							    =[]
            for j in range(0							,					z.shape[3]							,					_a ):
                 _SCREAMING_SNAKE_CASE							    =z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
                 _SCREAMING_SNAKE_CASE							    =self.post_quant_conv(_a )
                 _SCREAMING_SNAKE_CASE							    =self.decoder(_a )
                 row.append(_a )
            rows.append(_a )
       _SCREAMING_SNAKE_CASE							    =[]
       for i, row in enumerate(_a ):
            _SCREAMING_SNAKE_CASE							    =[]
            for j, tile in enumerate(_a ):
                 # blend the above tile and the left tile
                 # to the current tile and add the current tile to the result row
                 if i > 0:
                      _SCREAMING_SNAKE_CASE							    =self.blend_v(rows[i - 1][j]							,					_a							,					_a )
                 if j > 0:
                      _SCREAMING_SNAKE_CASE							    =self.blend_h(row[j - 1]							,					_a							,					_a )
                 result_row.append(tile[:, :, :row_limit, :row_limit] )
            result_rows.append(torch.cat(_a							,					dim=3 ) )

       _SCREAMING_SNAKE_CASE							    =torch.cat(_a							,					dim=2 )
       if not return_dict:
            return (dec,)

       return DecoderOutput(sample=_a )





  def 						A  (		self      :	Optional[int]							,					_a      :	torch.FloatTensor							,					_a      :	bool = False							,					_a      :	bool = True							,					_a      :	Optional[torch.Generator] = None							,					)	->    Union[DecoderOutput, torch.FloatTensor]:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =sample
       _SCREAMING_SNAKE_CASE							    =self.encode(_a ).latent_dist
       if sample_posterior:
            _SCREAMING_SNAKE_CASE							    =posterior.sample(generator=_a )
       else:
            _SCREAMING_SNAKE_CASE							    =posterior.mode()
       _SCREAMING_SNAKE_CASE							    =self.decode(_a ).sample

       if not return_dict:
            return (dec,)

       return DecoderOutput(sample=_a )



'''simple docstring'''
import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCamelCase :      List[Any]					 =     version.parse(importlib_metadata.version("nltk"))
if NLTK_VERSION >= version.Version("3.6.4"):
     from nltk import word_tokenize


lowerCamelCase :      Any					 =     "\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n"

lowerCamelCase :      Optional[Any]					 =     "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n"

lowerCamelCase :      Optional[Any]					 =     "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    'meteor': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric('meteor')\n    >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n    >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results[\"meteor\"], 4))\n    0.6944\n"







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,   _KWARGS_DESCRIPTION  )
class 							A__    (       datasets.Metric  ):





  def 						A  (		self      :	Tuple )	->    str:





       '''simple docstring'''






       return datasets.MetricInfo(
           description=_DESCRIPTION							,					citation=_CITATION							,					inputs_description=_KWARGS_DESCRIPTION							,					features=datasets.Features(
               {
                   'predictions': datasets.Value('string'							,					id='sequence' ),
                   'references': datasets.Value('string'							,					id='sequence' ),
               } )							,					codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py']							,					reference_urls=[
               'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score',
               'https://en.wikipedia.org/wiki/METEOR',
           ]							,					)





  def 						A  (		self      :	Union[str, Any]							,					_a      :	Union[str, Any] )	->    Optional[int]:





       '''simple docstring'''






       import nltk

       nltk.download('wordnet' )
       if NLTK_VERSION >= version.Version('3.6.5' ):
            nltk.download('punkt' )
       if NLTK_VERSION >= version.Version('3.6.6' ):
            nltk.download('omw-1.4' )





  def 						A  (		self      :	int							,					_a      :	Tuple							,					_a      :	List[str]							,					_a      :	List[str]=0.9							,					_a      :	Dict=3							,					_a      :	Optional[int]=0.5 )	->    Optional[int]:





       '''simple docstring'''






       if NLTK_VERSION >= version.Version('3.6.5' ):
            _SCREAMING_SNAKE_CASE							    =[
                meteor_score.single_meteor_score(
                    word_tokenize(_a )							,					word_tokenize(_a )							,					alpha=_a							,					beta=_a							,					gamma=_a )
                for ref, pred in zip(_a							,					_a )
            ]
       else:
            _SCREAMING_SNAKE_CASE							    =[
                meteor_score.single_meteor_score(_a							,					_a							,					alpha=_a							,					beta=_a							,					gamma=_a )
                for ref, pred in zip(_a							,					_a )
            ]

       return {"meteor": np.mean(_a )}
