

from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_UpperCAmelCase		:   Optional[int]										=       """\
@misc{wu2016googles,
      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""

_UpperCAmelCase		:   Union[str, Any]										=       """\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

_UpperCAmelCase		:   Any										=       """\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""







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




				def     a							(					self       ):
											return datasets.MetricInfo(
											    description=_DESCRIPTION      ,   citation=_CITATION      ,   inputs_description=_KWARGS_DESCRIPTION      ,   features=datasets.Features(
											        {
											            'predictions': datasets.Sequence(datasets.Value('string'      ,   id='token'       )      ,   id='sequence'       ),
											            'references': datasets.Sequence(
											                datasets.Sequence(datasets.Value('string'      ,   id='token'       )      ,   id='sequence'       )      ,   id='references'       ),
											        }       )      ,   )




				def     a							(					self      ,   snake_case      ,   snake_case      ,   snake_case = 1      ,   snake_case = 4      ,   ):
											return {
											    "google_bleu": gleu_score.corpus_gleu(
											        list_of_references=snake_case      ,   hypotheses=snake_case      ,   min_len=snake_case      ,   max_len=snake_case       )
											}







import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
					import tensorflow as tf

if is_torch_available():
					import torch


_UpperCAmelCase		:   Dict										=       logging.get_logger(__name__)







class  lowercase				:




				def __init__(					self      ,   snake_case = None      ,   snake_case = None      ,   snake_case=None      ,   snake_case=None       ):
											if not conversation_id:
																		snake_case_							=    uuid.uuida()
											if past_user_inputs is None:
																		snake_case_							=    []
											if generated_responses is None:
																		snake_case_							=    []

											snake_case_							=    conversation_id
											snake_case_							=    past_user_inputs
											snake_case_							=    generated_responses
											snake_case_							=    text




				def __eq__(					self      ,   snake_case       ):
											if not isinstance(snake_case      ,   snake_case       ):
																		return False
											if self.uuid == other.uuid:
																		return True
											return (
											    self.new_user_input == other.new_user_input
											    and self.past_user_inputs == other.past_user_inputs
											    and self.generated_responses == other.generated_responses
											)




				def     a							(					self      ,   snake_case      ,   snake_case = False       ):
											if self.new_user_input:
																		if overwrite:
																									logger.warning(
																									    F'''User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '''
																									    F'''with: "{text}".'''       )
																									snake_case_							=    text
																		else:
																									logger.warning(
																									    F'''User input added while unprocessed input was existing: "{self.new_user_input}" new input '''
																									    F'''ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input'''       )
											else:
																		snake_case_							=    text




				def     a							(					self       ):
											if self.new_user_input:
																		self.past_user_inputs.append(self.new_user_input       )
											snake_case_							=    None




				def     a							(					self      ,   snake_case       ):
											self.generated_responses.append(snake_case       )




				def     a							(					self       ):
											for user_input, generated_response in zip(self.past_user_inputs      ,   self.generated_responses       ):
																		yield True, user_input
																		yield False, generated_response
											if self.new_user_input:
																		yield True, self.new_user_input




				def __repr__(					self       ):
											snake_case_							=    F'''Conversation id: {self.uuid} \n'''
											for is_user, text in self.iter_texts():
																		snake_case_							=    'user' if is_user else 'bot'
																		output += F'''{name} >> {text} \n'''
											return output







@add_end_docstrings(
    lowercase_	,  R'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''	,  )
class  lowercase				(       lowercase_			):




				def __init__(					self      ,   *snake_case      ,   **snake_case       ):
											super().__init__(*snake_case      ,   **snake_case       )
											if self.tokenizer.pad_token_id is None:
																		snake_case_							=    self.tokenizer.eos_token




				def     a							(					self      ,   snake_case=None      ,   snake_case=None      ,   snake_case=None      ,   **snake_case       ):
											snake_case_							=    {}
											snake_case_							=    {}
											snake_case_							=    {}

											if min_length_for_response is not None:
																		snake_case_							=    min_length_for_response
											if minimum_tokens is not None:
																		snake_case_							=    minimum_tokens

											if "max_length" in generate_kwargs:
																		snake_case_							=    generate_kwargs['max_length']
																		# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
											if clean_up_tokenization_spaces is not None:
																		snake_case_							=    clean_up_tokenization_spaces

											if generate_kwargs:
																		forward_params.update(snake_case       )
											return preprocess_params, forward_params, postprocess_params




				def __call__(					self      ,   snake_case      ,   snake_case=0      ,   **snake_case       ):
											snake_case_							=    super().__call__(snake_case      ,   num_workers=snake_case      ,   **snake_case       )
											if isinstance(snake_case      ,   snake_case       ) and len(snake_case       ) == 1:
																		return outputs[0]
											return outputs




				def     a							(					self      ,   snake_case      ,   snake_case=32       ):
											if not isinstance(snake_case      ,   snake_case       ):
																		raise ValueError('ConversationalPipeline, expects Conversation as inputs'       )
											if conversation.new_user_input is None:
																		raise ValueError(
																		    F'''Conversation with UUID {type(conversation.uuid       )} does not contain new user input to process. '''
																		    'Add user inputs with the conversation\'s `add_user_input` method'       )
											if hasattr(self.tokenizer      ,   '_build_conversation_input_ids'       ):
																		snake_case_							=    self.tokenizer._build_conversation_input_ids(snake_case       )
											else:
																		# If the tokenizer cannot handle conversations, we default to only the old version
																		snake_case_							=    self._legacy_parse_and_tokenize(snake_case       )

											if self.framework == "pt":
																		snake_case_							=    torch.LongTensor([input_ids]       )
											elif self.framework == "tf":
																		snake_case_							=    tf.constant([input_ids]       )
											return {"input_ids": input_ids, "conversation": conversation}




				def     a							(					self      ,   snake_case      ,   snake_case=10      ,   **snake_case       ):
											snake_case_							=    generate_kwargs.get('max_length'      ,   self.model.config.max_length       )

											snake_case_							=    model_inputs['input_ids'].shape[1]
											if max_length - minimum_tokens < n:
																		logger.warning(F'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})'''       )
																		snake_case_							=    max_length - minimum_tokens
																		snake_case_							=    model_inputs['input_ids'][:, -trim:]
																		if "attention_mask" in model_inputs:
																									snake_case_							=    model_inputs['attention_mask'][:, -trim:]
											snake_case_							=    model_inputs.pop('conversation'       )
											snake_case_							=    max_length
											snake_case_							=    self.model.generate(**snake_case      ,   **snake_case       )
											if self.model.config.is_encoder_decoder:
																		snake_case_							=    1
											else:
																		snake_case_							=    n
											return {"output_ids": output_ids[:, start_position:], "conversation": conversation}




				def     a							(					self      ,   snake_case      ,   snake_case=True       ):
											snake_case_							=    model_outputs['output_ids']
											snake_case_							=    self.tokenizer.decode(
											    output_ids[0]      ,   skip_special_tokens=snake_case      ,   clean_up_tokenization_spaces=snake_case      ,   )
											snake_case_							=    model_outputs['conversation']
											conversation.mark_processed()
											conversation.append_response(snake_case       )
											return conversation




				def     a							(					self      ,   snake_case       ):
											snake_case_							=    self.tokenizer.eos_token_id
											snake_case_							=    []
											for is_user, text in conversation.iter_texts():
																		if eos_token_id is not None:
																									input_ids.extend(self.tokenizer.encode(snake_case      ,   add_special_tokens=snake_case       ) + [eos_token_id]       )
																		else:
																									input_ids.extend(self.tokenizer.encode(snake_case      ,   add_special_tokens=snake_case       )       )

											if len(snake_case       ) > self.tokenizer.model_max_length:
																		snake_case_							=    input_ids[-self.tokenizer.model_max_length :]
											return input_ids




