


'''simple docstring'''
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


__snake_case							   =  logging.get_logger(__name__)


def     a   (    __a				,      __a     )						->			str:



					'''simple docstring'''






					UpperCamelCase__     :int							      =				nn.functional.normalize(__a     )
					UpperCamelCase__     :Union[str, Any]							      =				nn.functional.normalize(__a     )
					return torch.mm(__a				,      normalized_text_embeds.t()     )







class      lowercase			(							A__      ):

		"""simple docstring"""

		_a     :   Optional[int]									=       CLIPConfig

		_a     :   Tuple									=       ['CLIPEncoderLayer']




		def __init__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(UpperCamelCase_							)

							UpperCamelCase__     :Any							      =				CLIPVisionModel(config.vision_config							)
							UpperCamelCase__     :Optional[int]							      =				nn.Linear(config.vision_config.hidden_size					,     config.projection_dim					,     bias=UpperCamelCase_							)

							UpperCamelCase__     :List[Any]							      =				nn.Parameter(torch.ones(17					,     config.projection_dim							)					,     requires_grad=UpperCamelCase_							)
							UpperCamelCase__     :Tuple							      =				nn.Parameter(torch.ones(3					,     config.projection_dim							)					,     requires_grad=UpperCamelCase_							)

							UpperCamelCase__     :int							      =				nn.Parameter(torch.ones(17							)					,     requires_grad=UpperCamelCase_							)
							UpperCamelCase__     :List[Any]							      =				nn.Parameter(torch.ones(3							)					,     requires_grad=UpperCamelCase_							)




		@torch.no_grad()
		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :Tuple							      =				self.vision_model(UpperCamelCase_							)[1]  # pooled_output
							UpperCamelCase__     :str							      =				self.visual_projection(UpperCamelCase_							)

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							UpperCamelCase__     :List[Any]							      =				cosine_distance(UpperCamelCase_					,     self.special_care_embeds							).cpu().float().numpy()
							UpperCamelCase__     :List[Any]							      =				cosine_distance(UpperCamelCase_					,     self.concept_embeds							).cpu().float().numpy()

							UpperCamelCase__     :Dict							      =				[]
							UpperCamelCase__     :Tuple							      =				image_embeds.shape[0]
							for i in range(UpperCamelCase_							):
												UpperCamelCase__     :Optional[Any]							      =				{'''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
												UpperCamelCase__     :Union[str, Any]							      =				0.0

												for concept_idx in range(len(special_cos_dist[0]							)							):
																	UpperCamelCase__     :str							      =				special_cos_dist[i][concept_idx]
																	UpperCamelCase__     :Union[str, Any]							      =				self.special_care_embeds_weights[concept_idx].item()
																	UpperCamelCase__     :Optional[int]							      =				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]}							)
																						UpperCamelCase__     :Optional[Any]							      =				0.01

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

												result.append(UpperCamelCase_							)

							UpperCamelCase__     :Tuple							      =				[len(res['''bad_concepts''']							) > 0 for res in result]

							return images, has_nsfw_concepts




		@torch.no_grad()
		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :str							      =				self.vision_model(UpperCamelCase_							)[1]  # pooled_output
							UpperCamelCase__     :Tuple							      =				self.visual_projection(UpperCamelCase_							)

							UpperCamelCase__     :Optional[Any]							      =				cosine_distance(UpperCamelCase_					,     self.special_care_embeds							)
							UpperCamelCase__     :Any							      =				cosine_distance(UpperCamelCase_					,     self.concept_embeds							)

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

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

							UpperCamelCase__     :Any							      =				(cos_dist - self.concept_embeds_weights) + special_adjustment
							# concept_scores = concept_scores.round(decimals=3)
							UpperCamelCase__     :Optional[Any]							      =				torch.any(concept_scores > 0					,     dim=1							)

							return images, has_nsfw_concepts



'''simple docstring'''
from __future__ import annotations

import csv

import requests
from bsa import BeautifulSoup


def     a   (    __a = ""     )						->			dict[str, float]:



					'''simple docstring'''






					UpperCamelCase__     :Optional[Any]							      =				url or '''https://www.imdb.com/chart/top/?ref_=nv_mv_250'''
					UpperCamelCase__     :Optional[int]							      =				BeautifulSoup(requests.get(__a     ).text				,      '''html.parser'''     )
					UpperCamelCase__     :Tuple							      =				soup.find_all('''td'''				,      attrs='''titleColumn'''     )
					UpperCamelCase__     :Union[str, Any]							      =				soup.find_all('''td'''				,      class_='''ratingColumn imdbRating'''     )
					return {
					    title.a.text: float(rating.strong.text     )
					    for title, rating in zip(__a				,      __a     )
					}


def     a   (    __a = "IMDb_Top_250_Movies.csv"     )						->			None:



					'''simple docstring'''






					UpperCamelCase__     :Optional[Any]							      =				get_imdb_top_aaa_movies()
					with open(__a				,      '''w'''				,      newline=''''''     ) as out_file:
										UpperCamelCase__     :int							      =				csv.writer(__a     )
										writer.writerow(['''Movie title''', '''IMDb rating''']     )
										for title, rating in movies.items():
															writer.writerow([title, rating]     )


if __name__ == "__main__":
		write_movies()