



"""simple docstring"""
import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


SCREAMING_SNAKE_CASE_      						=			logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE_      						=			"PoolFormerConfig"

# Base docstring
SCREAMING_SNAKE_CASE_      						=			"sail/poolformer_s12"
SCREAMING_SNAKE_CASE_      						=			[1, 5_12, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE_      						=			"sail/poolformer_s12"
SCREAMING_SNAKE_CASE_      						=			"tabby, tabby cat"

SCREAMING_SNAKE_CASE_      						=			[
    "sail/poolformer_s12",
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]



def 							lowerCAmelCase_    (				SCREAMING_SNAKE_CASE__,			SCREAMING_SNAKE_CASE__ = 0.0,			SCREAMING_SNAKE_CASE__ = False						)      ->   Optional[Any]:





		if drop_prob == 0.0 or not training:
				return input
		a_  :   List[str]			    =  1 - drop_prob
		a_  :   Any			    =  (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
		a_  :   str			    =  keep_prob + torch.rand(snake_case__,			dtype=input.dtype,			device=input.device						)
		random_tensor.floor_()  # binarize
		a_  :   Any			    =  input.div(snake_case__						) * random_tensor
		return output




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_ = None   ):
									super().__init__()
									a_  :   Tuple			    =  drop_prob






							def snake_case_	( self      ,  a_   ):
									return drop_path(a_      ,  self.drop_prob      ,  self.training   )






							def snake_case_	( self   ):
									return "p={}".format(self.drop_prob   )




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_      ,  a_      ,  a_      ,  a_      ,  a_      ,  a_=None   ):
									super().__init__()
									a_  :   int			    =  patch_size if isinstance(a_      ,  collections.abc.Iterable   ) else (patch_size, patch_size)
									a_  :   int			    =  stride if isinstance(a_      ,  collections.abc.Iterable   ) else (stride, stride)
									a_  :   Optional[int]			    =  padding if isinstance(a_      ,  collections.abc.Iterable   ) else (padding, padding)

									a_  :   List[str]			    =  nn.Convad(a_      ,  a_      ,  kernel_size=a_      ,  stride=a_      ,  padding=a_   )
									a_  :   Optional[Any]			    =  norm_layer(a_   ) if norm_layer else nn.Identity()






							def snake_case_	( self      ,  a_   ):
									a_  :   Tuple			    =  self.projection(a_   )
									a_  :   int			    =  self.norm(a_   )
									return embeddings




