# -*- 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)