Views
No views yet

Transformers librairie. You will also need to install the Taming Transformers library for high-resolution image synthesis:pip install git+https://github.com/CompVis/taming-transformers.git1from transformers import GPT2Tokenizer, GPT2LMHeadModel
2from huggingface_hub import hf_hub_download
3from omegaconf import OmegaConf
4from taming.models import vqgan
5import torch
6from PIL import Image
7import numpy as np
8
9# Load VQGAN model
10vqgan_ckpt = hf_hub_download(repo_id="boris/vqgan_f16_16384", filename="model.ckpt", force_download=False)
11vqgan_config = hf_hub_download(repo_id="boris/vqgan_f16_16384", filename="config.yaml", force_download=False)
12
13config = OmegaConf.load(vqgan_config)
14vqgan_model = vqgan.VQModel(**config.model.params)
15vqgan_model.eval().requires_grad_(False)
16vqgan_model.init_from_ckpt(vqgan_ckpt)
17
18# Load pretrained model
19model = GPT2LMHeadModel.from_pretrained("asi/igpt-fr-cased-base")
20model.eval()
21tokenizer = GPT2Tokenizer.from_pretrained("asi/igpt-fr-cased-base")
22
23# Generate a sample of text
24input_sentence = "Une carte de l'europe"
25input_ids = tokenizer.encode(input_sentence, return_tensors='pt')
26input_ids = torch.cat((input_ids, torch.tensor([[50000]])), 1) # Add image generation token
27
28greedy_output = model.generate(
29 input_ids.to(device),
30 max_length=256+input_ids.shape[1],
31 do_sample=True,
32 top_p=0.92,
33 top_k=0)
34
35def custom_to_pil(x):
36 x = x.detach().cpu()
37 x = torch.clamp(x, -1., 1.)
38 x = (x + 1.)/2.
39 x = x.permute(1,2,0).numpy()
40 x = (255*x).astype(np.uint8)
41 x = Image.fromarray(x)
42 if not x.mode == "RGB":
43 x = x.convert("RGB")
44 return x
45
46z_idx = greedy_output[0, input_ids.shape[1]:] - 50001
47z_quant = vqgan_model.quantize.get_codebook_entry(z_idx, shape=(1, 16, 16, 256))
48x_rec = vqgan_model.decode(z_quant).to('cpu')[0]
49display(custom_to_pil(x_rec))1from tqdm import tqdm
2
3def hallucinate(prompt, num_images=64):
4 input_ids = tokenizer.encode(prompt, return_tensors='pt')
5 input_ids = torch.cat((input_ids, torch.tensor([[50000]])), 1).to(device) # Add image generation token
6
7 all_images = []
8 for i in tqdm(range(num_images)):
9 greedy_output = model.generate(
10 input_ids.to(device),
11 max_length=256+input_ids.shape[1],
12 do_sample=True,
13 top_p=0.92,
14 top_k=0)
15
16 z_idx = greedy_output[0, input_ids.shape[1]:] - 50001
17 z_quant = vqgan_model.quantize.get_codebook_entry(z_idx, shape=(1, 16, 16, 256))
18 x_rec = vqgan_model.decode(z_quant).to('cpu')[0]
19 all_images.append(custom_to_pil(x_rec))
20 return all_images
21
22input_sentence = "Une carte de l'europe"
23all_images = hallucinate(input_sentence)
24
25from transformers import pipeline
26
27opus_model = "Helsinki-NLP/opus-mt-fr-en"
28opus_translator = pipeline("translation", model=opus_model)
29
30opus_translator(input_sentence)
31
32from transformers import CLIPProcessor, CLIPModel
33
34clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
35clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
36
37def clip_top_k(prompt, images, k=8):
38 prompt_fr = opus_translator(input_sentence)[0]['translation_text']
39 inputs = clip_processor(text=prompt_fr, images=images, return_tensors="pt", padding=True)
40 outputs = clip_model(**inputs)
41 logits = outputs.logits_per_text # this is the image-text similarity score
42 scores = np.array(logits[0].detach()).argsort()[-k:][::-1]
43 return [images[score] for score in scores]
44
45filtered_images = clip_top_k(input_sentence, all_images)
46
47for fi in filtered_images:
48 display(fi)