class       snake_case_    (    nn.GroupNorm					):






							def __init__( self      ,  a_      ,  **a_   ):
									super().__init__(1      ,  a_      ,  **a_   )




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_   ):
									super().__init__()
									a_  :   Dict			    =  nn.AvgPoolad(a_      ,  stride=1      ,  padding=pool_size // 2      ,  count_include_pad=a_   )






							def snake_case_	( self      ,  a_   ):
									return self.pool(a_   ) - hidden_states




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_      ,  a_      ,  a_      ,  a_   ):
									super().__init__()
									a_  :   List[str]			    =  nn.Convad(a_      ,  a_      ,  1   )
									a_  :   Tuple			    =  nn.Convad(a_      ,  a_      ,  1   )
									a_  :   int			    =  PoolFormerDropPath(a_   )
									if isinstance(config.hidden_act      ,  a_   ):
											a_  :   List[str]			    =  ACTaFN[config.hidden_act]
									else:
											a_  :   Tuple			    =  config.hidden_act






							def snake_case_	( self      ,  a_   ):
									a_  :   Dict			    =  self.conva(a_   )
									a_  :   int			    =  self.act_fn(a_   )
									a_  :   str			    =  self.drop(a_   )
									a_  :   List[Any]			    =  self.conva(a_   )
									a_  :   Optional[Any]			    =  self.drop(a_   )

									return hidden_states




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_      ,  a_      ,  a_      ,  a_      ,  a_      ,  a_   ):
									super().__init__()
									a_  :   int			    =  PoolFormerPooling(a_   )
									a_  :   Tuple			    =  PoolFormerOutput(a_      ,  a_      ,  a_      ,  a_   )
									a_  :   str			    =  PoolFormerGroupNorm(a_   )
									a_  :   Optional[int]			    =  PoolFormerGroupNorm(a_   )

									# Useful for training neural nets
									a_  :   str			    =  PoolFormerDropPath(a_   ) if drop_path > 0.0 else nn.Identity()
									a_  :   Dict			    =  config.use_layer_scale
									if config.use_layer_scale:
											a_  :   Optional[int]			    =  nn.Parameter(
											    config.layer_scale_init_value * torch.ones((a_)   )      ,  requires_grad=a_   )
											a_  :   Dict			    =  nn.Parameter(
											    config.layer_scale_init_value * torch.ones((a_)   )      ,  requires_grad=a_   )






							def snake_case_	( self      ,  a_   ):
									if self.use_layer_scale:
											a_  :   str			    =  self.pooling(self.before_norm(a_   )   )
											a_  :   Optional[Any]			    =  self.layer_scale_a.unsqueeze(-1   ).unsqueeze(-1   ) * pooling_output
											# First residual connection
											a_  :   Optional[int]			    =  hidden_states + self.drop_path(a_   )
											a_  :   Tuple			    =  ()

											a_  :   Optional[Any]			    =  self.output(self.after_norm(a_   )   )
											a_  :   List[Any]			    =  self.layer_scale_a.unsqueeze(-1   ).unsqueeze(-1   ) * layer_output
											# Second residual connection
											a_  :   List[str]			    =  hidden_states + self.drop_path(a_   )

											a_  :   Any			    =  (output,) + outputs
											return outputs

									else:
											a_  :   List[Any]			    =  self.drop_path(self.pooling(self.before_norm(a_   )   )   )
											# First residual connection
											a_  :   List[str]			    =  pooling_output + hidden_states
											a_  :   Optional[Any]			    =  ()

											# Second residual connection inside the PoolFormerOutput block
											a_  :   List[str]			    =  self.drop_path(self.output(self.after_norm(a_   )   )   )
											a_  :   Tuple			    =  hidden_states + layer_output

											a_  :   Optional[Any]			    =  (output,) + outputs
											return outputs




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_   ):
									super().__init__()
									a_  :   Dict			    =  config
									# stochastic depth decay rule
									a_  :   Tuple			    =  [x.item() for x in torch.linspace(0      ,  config.drop_path_rate      ,  sum(config.depths   )   )]

									# patch embeddings
									a_  :   List[str]			    =  []
									for i in range(config.num_encoder_blocks   ):
											embeddings.append(
											    PoolFormerEmbeddings(
											        patch_size=config.patch_sizes[i]      ,  stride=config.strides[i]      ,  padding=config.padding[i]      ,  num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1]      ,  hidden_size=config.hidden_sizes[i]      ,  )   )
									a_  :   int			    =  nn.ModuleList(a_   )

									# Transformer blocks
									a_  :   Any			    =  []
									a_  :   str			    =  0
									for i in range(config.num_encoder_blocks   ):
											# each block consists of layers
											a_  :   Tuple			    =  []
											if i != 0:
													cur += config.depths[i - 1]
											for j in range(config.depths[i]   ):
													layers.append(
													    PoolFormerLayer(
													        a_      ,  num_channels=config.hidden_sizes[i]      ,  pool_size=config.pool_size      ,  hidden_size=config.hidden_sizes[i]      ,  intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio   )      ,  drop_path=dpr[cur + j]      ,  )   )
											blocks.append(nn.ModuleList(a_   )   )

									a_  :   int			    =  nn.ModuleList(a_   )






							def snake_case_	( self      ,  a_      ,  a_=False      ,  a_=True   ):
									a_  :   Optional[int]			    =  () if output_hidden_states else None

									a_  :   Optional[Any]			    =  pixel_values
									for idx, layers in enumerate(zip(self.patch_embeddings      ,  self.block   )   ):
											a_    ,					a_  :   Any			    =  layers
											# Get patch embeddings from hidden_states
											a_  :   List[Any]			    =  embedding_layer(a_   )
											# Send the embeddings through the blocks
											for _, blk in enumerate(a_   ):
													a_  :   Any			    =  blk(a_   )
													a_  :   Optional[int]			    =  layer_outputs[0]

											if output_hidden_states:
													a_  :   int			    =  all_hidden_states + (hidden_states,)

									if not return_dict:
											return tuple(v for v in [hidden_states, all_hidden_states] if v is not None   )

									return BaseModelOutputWithNoAttention(last_hidden_state=a_      ,  hidden_states=a_   )




