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