


'''simple docstring'''


from typing import Dict

import numpy as np

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


if is_tf_available():
						import tensorflow as tf

						from ..tf_utils import stable_softmax


if is_torch_available():
						import torch


lowerCamelCase__					=   logging.get_logger(__name__)






@add_end_docstrings(
    UpperCAmelCase__			,				R"\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    "			,				)
class 		lowerCAmelCase__	(	UpperCAmelCase__		):




			def 							lowerCAmelCase__			(						self     :   Optional[int]		,     lowerCamelCase__     :   GenericTensor       )      ->np.ndarray:



					'''simple docstring'''







					if self.framework == "tf":
							_UpperCAmelCase						:				Any	    =					tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
					elif self.framework == "pt":
							_UpperCAmelCase						:				str	    =					torch.nonzero(input_ids == self.tokenizer.mask_token_id		,     as_tuple=lowerCamelCase__       )
					else:
							raise ValueError("Unsupported framework"       )
					return masked_index




			def 							lowerCAmelCase__			(						self     :   Union[str, Any]		,     lowerCamelCase__     :   GenericTensor       )      ->np.ndarray:



					'''simple docstring'''







					_UpperCAmelCase						:				str	    =					self.get_masked_index(lowerCamelCase__       )
					_UpperCAmelCase						:				int	    =					np.prod(masked_index.shape       )
					if numel < 1:
							raise PipelineException(
							    "fill-mask"		,     self.model.base_model_prefix		,     F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""		,     )




			def 							lowerCAmelCase__			(						self     :   str		,     lowerCamelCase__     :   GenericTensor       )      ->int:



					'''simple docstring'''







					if isinstance(lowerCamelCase__		,     lowerCamelCase__       ):
							for model_input in model_inputs:
									self._ensure_exactly_one_mask_token(model_input["input_ids"][0]       )
					else:
							for input_ids in model_inputs["input_ids"]:
									self._ensure_exactly_one_mask_token(lowerCamelCase__       )




			def 							lowerCAmelCase__			(						self     :   Any		,     lowerCamelCase__     :   List[str]		,     lowerCamelCase__     :   int=None		,     **lowerCamelCase__     :   Optional[int]       )      ->Dict[str, GenericTensor]:



					'''simple docstring'''







					if return_tensors is None:
							_UpperCAmelCase						:				List[str]	    =					self.framework
					_UpperCAmelCase						:				Tuple	    =					self.tokenizer(lowerCamelCase__		,     return_tensors=lowerCamelCase__       )
					self.ensure_exactly_one_mask_token(lowerCamelCase__       )
					return model_inputs




			def 							lowerCAmelCase__			(						self     :   str		,     lowerCamelCase__     :   Tuple       )      ->Dict:



					'''simple docstring'''







					_UpperCAmelCase						:				Optional[Any]	    =					self.model(**lowerCamelCase__       )
					_UpperCAmelCase						:				str	    =					model_inputs["input_ids"]
					return model_outputs




			def 							lowerCAmelCase__			(						self     :   int		,     lowerCamelCase__     :   Tuple		,     lowerCamelCase__     :   Optional[Any]=5		,     lowerCamelCase__     :   str=None       )      ->Optional[Any]:



					'''simple docstring'''







					if target_ids is not None and target_ids.shape[0] < top_k:
							_UpperCAmelCase						:				List[Any]	    =					target_ids.shape[0]
					_UpperCAmelCase						:				Union[str, Any]	    =					model_outputs["input_ids"][0]
					_UpperCAmelCase						:				Tuple	    =					model_outputs["logits"]

					if self.framework == "tf":
							_UpperCAmelCase						:				str	    =					tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()[:, 0]

							_UpperCAmelCase						:				List[str]	    =					outputs.numpy()

							_UpperCAmelCase						:				str	    =					outputs[0, masked_index, :]
							_UpperCAmelCase						:				str	    =					stable_softmax(lowerCamelCase__		,     axis=-1       )
							if target_ids is not None:
									_UpperCAmelCase						:				Optional[Any]	    =					tf.gather_nd(tf.squeeze(lowerCamelCase__		,     0       )		,     target_ids.reshape(-1		,     1       )       )
									_UpperCAmelCase						:				int	    =					tf.expand_dims(lowerCamelCase__		,     0       )

							_UpperCAmelCase						:				str	    =					tf.math.top_k(lowerCamelCase__		,     k=lowerCamelCase__       )
							_UpperCAmelCase    ,			_UpperCAmelCase						:				List[Any]	    =					topk.values.numpy(), topk.indices.numpy()
					else:
							_UpperCAmelCase						:				List[str]	    =					torch.nonzero(input_ids == self.tokenizer.mask_token_id		,     as_tuple=lowerCamelCase__       ).squeeze(-1       )
							# Fill mask pipeline supports only one ${mask_token} per sample

							_UpperCAmelCase						:				Tuple	    =					outputs[0, masked_index, :]
							_UpperCAmelCase						:				List[str]	    =					logits.softmax(dim=-1       )
							if target_ids is not None:
									_UpperCAmelCase						:				List[Any]	    =					probs[..., target_ids]

							_UpperCAmelCase    ,			_UpperCAmelCase						:				Optional[Any]	    =					probs.topk(lowerCamelCase__       )

					_UpperCAmelCase						:				str	    =					[]
					_UpperCAmelCase						:				List[Any]	    =					values.shape[0] == 1
					for i, (_values, _predictions) in enumerate(zip(values.tolist()		,     predictions.tolist()       )       ):
							_UpperCAmelCase						:				Union[str, Any]	    =					[]
							for v, p in zip(_values		,     _predictions       ):
									# Copy is important since we're going to modify this array in place
									_UpperCAmelCase						:				Any	    =					input_ids.numpy().copy()
									if target_ids is not None:
											_UpperCAmelCase						:				List[Any]	    =					target_ids[p].tolist()

									_UpperCAmelCase						:				Union[str, Any]	    =					p
									# Filter padding out:
									_UpperCAmelCase						:				Union[str, Any]	    =					tokens[np.where(tokens != self.tokenizer.pad_token_id       )]
									# Originally we skip special tokens to give readable output.
									# For multi masks though, the other [MASK] would be removed otherwise
									# making the output look odd, so we add them back
									_UpperCAmelCase						:				Optional[int]	    =					self.tokenizer.decode(lowerCamelCase__		,     skip_special_tokens=lowerCamelCase__       )
									_UpperCAmelCase						:				List[str]	    =					{"score": v, "token": p, "token_str": self.tokenizer.decode([p]       ), "sequence": sequence}
									row.append(lowerCamelCase__       )
							result.append(lowerCamelCase__       )
					if single_mask:
							return result[0]
					return result




			def 							lowerCAmelCase__			(						self     :   Dict		,     lowerCamelCase__     :   int		,     lowerCamelCase__     :   Dict=None       )      ->Dict:



					'''simple docstring'''







					if isinstance(lowerCamelCase__		,     lowerCamelCase__       ):
							_UpperCAmelCase						:				Union[str, Any]	    =					[targets]
					try:
							_UpperCAmelCase						:				Union[str, Any]	    =					self.tokenizer.get_vocab()
					except Exception:
							_UpperCAmelCase						:				List[str]	    =					{}
					_UpperCAmelCase						:				Tuple	    =					[]
					for target in targets:
							_UpperCAmelCase						:				Optional[Any]	    =					vocab.get(lowerCamelCase__		,     lowerCamelCase__       )
							if id_ is None:
									_UpperCAmelCase						:				List[str]	    =					self.tokenizer(
									    lowerCamelCase__		,     add_special_tokens=lowerCamelCase__		,     return_attention_mask=lowerCamelCase__		,     return_token_type_ids=lowerCamelCase__		,     max_length=1		,     truncation=lowerCamelCase__		,     )["input_ids"]
									if len(lowerCamelCase__       ) == 0:
											logger.warning(
											    F"""The specified target token `{target}` does not exist in the model vocabulary. """
											    "We cannot replace it with anything meaningful, ignoring it"       )
											continue
									_UpperCAmelCase						:				Optional[Any]	    =					input_ids[0]
									# XXX: If users encounter this pass
									# it becomes pretty slow, so let's make sure
									# The warning enables them to fix the input to
									# get faster performance.
									logger.warning(
									    F"""The specified target token `{target}` does not exist in the model vocabulary. """
									    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_       )}`."""       )
							target_ids.append(id_       )
					_UpperCAmelCase						:				List[str]	    =					list(set(lowerCamelCase__       )       )
					if len(lowerCamelCase__       ) == 0:
							raise ValueError("At least one target must be provided when passed."       )
					_UpperCAmelCase						:				Dict	    =					np.array(lowerCamelCase__       )
					return target_ids




			def 							lowerCAmelCase__			(						self     :   List[Any]		,     lowerCamelCase__     :   Any=None		,     lowerCamelCase__     :   Optional[int]=None       )      ->Union[str, Any]:



					'''simple docstring'''







					_UpperCAmelCase						:				int	    =					{}

					if targets is not None:
							_UpperCAmelCase						:				List[Any]	    =					self.get_target_ids(lowerCamelCase__		,     lowerCamelCase__       )
							_UpperCAmelCase						:				Tuple	    =					target_ids

					if top_k is not None:
							_UpperCAmelCase						:				List[Any]	    =					top_k

					if self.tokenizer.mask_token_id is None:
							raise PipelineException(
							    "fill-mask"		,     self.model.base_model_prefix		,     "The tokenizer does not define a `mask_token`."       )
					return {}, {}, postprocess_params






			def __call__(						self     :   List[Any]		,     lowerCamelCase__     :   int		,     *lowerCamelCase__     :   List[str]		,     **lowerCamelCase__     :   Union[str, Any]       )      ->Union[str, Any]:



					'''simple docstring'''







					_UpperCAmelCase						:				Any	    =					super().__call__(lowerCamelCase__		,     **lowerCamelCase__       )
					if isinstance(lowerCamelCase__		,     lowerCamelCase__       ) and len(lowerCamelCase__       ) == 1:
							return outputs[0]
					return outputs







'''simple docstring'''


from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

lowerCamelCase__					=   {'UserAgent': UserAgent().random}






def        __lowerCAmelCase       (__lowerCAmelCase      ):
		_UpperCAmelCase						:				List[str]	    =					script.contents[0]
		_UpperCAmelCase						:				Any	    =					json.loads(data[data.find("{\"config\""      ) : -1]      )
		return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]






class 		lowerCAmelCase__	:




			def __init__(						self     :   str		,     lowerCamelCase__     :   List[Any]       )      ->List[str]:



					'''simple docstring'''







					_UpperCAmelCase						:				List[Any]	    =					F"""https://www.instagram.com/{username}/"""
					_UpperCAmelCase						:				Dict	    =					self.get_json()




			def 							lowerCAmelCase__			(						self     :   Any       )      ->dict:



					'''simple docstring'''







					_UpperCAmelCase						:				Optional[int]	    =					requests.get(self.url		,     headers=lowerCamelCase__       ).text
					_UpperCAmelCase						:				Any	    =					BeautifulSoup(lowerCamelCase__		,     "html.parser"       ).find_all("script"       )
					try:
							return extract_user_profile(scripts[4]       )
					except (json.decoder.JSONDecodeError, KeyError):
							return extract_user_profile(scripts[3]       )




			def __repr__(						self     :   Optional[Any]       )      ->str:



					'''simple docstring'''







					return F"""{self.__class__.__name__}('{self.username}')"""




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



					'''simple docstring'''







					return F"""{self.fullname} ({self.username}) is {self.biography}"""




			@property
			def 							lowerCAmelCase__			(						self     :   Optional[int]       )      ->str:



					'''simple docstring'''







					return self.user_data["username"]




			@property
			def 							lowerCAmelCase__			(						self     :   Optional[int]       )      ->str:



					'''simple docstring'''







					return self.user_data["full_name"]




			@property
			def 							lowerCAmelCase__			(						self     :   Optional[int]       )      ->str:



					'''simple docstring'''







					return self.user_data["biography"]




			@property
			def 							lowerCAmelCase__			(						self     :   int       )      ->str:



					'''simple docstring'''







					return self.user_data["business_email"]




			@property
			def 							lowerCAmelCase__			(						self     :   str       )      ->str:



					'''simple docstring'''







					return self.user_data["external_url"]




			@property
			def 							lowerCAmelCase__			(						self     :   Tuple       )      ->int:



					'''simple docstring'''







					return self.user_data["edge_followed_by"]["count"]




			@property
			def 							lowerCAmelCase__			(						self     :   str       )      ->int:



					'''simple docstring'''







					return self.user_data["edge_follow"]["count"]




			@property
			def 							lowerCAmelCase__			(						self     :   Any       )      ->int:



					'''simple docstring'''







					return self.user_data["edge_owner_to_timeline_media"]["count"]




			@property
			def 							lowerCAmelCase__			(						self     :   List[Any]       )      ->str:



					'''simple docstring'''







					return self.user_data["profile_pic_url_hd"]




			@property
			def 							lowerCAmelCase__			(						self     :   Optional[Any]       )      ->bool:



					'''simple docstring'''







					return self.user_data["is_verified"]






			@property
			def 							lowerCAmelCase__			(						self     :   int       )      ->bool:



					'''simple docstring'''







					return self.user_data["is_private"]






def        __lowerCAmelCase       (__lowerCAmelCase = "github"      ):
		import os

		if os.environ.get("CI"      ):
				return  # test failing on GitHub Actions
		_UpperCAmelCase						:				Dict	    =					InstagramUser(__lowerCAmelCase      )
		assert instagram_user.user_data
		assert isinstance(instagram_user.user_data					,       __lowerCAmelCase      )
		assert instagram_user.username == username
		if username != "github":
				return
		assert instagram_user.fullname == "GitHub"
		assert instagram_user.biography == "Built for developers."
		assert instagram_user.number_of_posts > 150
		assert instagram_user.number_of_followers > 120_000
		assert instagram_user.number_of_followings > 15
		assert instagram_user.email == "support@github.com"
		assert instagram_user.website == "https://github.com/readme"
		assert instagram_user.profile_picture_url.startswith("https://instagram."      )
		assert instagram_user.is_verified is True
		assert instagram_user.is_private is False


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						lowerCamelCase__					=   InstagramUser('github')
						print(instagram_user)
						print(F'''{instagram_user.number_of_posts = }''')
						print(F'''{instagram_user.number_of_followers = }''')
						print(F'''{instagram_user.number_of_followings = }''')
						print(F'''{instagram_user.email = }''')
						print(F'''{instagram_user.website = }''')
						print(F'''{instagram_user.profile_picture_url = }''')
						print(F'''{instagram_user.is_verified = }''')
						print(F'''{instagram_user.is_private = }''')