class       snake_case_    (    a_					):
							__lowerCAmelCase            =       PoolFormerConfig
							__lowerCAmelCase            =       "poolformer"
							__lowerCAmelCase            =       "pixel_values"
							__lowerCAmelCase            =       True






							def snake_case_	( self      ,  a_   ):
									if isinstance(a_      ,  (nn.Linear, nn.Convad)   ):
											module.weight.data.normal_(mean=0.0      ,  std=self.config.initializer_range   )
											if module.bias is not None:
													module.bias.data.zero_()
									elif isinstance(a_      ,  nn.LayerNorm   ):
											module.bias.data.zero_()
											module.weight.data.fill_(1.0   )






							def snake_case_	( self      ,  a_      ,  a_=False   ):
									if isinstance(a_      ,  a_   ):
											a_  :   List[Any]			    =  value

SCREAMING_SNAKE_CASE_      						=			R"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

SCREAMING_SNAKE_CASE_      						=			R"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`PoolFormerImageProcessor.__call__`] for details.\n"




@add_start_docstrings(
    "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top."  ,a_  ,)
class       snake_case_    (    a_					):






							def __init__( self      ,  a_   ):
									super().__init__(a_   )
									a_  :   Optional[int]			    =  config

									a_  :   Dict			    =  PoolFormerEncoder(a_   )

									# Initialize weights and apply final processing
									self.post_init()






							def snake_case_	( self   ):
									return self.embeddings.patch_embeddings






							@add_start_docstrings_to_model_forward(a_   )
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC      ,  output_type=a_      ,  config_class=_CONFIG_FOR_DOC      ,  modality="vision"      ,  expected_output=_EXPECTED_OUTPUT_SHAPE      ,  )
							def snake_case_	( self      ,  a_ = None      ,  a_ = None      ,  a_ = None      ,  ):
									a_  :   Dict			    =  (
									    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
									)
									a_  :   Optional[int]			    =  return_dict if return_dict is not None else self.config.use_return_dict

									if pixel_values is None:
											raise ValueError("You have to specify pixel_values"   )

									a_  :   Dict			    =  self.encoder(
									    a_      ,  output_hidden_states=a_      ,  return_dict=a_      ,  )
									a_  :   Optional[int]			    =  encoder_outputs[0]

									if not return_dict:
											return (sequence_output, None) + encoder_outputs[1:]

									return BaseModelOutputWithNoAttention(
									    last_hidden_state=a_      ,  hidden_states=encoder_outputs.hidden_states      ,  )




class       snake_case_    (    nn.Module					):






							def __init__( self      ,  a_   ):
									super().__init__()
									a_  :   Any			    =  nn.Linear(config.hidden_size      ,  config.hidden_size   )






							def snake_case_	( self      ,  a_   ):
									a_  :   Union[str, Any]			    =  self.dense(a_   )
									return output




@add_start_docstrings(
    "\n    PoolFormer Model transformer with an image classification head on top\n    "  ,a_  ,)
