slarabi commited on
Commit
62c0378
·
verified ·
1 Parent(s): ce8c12c

Upload SketchGeneratingAndSimilarityComputing.py

Browse files
SketchGeneratingAndSimilarityComputing.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Untitled15.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/19uX16BfabsNbAGHLkTWZLGNduuUblfld
8
+ """
9
+
10
+ # -*- coding: utf-8 -*-
11
+ """
12
+ Interactive Interface for Sketch Generation and Similarity Calculation
13
+ (Avec choix de chargement du modèle : Google Drive ou Chemin personnalisé)
14
+ """
15
+
16
+ import os
17
+ import random
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ from PIL import Image
23
+ from sentence_transformers import SentenceTransformer
24
+ import ipywidgets as widgets
25
+ from IPython.display import display, clear_output
26
+ import matplotlib.pyplot as plt
27
+
28
+ # =====================================================================
29
+ # 0. Initial Configuration & Model Loading Options
30
+ # =====================================================================
31
+ SEED = 42
32
+ random.seed(SEED)
33
+ np.random.seed(SEED)
34
+ torch.manual_seed(SEED)
35
+
36
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
37
+ print("Used Device :", DEVICE)
38
+
39
+ H_SKETCH, W_SKETCH = 400, 800
40
+ C_SKETCH = 1
41
+
42
+ os.makedirs("sample_data", exist_ok=True)
43
+
44
+ # ---------------------------------------------------------------------
45
+ # MODEL PATH CONFIGURATION
46
+ # ---------------------------------------------------------------------
47
+ # Option 1: Load from Google Drive (Set to True to mount the Drive)
48
+ USE_GOOGLE_DRIVE = True
49
+
50
+ # Option 2: Custom direct path (leave blank "" if using Drive)
51
+ # Example : "/content/sample_data/model_gray_coco30000captions_384dim.pth"
52
+
53
+ CUSTOM_MODEL_PATH = ""
54
+
55
+ if CUSTOM_MODEL_PATH:
56
+ model_path = CUSTOM_MODEL_PATH
57
+ elif USE_GOOGLE_DRIVE:
58
+ from google.colab import drive
59
+ drive.mount('/content/drive', force_remount=False)
60
+ drive_dir = "/content/drive/My Drive"
61
+ model_path = os.path.join(drive_dir, "model_gray_coco30000captions_384dim.pth")
62
+ else:
63
+ model_path = "model_gray_coco30000captions_384dim.pth"
64
+
65
+ # ---------------------------------------------------------------------
66
+
67
+ # Loading SBERT
68
+ print("Loading SBERT...")
69
+ sbert = SentenceTransformer("all-MiniLM-L6-v2", device=str(DEVICE))
70
+
71
+ # Definition of Architecture
72
+ class SemanticEncoder(nn.Module):
73
+ def __init__(self, input_dim=384, latent_dim=384):
74
+ super().__init__()
75
+ self.net = nn.Sequential(
76
+ nn.Linear(input_dim, 384), nn.ReLU(), nn.Dropout(0.1),
77
+ nn.Linear(384, latent_dim), nn.LayerNorm(latent_dim),
78
+ )
79
+ def forward(self, x):
80
+ return self.net(x)
81
+
82
+ class GraySketchDecoder(nn.Module):
83
+ def __init__(self, latent_dim=384):
84
+ super().__init__()
85
+ self.fc = nn.Linear(latent_dim, 128 * 13 * 25)
86
+ self.deconv = nn.Sequential(
87
+ nn.BatchNorm2d(128), nn.ReLU(),
88
+ nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
89
+ nn.Conv2d(128, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
90
+ nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
91
+ nn.Conv2d(64, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
92
+ nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
93
+ nn.Conv2d(32, C_SKETCH, kernel_size=3, padding=1),
94
+ nn.Upsample(size=(H_SKETCH, W_SKETCH), mode="bilinear", align_corners=False),
95
+ nn.Sigmoid(),
96
+ )
97
+ def forward(self, z):
98
+ return self.deconv(self.fc(z).view(-1, 128, 13, 25))
99
+
100
+ class GraySketchEncoder(nn.Module):
101
+ def __init__(self, output_dim=384):
102
+ super().__init__()
103
+ self.conv = nn.Sequential(
104
+ nn.Conv2d(C_SKETCH, 32, 4, 2, 1), nn.ReLU(),
105
+ nn.Conv2d(32, 64, 4, 2, 1), nn.ReLU(),
106
+ nn.Conv2d(64, 128, 4, 2, 1), nn.ReLU(),
107
+ nn.AdaptiveAvgPool2d((4, 8)),
108
+ nn.Flatten(),
109
+ )
110
+ self.fc = nn.Linear(128 * 4 * 8, output_dim)
111
+ def forward(self, sketch):
112
+ return self.fc(self.conv(sketch))
113
+
114
+ class EndToEndGrayPipeline(nn.Module):
115
+ def __init__(self, input_dim=384, latent_dim=384):
116
+ super().__init__()
117
+ self.semantic_encoder = SemanticEncoder(input_dim, latent_dim)
118
+ self.sketch_decoder = GraySketchDecoder(latent_dim)
119
+ self.sketch_encoder = GraySketchEncoder(latent_dim)
120
+ def forward(self, text_emb):
121
+ z = self.semantic_encoder(text_emb)
122
+ sketch = self.sketch_decoder(z)
123
+ return z, sketch, self.sketch_encoder(sketch)
124
+
125
+ # Instantiation and loading of weights
126
+ model_gray_coco = EndToEndGrayPipeline(input_dim=384, latent_dim=384).to(DEVICE)
127
+
128
+ if os.path.exists(model_path):
129
+ print(f"Loading model from: {model_path}")
130
+ model_gray_coco.load_state_dict(torch.load(model_path, map_location=DEVICE))
131
+ model_gray_coco.eval()
132
+ print("Model ready !")
133
+ else:
134
+ raise FileNotFoundError(f"Model not found at: {model_path}. Please check the path or configure CUSTOM_MODEL_PATH.")
135
+
136
+
137
+ # =====================================================================
138
+ # 1. Generation and Calculation Functions
139
+ # =====================================================================
140
+ def generate_single_sketch(query_text):
141
+ model_gray_coco.eval()
142
+ with torch.no_grad():
143
+ q_emb = sbert.encode(query_text, convert_to_tensor=True).unsqueeze(0).to(DEVICE)
144
+ _, sketch_tensor, _ = model_gray_coco(q_emb)
145
+ sketch_np = (sketch_tensor.squeeze(0).squeeze(0).cpu().numpy() * 255).astype(np.uint8)
146
+ img_pil = Image.fromarray(sketch_np).convert("RGB")
147
+ return img_pil.resize((W_SKETCH, H_SKETCH), Image.Resampling.BILINEAR)
148
+
149
+ def compare_texts_and_sketches(text1, text2):
150
+ model_gray_coco.eval()
151
+ texts = [text1, text2]
152
+
153
+ with torch.no_grad():
154
+ # Encoding Raw SBERT
155
+ sbert_embs = sbert.encode(texts, convert_to_tensor=True, device=DEVICE)
156
+ sbert_embs_norm = F.normalize(sbert_embs, dim=1)
157
+ sim_sbert = torch.sum(sbert_embs_norm[0] * sbert_embs_norm[1]).item()
158
+
159
+ # Semantic Latent Space Similarity
160
+ latent_embs = model_gray_coco.semantic_encoder(sbert_embs)
161
+ latent_embs_norm = F.normalize(latent_embs, dim=1)
162
+ sim_latent = torch.sum(latent_embs_norm[0] * latent_embs_norm[1]).item()
163
+
164
+ # Generation of sketches and encoding via sketch_encoder
165
+ z = model_gray_coco.semantic_encoder(sbert_embs)
166
+ sketches = model_gray_coco.sketch_decoder(z)
167
+ sketch_latents = model_gray_coco.sketch_encoder(sketches)
168
+ sketch_latents_norm = F.normalize(sketch_latents, dim=1)
169
+ sim_sketch = torch.sum(sketch_latents_norm[0] * sketch_latents_norm[1]).item()
170
+
171
+ img1 = Image.fromarray((sketches[0].squeeze(0).cpu().numpy() * 255).astype(np.uint8)).convert("RGB")
172
+ img2 = Image.fromarray((sketches[1].squeeze(0).cpu().numpy() * 255).astype(np.uint8)).convert("RGB")
173
+
174
+ return sim_sbert, sim_latent, sim_sketch, img1, img2
175
+
176
+
177
+ # =====================================================================
178
+ # 2. Creating the Graphical User Interface (IPywidgets)
179
+ # =====================================================================
180
+
181
+ # --- Tab 1: A text -> A sketch ---
182
+ input_text_1 = widgets.Textarea(
183
+ value='A man walks along a pathway through a quiet park during the early morning.',
184
+ placeholder='Enter your text here...',
185
+ description='Texte :',
186
+ disabled=False,
187
+ layout=widgets.Layout(width='80%', height='80px')
188
+ )
189
+ btn_gen_1 = widgets.Button(description="Generate the Sketch", button_style='success')
190
+ output_area_1 = widgets.Output()
191
+
192
+ def on_button_1_clicked(b):
193
+ with output_area_1:
194
+ clear_output(wait=True)
195
+ if not input_text_1.value.strip():
196
+ print("Please enter valid text.")
197
+ return
198
+ print("Generating......")
199
+ img = generate_single_sketch(input_text_1.value)
200
+ plt.figure(figsize=(8, 4))
201
+ plt.imshow(img)
202
+ plt.axis('off')
203
+ plt.title(f"Sketch for : {input_text_1.value[:50]}...")
204
+ plt.show()
205
+
206
+ btn_gen_1.on_click(on_button_1_clicked)
207
+ tab1 = widgets.VBox([widgets.Label("Generate the sketch from a single text :"), input_text_1, btn_gen_1, output_area_1])
208
+
209
+
210
+ # --- Tab 2: Two texts -> Sketches + Similarities ---
211
+ input_text_2a = widgets.Textarea(
212
+ value='A group of friends gathered around a wooden table with food and drinks.',
213
+ placeholder='First text...',
214
+ description='Text 1 :',
215
+ disabled=False,
216
+ layout=widgets.Layout(width='80%', height='60px')
217
+ )
218
+ input_text_2b = widgets.Textarea(
219
+ value='Several individuals sitting at a table with meals, talking and celebrating.',
220
+ placeholder='Second text...',
221
+ description='Text 2 :',
222
+ disabled=False,
223
+ layout=widgets.Layout(width='80%', height='60px')
224
+ )
225
+ btn_gen_2 = widgets.Button(description="Compute and Print", button_style='primary')
226
+ output_area_2 = widgets.Output()
227
+
228
+ def on_button_2_clicked(b):
229
+ with output_area_2:
230
+ clear_output(wait=True)
231
+ t1, t2 = input_text_2a.value.strip(), input_text_2b.value.strip()
232
+ if not t1 or not t2:
233
+ print("Please fill in both text fields.")
234
+ return
235
+ print("Calculating similarities and generating sketches—in progress...")
236
+ sim_sbert, sim_latent, sim_sketch, img1, img2 = compare_texts_and_sketches(t1, t2)
237
+
238
+ # Affichage des métriques
239
+ print("\n" + "="*50)
240
+ print(" SIMILARITY RESULTS")
241
+ print("="*50)
242
+ print(f"🔹 Similarity SBERT (Brut) : {sim_sbert:.4f}")
243
+ print(f"🔹 Similarity Latent Space : {sim_latent:.4f}")
244
+ print(f"🔹 Similarity of Sketches (Features) : {sim_sketch:.4f}")
245
+ print("="*50 + "\n")
246
+
247
+ # Affichage des images côte à côte
248
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5))
249
+ axes[0].imshow(img1)
250
+ axes[0].set_title("Sketch 1", fontsize=10)
251
+ axes[0].axis('off')
252
+
253
+ axes[1].imshow(img2)
254
+ axes[1].set_title("Sketch 2", fontsize=10)
255
+ axes[1].axis('off')
256
+
257
+ plt.tight_layout()
258
+ plt.show()
259
+
260
+ btn_gen_2.on_click(on_button_2_clicked)
261
+ tab2 = widgets.VBox([widgets.Label("Comparing two texts (Generation + SBERT Similarities & Sketches) :"), input_text_2a, input_text_2b, btn_gen_2, output_area_2])
262
+
263
+
264
+ # --- Assemblage des onglets ---
265
+ tabs = widgets.Tab(children=[tab1, tab2])
266
+ tabs.set_title(0, '1) One Text -> Sketch')
267
+ tabs.set_title(1, '2) Two Texts -> Similarities & Sketches')
268
+
269
+ display(tabs)