



import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


A__  :  int								=					logging.get_logger(__name__)


def 			UpperCamelCase(  __UpperCamelCase							:		Union[str, Any]     ,__UpperCamelCase							:		Union[str, Any] ):
		lowerCAmelCase_			:     Any									= nn.functional.normalize(__UpperCamelCase )
		lowerCAmelCase_			:     Optional[int]									= nn.functional.normalize(__UpperCamelCase )
		return torch.mm(__UpperCamelCase     ,normalized_text_embeds.t() )





class 				__snake_case						(     UpperCamelCase_						):
							_a			      = CLIPConfig

							_a			      = ['''CLIPEncoderLayer''']




							def __init__(       self     :       Dict				,				A_     :       CLIPConfig):
									super().__init__(A_)

									lowerCAmelCase_			:     Optional[Any]									= CLIPVisionModel(config.vision_config)
									lowerCAmelCase_			:     Dict									= nn.Linear(config.vision_config.hidden_size				,				config.projection_dim				,				bias=A_)

									lowerCAmelCase_			:     List[Any]									= nn.Parameter(torch.ones(1_7				,				config.projection_dim)				,				requires_grad=A_)
									lowerCAmelCase_			:     Tuple									= nn.Parameter(torch.ones(3				,				config.projection_dim)				,				requires_grad=A_)

									lowerCAmelCase_			:     int									= nn.Parameter(torch.ones(1_7)				,				requires_grad=A_)
									lowerCAmelCase_			:     int									= nn.Parameter(torch.ones(3)				,				requires_grad=A_)




							@torch.no_grad()
							def    UpperCAmelCase__			(       self     :       int				,				A_     :       int				,				A_     :       int):
									lowerCAmelCase_			:     int									= self.vision_model(A_)[1]  # pooled_output
									lowerCAmelCase_			:     Optional[Any]									= self.visual_projection(A_)

									# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
									lowerCAmelCase_			:     int									= cosine_distance(A_				,				self.special_care_embeds).cpu().float().numpy()
									lowerCAmelCase_			:     Dict									= cosine_distance(A_				,				self.concept_embeds).cpu().float().numpy()

									lowerCAmelCase_			:     Any									= []
									lowerCAmelCase_			:     Optional[Any]									= image_embeds.shape[0]
									for i in range(A_):
											lowerCAmelCase_			:     int									= {'''special_scores''': {}, '''special_care''': [], '''concept_scores''': {}, '''bad_concepts''': []}

											# increase this value to create a stronger `nfsw` filter
											# at the cost of increasing the possibility of filtering benign images
											lowerCAmelCase_			:     Any									= 0.0

											for concept_idx in range(len(special_cos_dist[0])):
													lowerCAmelCase_			:     Optional[int]									= special_cos_dist[i][concept_idx]
													lowerCAmelCase_			:     Optional[int]									= self.special_care_embeds_weights[concept_idx].item()
													lowerCAmelCase_			:     Dict									= round(concept_cos - concept_threshold + adjustment				,				3)
													if result_img["special_scores"][concept_idx] > 0:
															result_img["special_care"].append({concept_idx, result_img['''special_scores'''][concept_idx]})
															lowerCAmelCase_			:     str									= 0.01

											for concept_idx in range(len(cos_dist[0])):
													lowerCAmelCase_			:     Optional[Any]									= cos_dist[i][concept_idx]
													lowerCAmelCase_			:     Dict									= self.concept_embeds_weights[concept_idx].item()
													lowerCAmelCase_			:     Any									= round(concept_cos - concept_threshold + adjustment				,				3)
													if result_img["concept_scores"][concept_idx] > 0:
															result_img["bad_concepts"].append(A_)

											result.append(A_)

									lowerCAmelCase_			:     str									= [len(res['''bad_concepts''']) > 0 for res in result]

									return images, has_nsfw_concepts







							@torch.no_grad()
							def    UpperCAmelCase__			(       self     :       str				,				A_     :       torch.FloatTensor				,				A_     :       torch.FloatTensor):
									lowerCAmelCase_			:     str									= self.vision_model(A_)[1]  # pooled_output
									lowerCAmelCase_			:     Optional[int]									= self.visual_projection(A_)

									lowerCAmelCase_			:     List[str]									= cosine_distance(A_				,				self.special_care_embeds)
									lowerCAmelCase_			:     Union[str, Any]									= cosine_distance(A_				,				self.concept_embeds)

									# increase this value to create a stronger `nsfw` filter
									# at the cost of increasing the possibility of filtering benign images
									lowerCAmelCase_			:     Any									= 0.0

									lowerCAmelCase_			:     List[str]									= special_cos_dist - self.special_care_embeds_weights + adjustment
									# special_scores = special_scores.round(decimals=3)
									lowerCAmelCase_			:     List[str]									= torch.any(special_scores > 0				,				dim=1)
									lowerCAmelCase_			:     Optional[int]									= special_care * 0.01
									lowerCAmelCase_			:     Optional[Any]									= special_adjustment.unsqueeze(1).expand(-1				,				cos_dist.shape[1])

									lowerCAmelCase_			:     str									= (cos_dist - self.concept_embeds_weights) + special_adjustment
									# concept_scores = concept_scores.round(decimals=3)
									lowerCAmelCase_			:     Dict									= torch.any(concept_scores > 0				,				dim=1)

									return images, has_nsfw_concepts










from datetime import datetime as dt
import os

from github import Github


A__  :  List[str]								=					[
    '''good first issue''',
    '''good second issue''',
    '''good difficult issue''',
    '''feature request''',
    '''new model''',
    '''wip''',
]


def 			UpperCamelCase(  ):
		lowerCAmelCase_			:     Union[str, Any]									= Github(os.environ['''GITHUB_TOKEN'''] )
		lowerCAmelCase_			:     Tuple									= g.get_repo('''huggingface/transformers''' )
		lowerCAmelCase_			:     int									= repo.get_issues(state='''open''' )

		for issue in open_issues:
				lowerCAmelCase_			:     Optional[Any]									= sorted([comment for comment in issue.get_comments()]     ,key=lambda __UpperCamelCase : i.created_at     ,reverse=__UpperCamelCase )
				lowerCAmelCase_			:     Tuple									= comments[0] if len(__UpperCamelCase ) > 0 else None
				if (
				    last_comment is not None
				    and last_comment.user.login == "github-actions[bot]"
				    and (dt.utcnow() - issue.updated_at).days > 7
				    and (dt.utcnow() - issue.created_at).days >= 30
				    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
				):
						# print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
						issue.edit(state='''closed''' )
				elif (
				    (dt.utcnow() - issue.updated_at).days > 23
				    and (dt.utcnow() - issue.created_at).days >= 30
				    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
				):
						# print(f"Would add stale comment to {issue.number}")
						issue.create_comment(
						    '''This issue has been automatically marked as stale because it has not had '''
						    '''recent activity. If you think this still needs to be addressed '''
						    '''please comment on this thread.\n\nPlease note that issues that do not follow the '''
						    '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) '''
						    '''are likely to be ignored.''' )


if __name__ == "__main__":
						main()