class       snake_case_    (    a_					):






							def __init__( self      ,  a_   ):
									super().__init__(a_   )
									a_  :   Optional[Any]			    =  config.num_labels
									a_  :   Dict			    =  PoolFormerModel(a_   )

									# Final norm
									a_  :   int			    =  PoolFormerGroupNorm(config.hidden_sizes[-1]   )
									# Classifier head
									a_  :   List[str]			    =  (
									    nn.Linear(config.hidden_sizes[-1]      ,  config.num_labels   ) if config.num_labels > 0 else nn.Identity()
									)

									# Initialize weights and apply final processing
									self.post_init()






							@add_start_docstrings_to_model_forward(a_   )
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT      ,  output_type=a_      ,  config_class=_CONFIG_FOR_DOC      ,  expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,  )
							def snake_case_	( self      ,  a_ = None      ,  a_ = None      ,  a_ = None      ,  a_ = None      ,  ):
									a_  :   Any			    =  return_dict if return_dict is not None else self.config.use_return_dict

									a_  :   Optional[Any]			    =  self.poolformer(
									    a_      ,  output_hidden_states=a_      ,  return_dict=a_      ,  )

									a_  :   int			    =  outputs[0]

									a_  :   str			    =  self.classifier(self.norm(a_   ).mean([-2, -1]   )   )

									a_  :   Tuple			    =  None
									if labels is not None:
											if self.config.problem_type is None:
													if self.num_labels == 1:
															a_  :   Union[str, Any]			    =  "regression"
													elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
															a_  :   Union[str, Any]			    =  "single_label_classification"
													else:
															a_  :   Optional[int]			    =  "multi_label_classification"

											if self.config.problem_type == "regression":
													a_  :   List[Any]			    =  MSELoss()
													if self.num_labels == 1:
															a_  :   Optional[int]			    =  loss_fct(logits.squeeze()      ,  labels.squeeze()   )
													else:
															a_  :   List[Any]			    =  loss_fct(a_      ,  a_   )
											elif self.config.problem_type == "single_label_classification":
													a_  :   Any			    =  CrossEntropyLoss()
													a_  :   Tuple			    =  loss_fct(logits.view(-1      ,  self.num_labels   )      ,  labels.view(-1   )   )
											elif self.config.problem_type == "multi_label_classification":
													a_  :   Optional[int]			    =  BCEWithLogitsLoss()
													a_  :   List[str]			    =  loss_fct(a_      ,  a_   )

									if not return_dict:
											a_  :   int			    =  (logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

									return ImageClassifierOutputWithNoAttention(loss=a_      ,  logits=a_      ,  hidden_states=outputs.hidden_states   )




from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

_lowerCAmelCase	:   List[str]    =   {"UserAgent": UserAgent().random}







def     UpperCAmelCase_		(					snake_case__					)	->     dict:



				"""simple docstring"""





				lowerCAmelCase__		  =  script.contents[0]
				lowerCAmelCase__		  =  json.loads(data[data.find('{"config"'					) : -1]					)
				return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]


class 	__snake_case   :
		def __init__(							self    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  f'https://www.instagram.com/{username}/'
						lowerCAmelCase__		  =  self.get_json()
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  requests.get(self.url    ,headers=a_						).text
						lowerCAmelCase__		  =  BeautifulSoup(a_    ,'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						):







						"""simple docstring"""
						return f'{self.__class__.__name__}(\'{self.username}\')'
		def __str__(							self						):







						"""simple docstring"""
						return f'{self.fullname} ({self.username}) is {self.biography}'
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["username"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["full_name"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["biography"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["business_email"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["external_url"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["edge_followed_by"]["count"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["edge_follow"]["count"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["edge_owner_to_timeline_media"]["count"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["profile_pic_url_hd"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["is_verified"]



		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["is_private"]







def     UpperCAmelCase_		(					snake_case__ = "github"					)	->     None:



				"""simple docstring"""





				import os

				if os.environ.get('CI'					):
								return  # test failing on GitHub Actions
				lowerCAmelCase__		  =  InstagramUser(snake_case__					)
				assert instagram_user.user_data
				assert isinstance(instagram_user.user_data    ,			snake_case__					)
				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 > 120000
				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	:   Optional[int]    =   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 = }""")
