




'''simple docstring'''







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

from ...utils import logging


A					       =logging.get_logger(__name__)





def 		snake_case_				(_a      :				int       ,  _a      :				List[str]	):
    UpperCAmelCase     			=						nn.functional.normalize(_a	)
    UpperCAmelCase     			=						nn.functional.normalize(_a	)
    return torch.mm(_a       ,  normalized_text_embeds.t()	)







class      _a    (      __a					):
       __a							:	Tuple  							=   CLIPConfig

       __a							:	int  							=   ["""CLIPEncoderLayer"""]
       def __init__(      self		:      Tuple  ,							lowercase		:      CLIPConfig							):



           '''simple docstring'''

           super().__init__(lowercase							)

           UpperCAmelCase     			=						CLIPVisionModel(config.vision_config							)
           UpperCAmelCase     			=						nn.Linear(config.vision_config.hidden_size  ,							config.projection_dim  ,							bias=lowercase							)

           UpperCAmelCase     			=						nn.Parameter(torch.ones(17  ,							config.projection_dim							)  ,							requires_grad=lowercase							)
           UpperCAmelCase     			=						nn.Parameter(torch.ones(3  ,							config.projection_dim							)  ,							requires_grad=lowercase							)

           UpperCAmelCase     			=						nn.Parameter(torch.ones(17							)  ,							requires_grad=lowercase							)
           UpperCAmelCase     			=						nn.Parameter(torch.ones(3							)  ,							requires_grad=lowercase							)
       @torch.no_grad()
       def        A (      self		:      Optional[Any]  ,							lowercase		:      Optional[int]  ,							lowercase		:      int							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.vision_model(lowercase							)[1]  # pooled_output
           UpperCAmelCase     			=						self.visual_projection(lowercase							)

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

           UpperCAmelCase     			=						[]
           UpperCAmelCase     			=						image_embeds.shape[0]
           for i in range(lowercase							):
               UpperCAmelCase     			=						{'''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     			=						0.0

               for concept_idx in range(len(special_cos_dist[0]							)							):
                   UpperCAmelCase     			=						special_cos_dist[i][concept_idx]
                   UpperCAmelCase     			=						self.special_care_embeds_weights[concept_idx].item()
                   UpperCAmelCase     			=						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     			=						0.01

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

               result.append(lowercase							)

           UpperCAmelCase     			=						[len(res['''bad_concepts''']							) > 0 for res in result]

           for idx, has_nsfw_concept in enumerate(lowercase							):
               if has_nsfw_concept:
                   if torch.is_tensor(lowercase							) or torch.is_tensor(images[0]							):
                       UpperCAmelCase     			=						torch.zeros_like(images[idx]							)  # black image
                   else:
                       UpperCAmelCase     			=						np.zeros(images[idx].shape							)  # black image

           if any(lowercase							):
               logger.warning(
                   '''Potential NSFW content was detected in one or more images. A black image will be returned instead.'''
                   ''' Try again with a different prompt and/or seed.'''							)

           return images, has_nsfw_concepts







       @torch.no_grad()
       def        A (      self		:      str  ,							lowercase		:      torch.FloatTensor  ,							lowercase		:      torch.FloatTensor							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.vision_model(lowercase							)[1]  # pooled_output
           UpperCAmelCase     			=						self.visual_projection(lowercase							)

           UpperCAmelCase     			=						cosine_distance(lowercase  ,							self.special_care_embeds							)
           UpperCAmelCase     			=						cosine_distance(lowercase  ,							self.concept_embeds							)

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

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

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

           UpperCAmelCase     			=						0.0  # black image

           return images, has_nsfw_concepts










'''simple docstring'''







from __future__ import annotations





def 		snake_case_				(_a      :				list[list[int]]       ,  _a      :				list[list[int]]	):
    assert len(_a	) == len(_a	)

    UpperCAmelCase     			=						len(_a	)
    UpperCAmelCase     			=						list(range(_a	)	)
    UpperCAmelCase     			=						[-1] * n  # who the donor has donated to
    UpperCAmelCase     			=						[-1] * n  # who the recipient has received from
    UpperCAmelCase     			=						[0] * n

    while unmatched_donors:
        UpperCAmelCase     			=						unmatched_donors[0]
        UpperCAmelCase     			=						donor_pref[donor]
        UpperCAmelCase     			=						donor_preference[num_donations[donor]]
        num_donations[donor] += 1
        UpperCAmelCase     			=						recipient_pref[recipient]
        UpperCAmelCase     			=						rec_record[recipient]

        if prev_donor != -1:
            if rec_preference.index(_a	) > rec_preference.index(_a	):
                UpperCAmelCase     			=						donor
                UpperCAmelCase     			=						recipient
                unmatched_donors.append(_a	)
                unmatched_donors.remove(_a	)
        else:
            UpperCAmelCase     			=						donor
            UpperCAmelCase     			=						recipient
            unmatched_donors.remove(_a	)
    return donor_record




