






"""simple docstring"""






from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


UpperCAmelCase_     :				Union[str, Any]         =				logging.get_logger(__name__)




class 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      def _SCREAMING_SNAKE_CASE				(		self  :						str		,			lowercase_  :						List[str]):




          '''simple docstring'''


          if isinstance(lowercase_		,			lowercase_):
              SCREAMING_SNAKE_CASE_   :						List[str]							=	[label.strip() for label in labels.split(''',''') if label.strip()]
          return labels



      def __call__(		self  :						Optional[Any]		,			lowercase_  :						Any		,			lowercase_  :						Optional[Any]		,			lowercase_  :						str):




          '''simple docstring'''


          if len(lowercase_) == 0 or len(lowercase_) == 0:
              raise ValueError('''You must include at least one label and at least one sequence.''')
          if hypothesis_template.format(labels[0]) == hypothesis_template:
              raise ValueError(
                  (
                      '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. '''
                      '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.'''
                  ).format(lowercase_))

          if isinstance(lowercase_		,			lowercase_):
              SCREAMING_SNAKE_CASE_   :						Dict							=	[sequences]

          SCREAMING_SNAKE_CASE_   :						int							=	[]
          for sequence in sequences:
              sequence_pairs.extend([[sequence, hypothesis_template.format(lowercase_)] for label in labels])

          return sequence_pairs, sequences




