Spaces:
No application file
No application file
File size: 13,190 Bytes
1a0f0cb | 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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | # -*- coding: utf-8 -*-
"""Untitled13.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1yLNDuxiW0UQnScp974bNmH2hKMq2iIqQ
"""
# -*- coding: utf-8 -*-
"""Untitled11.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1MgiykuAGja77XKxo2boeICyXOMHDHopc
gen sketch
"""
# -*- coding: utf-8 -*-
"""notebookGenSketch_10000Captions_Test_model_Exist.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1H7v4qTQa8rdT4VbL21RmwQ8RvDWE4W0g
"""
# -*- coding: utf-8 -*-
"""gen_sketches_last.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1kaPfieUOMQjFkJ7TYb46iOoY8Y82g_Fl
"""
# -*- coding: utf-8 -*-
"""gen_sketches_last.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1kaPfieUOMQjFkJ7TYb46iOoY8Y82g_Fl
"""
# -*- coding: utf-8 -*-
"""Untitled7.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1biLxE4eaUDAMimgiU5vQi4bXADbqLvHV
"""
# -*- coding: utf-8 -*-
"""gen_sketches_ng_384dim.ipynb - Version Latent 384-dim"""
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, ImageDraw, ImageFont
from sentence_transformers import SentenceTransformer
from datasets import load_dataset
# Fixer la graine pour la reproductibilité
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("Device utilisé :", DEVICE)
# Résolution en 400x800 (Hauteur: 400, Largeur: 800) et 1 canal (NG)
H_SKETCH, W_SKETCH = 400, 800
C_SKETCH = 1
print(f"Dimension des sketches configurée à : {H_SKETCH}x{W_SKETCH} avec {C_SKETCH} canal (Niveaux de Gris)")
# Création du dossier sample_data
os.makedirs("sample_data", exist_ok=True)
# =====================================================================
# 1. Chargement de MS-COCO
# =====================================================================
print("Téléchargement de coco_captions_quintets...")
coco_dataset = load_dataset("embedding-data/coco_captions_quintets", split="train")
raw_groups_coco = {}
for idx, item in enumerate(coco_dataset):
captions = item["set"]
if captions and len(captions) >= 3:
raw_groups_coco[str(idx)] = list(captions)
MAX_GROUPS = 10000
if len(raw_groups_coco) > MAX_GROUPS:
keep = random.sample(list(raw_groups_coco.keys()), MAX_GROUPS)
raw_groups_coco = {k: raw_groups_coco[k] for k in keep}
# Séparation Train / Test
groups_train_coco, groups_test_coco = {}, {}
for name, caps in raw_groups_coco.items():
caps = caps[:]
random.shuffle(caps)
n_test = max(1, round(len(caps) * 0.3))
groups_test_coco[name] = caps[:n_test]
groups_train_coco[name] = caps[n_test:]
print("Encodage SBERT des captions...")
sbert = SentenceTransformer("all-MiniLM-L6-v2", device=str(DEVICE))
all_caps = sorted({c for caps in groups_train_coco.values() for c in caps} |
{c for caps in groups_test_coco.values() for c in caps})
with torch.no_grad():
embs = sbert.encode(all_caps, convert_to_tensor=True, batch_size=64).to(DEVICE)
caption_to_emb = {c: embs[i] for i, c in enumerate(all_caps)}
group_names_coco = [n for n, c in groups_train_coco.items() if len(c) >= 2]
# =====================================================================
# 2. Architecture du Modèle avec Espace Latent à 384 dimensions
# =====================================================================
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__()
# Ajustement de la dimension intermédiaire pour correspondre à 384 d'entrée
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(),
)
# Sortie alignée sur l'espace latent à 384 dimensions
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)
def info_nce_loss(f1, f2, temp=0.07):
f1, f2 = F.normalize(f1, dim=1), F.normalize(f2, dim=1)
sim = torch.matmul(f1, f2.T) / temp
labels = torch.arange(f1.size(0), device=f1.device)
return (F.cross_entropy(sim, labels) + F.cross_entropy(sim.T, labels)) / 2.0
def spatial_variation_loss(sketch, blur_kernel=5):
blurred = F.avg_pool2d(sketch, kernel_size=blur_kernel, stride=1,
padding=blur_kernel // 2, count_include_pad=False)
return -blurred.var(dim=(2, 3)).mean()
# =====================================================================
# 3. Entraînement du modèle avec Latent 384-dim
# =====================================================================
def train_gray_pipeline(caption_to_emb, group_names, groups_train, steps=10000, batch_groups=32,
variation_weight=0.01, log_every=300):
model = EndToEndGrayPipeline(input_dim=384, latent_dim=384).to(DEVICE)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=steps)
batch_groups = min(batch_groups, len(group_names))
model.train()
for step in range(1, steps + 1):
batch = random.sample(group_names, batch_groups)
anchors, positives = [], []
for name in batch:
a_cap, p_cap = random.sample(groups_train[name], 2)
anchors.append(caption_to_emb[a_cap])
positives.append(caption_to_emb[p_cap])
emb_a = torch.stack(anchors, dim=0)
emb_b = torch.stack(positives, dim=0)
optimizer.zero_grad()
_, sketch_a, feat_a = model(emb_a)
_, sketch_b, feat_b = model(emb_b)
loss = info_nce_loss(feat_a, feat_b) + variation_weight * (
spatial_variation_loss(sketch_a) + spatial_variation_loss(sketch_b))
loss.backward()
optimizer.step()
scheduler.step()
if step % log_every == 0 or step == 1:
print(f"[COCO Gris Train 384-dim] pas {step:4d}/{steps} - loss : {loss.item():.4f}")
model.eval()
return model
import os
import torch
from google.colab import drive
#######################
# Montage de Google Drive
drive.mount('/content/drive')
drive_dir = "/content/drive/My Drive"
os.makedirs(drive_dir, exist_ok=True)
model_path = os.path.join(drive_dir, "model_gray_coco30000captions_384dim.pth")
# Instanciation de l'architecture avec latent_dim=384
model_gray_coco = EndToEndGrayPipeline(input_dim=384, latent_dim=384).to(DEVICE)
if os.path.exists(model_path):
print(f"Modèle trouvé sur Google Drive. Chargement depuis : {model_path}")
model_gray_coco.load_state_dict(torch.load(model_path, map_location=DEVICE))
model_gray_coco.eval()
print("Modèle chargé avec succès ! (Étape d'apprentissage ignorée)")
else:
print("Aucun modèle sauvegardé trouvé. Lancement de l'apprentissage (384-dim)...")
model_gray_coco = train_gray_pipeline(caption_to_emb, group_names_coco, groups_train_coco, steps=10000)
torch.save(model_gray_coco.state_dict(), model_path)
print(f"Apprentissage terminé. Modèle sauvegardé avec succès sur Google Drive : {model_path}")
######################
def save_sketches_with_text_to_sample_data(model, queries):
model.eval()
print("\n--- Sauvegarde des sketches (384-dim) dans sample_data (400x800) ---")
saved_images = []
for i, query in enumerate(queries):
with torch.no_grad():
q_emb = sbert.encode(query, convert_to_tensor=True).unsqueeze(0).to(DEVICE)
_, sketch_tensor, _ = model(q_emb)
# Conversion du tenseur PyTorch en tableau numpy 2D (0-255)
sketch_np = (sketch_tensor.squeeze(0).squeeze(0).cpu().numpy() * 255).astype(np.uint8)
# 1. Création de l'image PIL aux dimensions exactes 400x800 (W x H)
img_pil = Image.fromarray(sketch_np).convert("RGB")
img_pil = img_pil.resize((W_SKETCH, H_SKETCH), Image.Resampling.BILINEAR)
# 2. Enregistrement
filename = f"sample_data/sketch_384_{i+1}.png"
img_pil.save(filename)
saved_images.append(img_pil.copy())
print(f"Sauvegardé : {filename}")
return saved_images
# =====================================================================
# 4. Génération et Sauvegarde en 400x800
# =====================================================================
target_queries = [
"A man walks along a pathway through a quiet park during the early morning.",
"The man stops near a large tree and sets down his heavy leather briefcase on the grass.",
"The man opens the bag to take out a professional camera and a small notebook.",
"The man continues his walk toward the edge of the pond to capture photographs of the rising sun.",
"The man packs his gear away and resumes his journey along the path toward the park exit."
]
generated_images = save_sketches_with_text_to_sample_data(model_gray_coco, target_queries)
# =====================================================================
# 5. Génération de la séquence vidéo (3 secondes par croquis)
# =====================================================================
import cv2
def generate_sketch_video(image_paths, output_path="sample_data/hiker_journey_sequence.mp4", duration_per_image=3.0):
print("\n--- Génération de la vidéo des sketches ---")
if not image_paths:
print("Erreur : Aucune image à traiter.")
return
# Charger la première image pour récupérer les dimensions exactes (Largeur, Hauteur)
first_img_path = f"sample_data/sketch_384_1.png"
sample_img = cv2.imread(first_img_path)
if sample_img is None:
print(f"Erreur : Impossible de lire l'image {first_img_path}")
return
height, width, _ = sample_img.shape
# Configuration de la vidéo (30 images par seconde pour une fluidité optimale)
fps = 30
frames_per_image = int(duration_per_image * fps)
# Utilisation du codec MP4V pour un fichier .mp4 standard
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
for i in range(len(image_paths)):
img_path = f"sample_data/sketch_384_{i+1}.png"
frame = cv2.imread(img_path)
if frame is not None:
# Répéter la même image pour atteindre la durée souhaitée (3 secondes)
for _ in range(frames_per_image):
video_writer.write(frame)
print(f"Ajout à la vidéo : {img_path} ({duration_per_image}s)")
video_writer.release()
print(f"Vidéo générée avec succès ! Fichier sauvegardé sous : {output_path}")
# Liste des chemins des images générées précédemment
image_filenames = [f"sample_data/sketch_384_{i+1}.png" for i in range(len(target_queries))]
# Lancement de la création de la vidéo
generate_sketch_video(image_filenames, output_path="sample_data/hiker_journey_sequence.mp4", duration_per_image=3.0) |