1: import numpy as np
2: from PIL import ImageOps
3: 
4: from data_juicer.utils.constant import Fields, StatsKeys
5: from data_juicer.utils.mm_utils import (
6:     SpecialTokens,
7:     load_data_with_context,
8:     load_image,
9:     remove_special_tokens,
10: )
11: from data_juicer.utils.model_utils import get_model, prepare_model
12: 
13: from ..base_op import OPERATORS, Filter
14: from ..op_fusion import LOADED_IMAGES
15: 
16: OP_NAME = "image_text_similarity_filter"
17: 
18: 
19: @OPERATORS.register_module(OP_NAME)
20: @LOADED_IMAGES.register_module(OP_NAME)
21: class ImageTextSimilarityFilter(Filter):
22:     """Filter to keep samples with image-text similarity within a specified range.
23: 
24:     This operator uses a Hugging Face CLIP model to compute the similarity between images
25:     and text. It retains samples where the similarity scores fall within the given range.
26:     The similarity score is computed for each image-text pair, and the final score can be
27:     reduced using 'avg', 'max', or 'min' modes. The 'any' or 'all' strategy determines if at
28:     least one or all image-text pairs must meet the similarity criteria. The key metric
29:     'image_text_similarity' is cached in the sample's stats. Images can be flipped
30:     horizontally or vertically before computing the similarity."""
31: 
32:     _accelerator = "cuda"
33:     _batched_op = True
34: 
35:     def __init__(
36:         self,
37:         hf_clip: str = "openai/clip-vit-base-patch32",
38:         trust_remote_code: bool = False,
39:         min_score: float = 0.1,
40:         max_score: float = 1.0,
41:         horizontal_flip: bool = False,
42:         vertical_flip: bool = False,
43:         any_or_all: str = "any",
44:         reduce_mode: str = "avg",
45:         *args,
46:         **kwargs,
47:     ):
48:         """
49:         Initialization method.
50: 
51:         :param hf_clip: clip model name on huggingface to compute
52:             the similarity between image and text.
53:         :param trust_remote_code: whether to trust the remote code of HF models.
54:         :param min_score: The min similarity to keep samples.
55:         :param max_score: The max similarity to keep samples.
56:         :param horizontal_flip: Flip image horizontally (left to right).
57:         :param vertical_flip: Flip image vertically (top to bottom).
58:         :param any_or_all: keep this sample with 'any' or 'all' strategy of
59:             all images. 'any': keep this sample if any images meet the
60:             condition. 'all': keep this sample only if all images meet the
61:             condition.
62:         :param reduce_mode: reduce mode when one text corresponds to
63:             multiple images in a chunk.
64:             'avg': Take the average of multiple values
65:             'max': Take the max of multiple values
66:             'min': Take the min of multiple values
67:         :param args: extra args
68:         :param kwargs: extra args
69:         """
70:         kwargs["memory"] = "1500MB" if kwargs.get("memory", 0) == 0 else kwargs["memory"]
71:         super().__init__(*args, **kwargs)
72:         self.min_score = min_score
73:         self.max_score = max_score
74:         if reduce_mode not in ["avg", "max", "min"]:
75:             raise ValueError(
76:                 f"Reduce mode [{reduce_mode}] is not supported. " f'Can only be one of ["avg", "max", "min"].'
77:             )
78:         if any_or_all not in ["any", "all"]:
79:             raise ValueError(f"Keep strategy [{any_or_all}] is not supported. " f'Can only be one of ["any", "all"].')
80:         self.any = any_or_all == "any"
81:         self.model_key = prepare_model(
82:             model_type="huggingface", pretrained_model_name_or_path=hf_clip, trust_remote_code=trust_remote_code
83:         )
84:         self.reduce_mode = reduce_mode
85:         self.horizontal_flip = horizontal_flip
86:         self.vertical_flip = vertical_flip
87: 
88:     def compute_stats_single(self, sample, rank=None, context=False):
89:         # check if it's computed already
90:         if StatsKeys.image_text_similarity in sample[Fields.stats]:
91:             return sample
92: 
93:         # there is no image in this sample
94:         if self.image_key not in sample or not sample[self.image_key]:
95:             sample[Fields.stats][StatsKeys.image_text_similarity] = np.array([], dtype=np.float64)
96:             return sample
97: 
98:         # load images
99:         loaded_image_keys = sample[self.image_key]
100:         sample, images = load_data_with_context(
101:             sample, context, loaded_image_keys, load_image, mm_bytes_key=self.image_bytes_key
102:         )
103: 
104:         text = sample[self.text_key]
105:         offset = 0
106:         similarity = []
107:         model, processor = get_model(self.model_key, rank, self.use_cuda())
108: 
109:         for chunk in text.split(SpecialTokens.eoc):
110:             count = chunk.count(SpecialTokens.image)
111: 
112:             # no image or no text
113:             if count == 0 or len(chunk) == 0:
114:                 continue
115:             else:
116:                 text_chunk = remove_special_tokens(chunk)
117:                 image_chunk = []
118:                 for image_key in loaded_image_keys[offset : offset + count]:
119:                     image = images[image_key]
120:                     if self.horizontal_flip:
121:                         image = ImageOps.mirror(image)
122:                     if self.vertical_flip:
123:                         image = ImageOps.flip(image)
124:                     image_chunk.append(image)
125: 
126:                 inputs = processor(
127:                     text=text_chunk,
128:                     images=image_chunk,
129:                     return_tensors="pt",
130:                     truncation=True,
131:                     max_length=model.config.text_config.max_position_embeddings,
132:                     padding=True,
133:                 ).to(model.device)
134: 
135:                 outputs = model(**inputs)
136:                 chunk_logits = outputs.logits_per_text / 100.0
137: 
138:                 if self.reduce_mode == "avg":
139:                     chunk_similarity = chunk_logits.mean()
140:                 elif self.reduce_mode == "max":
141:                     chunk_similarity = chunk_logits.max()
142:                 else:
143:                     chunk_similarity = chunk_logits.min()
144: 
145:                 similarity.append(float(chunk_similarity))
146:             offset += count
147:         sample[Fields.stats][StatsKeys.image_text_similarity] = similarity
148: 
149:         return sample
150: 
151:     def process_single(self, sample, rank=None):
152:         similarity = sample[Fields.stats][StatsKeys.image_text_similarity]
153:         if len(similarity) <= 0:
154:             return True
155: 
156:         keep_bools = np.array(
157:             [self.get_keep_boolean(sim_value, self.min_score, self.max_score) for sim_value in similarity]
158:         )
159: 
160:         # different strategies
161:         if self.any:
162:             return keep_bools.any()
163:         else:
164:             return keep_bools.all()