@add_end_docstrings(UpperCAmelCase__				)
class 							lowerCAmelCase__       (    UpperCAmelCase__				):






      '''simple docstring'''

      def __init__(		self  :						Optional[Any]		,			lowercase_  :						Dict=ZeroShotClassificationArgumentHandler()		,			*lowercase_  :						List[str]		,			**lowercase_  :						Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	args_parser
          super().__init__(*lowercase_		,			**lowercase_)
          if self.entailment_id == -1:
              logger.warning(
                  '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to '''
                  '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.''')
      @property
      def _SCREAMING_SNAKE_CASE				(		self  :						Optional[int]):




          '''simple docstring'''


          for label, ind in self.model.config.labelaid.items():
              if label.lower().startswith('''entail'''):
                  return ind
          return -1
      def _SCREAMING_SNAKE_CASE				(		self  :						List[Any]		,			lowercase_  :						Optional[Any]		,			lowercase_  :						List[str]=True		,			lowercase_  :						Tuple=True		,			lowercase_  :						str=TruncationStrategy.ONLY_FIRST		,			**lowercase_  :						str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	self.framework
          if self.tokenizer.pad_token is None:
              # Override for tokenizers not supporting padding
              logger.error(
                  '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use '''
                  ''' `pad_token=eos_token`''')
              SCREAMING_SNAKE_CASE_   :						int							=	self.tokenizer.eos_token
          try:
              SCREAMING_SNAKE_CASE_   :						Tuple							=	self.tokenizer(
                  lowercase_		,			add_special_tokens=lowercase_		,			return_tensors=lowercase_		,			padding=lowercase_		,			truncation=lowercase_		,			)
          except Exception as e:
              if "too short" in str(lowercase_):
                  # tokenizers might yell that we want to truncate
                  # to a value that is not even reached by the input.
                  # In that case we don't want to truncate.
                  # It seems there's not a really better way to catch that
                  # exception.

                  SCREAMING_SNAKE_CASE_   :						List[str]							=	self.tokenizer(
                      lowercase_		,			add_special_tokens=lowercase_		,			return_tensors=lowercase_		,			padding=lowercase_		,			truncation=TruncationStrategy.DO_NOT_TRUNCATE		,			)
              else:
                  raise e

          return inputs
      def _SCREAMING_SNAKE_CASE				(		self  :						Union[str, Any]		,			**lowercase_  :						str):




          '''simple docstring'''


          if kwargs.get('''multi_class'''		,			lowercase_) is not None:
              SCREAMING_SNAKE_CASE_   :						Tuple							=	kwargs['''multi_class''']
              logger.warning(
                  '''The `multi_class` argument has been deprecated and renamed to `multi_label`. '''
                  '''`multi_class` will be removed in a future version of Transformers.''')
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	{}
          if "candidate_labels" in kwargs:
              SCREAMING_SNAKE_CASE_   :						List[str]							=	self._args_parser._parse_labels(kwargs['''candidate_labels'''])
          if "hypothesis_template" in kwargs:
              SCREAMING_SNAKE_CASE_   :						str							=	kwargs['''hypothesis_template''']

          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	{}
          if "multi_label" in kwargs:
              SCREAMING_SNAKE_CASE_   :						int							=	kwargs['''multi_label''']
          return preprocess_params, {}, postprocess_params
      def __call__(		self  :						Tuple		,			lowercase_  :						Union[str, List[str]]		,			*lowercase_  :						Tuple		,			**lowercase_  :						int		,			):




          '''simple docstring'''


          if len(lowercase_) == 0:
              pass
          elif len(lowercase_) == 1 and "candidate_labels" not in kwargs:
              SCREAMING_SNAKE_CASE_   :						Optional[int]							=	args[0]
          else:
              raise ValueError(F'Unable to understand extra arguments {args}')

          return super().__call__(lowercase_		,			**lowercase_)
      def _SCREAMING_SNAKE_CASE				(		self  :						Dict		,			lowercase_  :						Optional[Any]		,			lowercase_  :						Any=None		,			lowercase_  :						Optional[int]="This example is {}."):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_   :						Optional[int]							=	self._args_parser(lowercase_		,			lowercase_		,			lowercase_)

          for i, (candidate_label, sequence_pair) in enumerate(zip(lowercase_		,			lowercase_)):
              SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	self._parse_and_tokenize([sequence_pair])

              yield {
                  "candidate_label": candidate_label,
                  "sequence": sequences[0],
                  "is_last": i == len(lowercase_) - 1,
                  **model_input,
              }
      def _SCREAMING_SNAKE_CASE				(		self  :						Dict		,			lowercase_  :						Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						str							=	inputs['''candidate_label''']
          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	inputs['''sequence''']
          SCREAMING_SNAKE_CASE_   :						int							=	{k: inputs[k] for k in self.tokenizer.model_input_names}
          SCREAMING_SNAKE_CASE_   :						str							=	self.model(**lowercase_)

          SCREAMING_SNAKE_CASE_   :						Tuple							=	{
              '''candidate_label''': candidate_label,
              '''sequence''': sequence,
              '''is_last''': inputs['''is_last'''],
              **outputs,
          }
          return model_outputs



      def _SCREAMING_SNAKE_CASE				(		self  :						Optional[int]		,			lowercase_  :						Union[str, Any]		,			lowercase_  :						str=False):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_   :						List[Any]							=	[outputs['''candidate_label'''] for outputs in model_outputs]
          SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	[outputs['''sequence'''] for outputs in model_outputs]
          SCREAMING_SNAKE_CASE_   :						Dict							=	np.concatenate([output['''logits'''].numpy() for output in model_outputs])
          SCREAMING_SNAKE_CASE_   :						Tuple							=	logits.shape[0]
          SCREAMING_SNAKE_CASE_   :						int							=	len(lowercase_)
          SCREAMING_SNAKE_CASE_   :						str							=	N // n
          SCREAMING_SNAKE_CASE_   :						str							=	logits.reshape((num_sequences, n, -1))

          if multi_label or len(lowercase_) == 1:
              # softmax over the entailment vs. contradiction dim for each label independently
              SCREAMING_SNAKE_CASE_   :						int							=	self.entailment_id
              SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	-1 if entailment_id == 0 else 0
              SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	reshaped_outputs[..., [contradiction_id, entailment_id]]
              SCREAMING_SNAKE_CASE_   :						List[str]							=	np.exp(lowercase_) / np.exp(lowercase_).sum(-1		,			keepdims=lowercase_)
              SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	scores[..., 1]
          else:
              # softmax the "entailment" logits over all candidate labels
              SCREAMING_SNAKE_CASE_   :						int							=	reshaped_outputs[..., self.entailment_id]
              SCREAMING_SNAKE_CASE_   :						Union[str, Any]							=	np.exp(lowercase_) / np.exp(lowercase_).sum(-1		,			keepdims=lowercase_)

          SCREAMING_SNAKE_CASE_   :						Optional[Any]							=	list(reversed(scores[0].argsort()))
          return {
              "sequence": sequences[0],
              "labels": [candidate_labels[i] for i in top_inds],
              "scores": scores[0, top_inds].tolist(),
          }










"""simple docstring"""






from __future__ import annotations

import requests



def       _A    (__a							)				-> dict:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Any							=	f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty'
    return requests.get(__a							).json()



def       _A    (__a = 10							)				-> list[dict]:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Any							=	'''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'''
    SCREAMING_SNAKE_CASE_   :						Dict							=	requests.get(__a							).json()[:max_stories]
    return [get_hackernews_story(__a							) for story_id in story_ids]



def       _A    (__a = 10							)				-> str:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_   :						Tuple							=	hackernews_top_stories(__a							)
    return "\n".join('''* [{title}]({url})'''.format(**__a							) for story in stories							)


if __name__ == "__main__":
  print(hackernews_top_stories_as_markdown())


