


from dataclasses import dataclass
from typing import Dict, Optional, Union

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin


@dataclass
class     lowercase__  (					__UpperCAmelCase		):
  A__=  42




class     lowercase__  (					__UpperCAmelCase					,							__UpperCAmelCase		):






  @register_to_config
  def __init__(					self      :					Tuple		,						_lowercase      :					Any = 32		,						_lowercase      :					Union[str, Any] = 64		,						_lowercase      :					int = 20		,						_lowercase      :					Any = 7_68		,						_lowercase      :					Optional[Any]=77		,						_lowercase      :					Any=4		,						_lowercase      :					Dict = 0.0		,						_lowercase      :					Optional[int] = "silu"		,						_lowercase      :					str = None		,						_lowercase      :					Union[str, Any] = None		,						_lowercase      :					Union[str, Any] = "linear"		,						_lowercase      :					Any = "prd"		,						_lowercase      :					List[Any] = None		,						_lowercase      :					Optional[int] = None		,						_lowercase      :					List[str] = None		,						):




    """simple docstring"""







    super().__init__()
    UpperCAmelCase__										=     num_attention_heads
    UpperCAmelCase__										=     attention_head_dim
    UpperCAmelCase__										=     num_attention_heads * attention_head_dim
    UpperCAmelCase__										=     additional_embeddings

    UpperCAmelCase__										=     time_embed_dim or inner_dim
    UpperCAmelCase__										=     embedding_proj_dim or embedding_dim
    UpperCAmelCase__										=     clip_embed_dim or embedding_dim

    UpperCAmelCase__										=     Timesteps(_lowercase		,						_lowercase		,						0 )
    UpperCAmelCase__										=     TimestepEmbedding(_lowercase		,						_lowercase		,						out_dim=_lowercase		,						act_fn=_lowercase )

    UpperCAmelCase__										=     nn.Linear(_lowercase		,						_lowercase )

    if embedding_proj_norm_type is None:
      UpperCAmelCase__										=     None
    elif embedding_proj_norm_type == "layer":
      UpperCAmelCase__										=     nn.LayerNorm(_lowercase )
    else:
      raise ValueError(F"""unsupported embedding_proj_norm_type: {embedding_proj_norm_type}""" )

    UpperCAmelCase__										=     nn.Linear(_lowercase		,						_lowercase )

    if encoder_hid_proj_type is None:
      UpperCAmelCase__										=     None
    elif encoder_hid_proj_type == "linear":
      UpperCAmelCase__										=     nn.Linear(_lowercase		,						_lowercase )
    else:
      raise ValueError(F"""unsupported encoder_hid_proj_type: {encoder_hid_proj_type}""" )

    UpperCAmelCase__										=     nn.Parameter(torch.zeros(1		,						num_embeddings + additional_embeddings		,						_lowercase ) )

    if added_emb_type == "prd":
      UpperCAmelCase__										=     nn.Parameter(torch.zeros(1		,						1		,						_lowercase ) )
    elif added_emb_type is None:
      UpperCAmelCase__										=     None
    else:
      raise ValueError(
          F"""`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.""" )

    UpperCAmelCase__										=     nn.ModuleList(
        [
            BasicTransformerBlock(
                _lowercase		,						_lowercase		,						_lowercase		,						dropout=_lowercase		,						activation_fn="gelu"		,						attention_bias=_lowercase		,						)
            for d in range(_lowercase )
        ] )

    if norm_in_type == "layer":
      UpperCAmelCase__										=     nn.LayerNorm(_lowercase )
    elif norm_in_type is None:
      UpperCAmelCase__										=     None
    else:
      raise ValueError(F"""Unsupported norm_in_type: {norm_in_type}.""" )

    UpperCAmelCase__										=     nn.LayerNorm(_lowercase )

    UpperCAmelCase__										=     nn.Linear(_lowercase		,						_lowercase )

    UpperCAmelCase__										=     torch.full(
        [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]		,						-1_00_00.0 )
    causal_attention_mask.triu_(1 )
    UpperCAmelCase__										=     causal_attention_mask[None, ...]
    self.register_buffer("causal_attention_mask"		,						_lowercase		,						persistent=_lowercase )

    UpperCAmelCase__										=     nn.Parameter(torch.zeros(1		,						_lowercase ) )
    UpperCAmelCase__										=     nn.Parameter(torch.zeros(1		,						_lowercase ) )






  @property
  # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
  def 			_UpperCAmelCase  (					self      :					str ):




    """simple docstring"""







    UpperCAmelCase__										=     {}

    def fn_recursive_add_processors(_lowercase      :					str		,						_lowercase      :					Optional[int]		,						_lowercase      :					Optional[int] ):
      if hasattr(_lowercase		,						"set_processor" ):
        UpperCAmelCase__										=     module.processor

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

      return processors

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

    return processors






  def 			_UpperCAmelCase  (					self      :					str		,						_lowercase      :					List[Any] ):




    """simple docstring"""







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

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

    def fn_recursive_attn_processor(_lowercase      :					str		,						_lowercase      :					int		,						_lowercase      :					int ):
      if hasattr(_lowercase		,						"set_processor" ):
        if not isinstance(_lowercase		,						_lowercase ):
          module.set_processor(_lowercase )
        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}"""		,						_lowercase		,						_lowercase )

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






  def 			_UpperCAmelCase  (					self      :					int ):




    """simple docstring"""







    self.set_attn_processor(AttnProcessor() )






  def 			_UpperCAmelCase  (					self      :					Tuple		,						_lowercase      :					Optional[int]		,						_lowercase      :					List[Any]		,						_lowercase      :					Tuple		,						_lowercase      :					Optional[Any] = None		,						_lowercase      :					Union[str, Any] = None		,						_lowercase      :					str = True		,						):




    """simple docstring"""







    UpperCAmelCase__										=     hidden_states.shape[0]

    UpperCAmelCase__										=     timestep
    if not torch.is_tensor(_lowercase ):
      UpperCAmelCase__										=     torch.tensor([timesteps]		,						dtype=torch.long		,						device=hidden_states.device )
    elif torch.is_tensor(_lowercase ) and len(timesteps.shape ) == 0:
      UpperCAmelCase__										=     timesteps[None].to(hidden_states.device )

    # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
    UpperCAmelCase__										=     timesteps * torch.ones(_lowercase		,						dtype=timesteps.dtype		,						device=timesteps.device )

    UpperCAmelCase__										=     self.time_proj(_lowercase )

    # timesteps does not contain any weights and will always return f32 tensors
    # but time_embedding might be fp16, so we need to cast here.
    UpperCAmelCase__										=     timesteps_projected.to(dtype=self.dtype )
    UpperCAmelCase__										=     self.time_embedding(_lowercase )

    if self.embedding_proj_norm is not None:
      UpperCAmelCase__										=     self.embedding_proj_norm(_lowercase )

    UpperCAmelCase__										=     self.embedding_proj(_lowercase )
    if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
      UpperCAmelCase__										=     self.encoder_hidden_states_proj(_lowercase )
    elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
      raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set" )

    UpperCAmelCase__										=     self.proj_in(_lowercase )

    UpperCAmelCase__										=     self.positional_embedding.to(hidden_states.dtype )

    UpperCAmelCase__										=     []
    UpperCAmelCase__										=     0

    if encoder_hidden_states is not None:
      additional_embeds.append(_lowercase )
      additional_embeddings_len += encoder_hidden_states.shape[1]

    if len(proj_embeddings.shape ) == 2:
      UpperCAmelCase__										=     proj_embeddings[:, None, :]

    if len(hidden_states.shape ) == 2:
      UpperCAmelCase__										=     hidden_states[:, None, :]

    UpperCAmelCase__										=     additional_embeds + [
        proj_embeddings,
        time_embeddings[:, None, :],
        hidden_states,
    ]

    if self.prd_embedding is not None:
      UpperCAmelCase__										=     self.prd_embedding.to(hidden_states.dtype ).expand(_lowercase		,						-1		,						-1 )
      additional_embeds.append(_lowercase )

    UpperCAmelCase__										=     torch.cat(
        _lowercase		,						dim=1		,						)

    # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
    UpperCAmelCase__										=     additional_embeddings_len + proj_embeddings.shape[1] + 1
    if positional_embeddings.shape[1] < hidden_states.shape[1]:
      UpperCAmelCase__										=     F.pad(
          _lowercase		,						(
              0,
              0,
              additional_embeddings_len,
              self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
          )		,						value=0.0		,						)

    UpperCAmelCase__										=     hidden_states + positional_embeddings

    if attention_mask is not None:
      UpperCAmelCase__										=     (1 - attention_mask.to(hidden_states.dtype )) * -1_00_00.0
      UpperCAmelCase__										=     F.pad(_lowercase		,						(0, self.additional_embeddings)		,						value=0.0 )
      UpperCAmelCase__										=     (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype )
      UpperCAmelCase__										=     attention_mask.repeat_interleave(self.config.num_attention_heads		,						dim=0 )

    if self.norm_in is not None:
      UpperCAmelCase__										=     self.norm_in(_lowercase )

    for block in self.transformer_blocks:
      UpperCAmelCase__										=     block(_lowercase		,						attention_mask=_lowercase )

    UpperCAmelCase__										=     self.norm_out(_lowercase )

    if self.prd_embedding is not None:
      UpperCAmelCase__										=     hidden_states[:, -1]
    else:
      UpperCAmelCase__										=     hidden_states[:, additional_embeddings_len:]

    UpperCAmelCase__										=     self.proj_to_clip_embeddings(_lowercase )

    if not return_dict:
      return (predicted_image_embedding,)

    return PriorTransformerOutput(predicted_image_embedding=_lowercase )






  def 			_UpperCAmelCase  (					self      :					Tuple		,						_lowercase      :					Dict ):




    """simple docstring"""







    UpperCAmelCase__										=     (prior_latents * self.clip_std) + self.clip_mean
    return prior_latents









import csv

import tweepy

# Twitter API credentials
A      = ""
A      = ""
A      = ""
A      = ""





def __UpperCAmelCase       (		__A			)						->					None:



       '''simple docstring'''





       UpperCAmelCase__										=     tweepy.OAuthHandler(__A ,						__A			)
       auth.set_access_token(__A ,						__A			)
       UpperCAmelCase__										=     tweepy.API(__A			)

       # initialize a list to hold all the tweepy Tweets
       UpperCAmelCase__										=     []

       # make initial request for most recent tweets (200 is the maximum allowed count)
       UpperCAmelCase__										=     api.user_timeline(screen_name=__A ,						count=2_0_0			)

       # save most recent tweets
       alltweets.extend(__A			)

       # save the id of the oldest tweet less one
       UpperCAmelCase__										=     alltweets[-1].id - 1

       # keep grabbing tweets until there are no tweets left to grab
       while len(__A			) > 0:
              print(F"""getting tweets before {oldest}"""			)

              # all subsequent requests use the max_id param to prevent duplicates
              UpperCAmelCase__										=     api.user_timeline(
                  screen_name=__A ,						count=2_0_0 ,						max_id=__A			)

              # save most recent tweets
              alltweets.extend(__A			)

              # update the id of the oldest tweet less one
              UpperCAmelCase__										=     alltweets[-1].id - 1

              print(F"""...{len(__A			)} tweets downloaded so far"""			)

       # transform the tweepy tweets into a 2D array that will populate the csv
       UpperCAmelCase__										=     [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets]

       # write the csv
       with open(F"""new_{screen_name}_tweets.csv""" ,						"w"			) as f:
              UpperCAmelCase__										=     csv.writer(__A			)
              writer.writerow(["id", "created_at", "text"]			)
              writer.writerows(__A			)


if __name__ == "__main__":
    # pass in the username of the account you want to download
    get_all_tweets("FirePing32")





