Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.system('pip install git+https://github.com/huggingface/transformers --upgrade')
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
from transformers import ImageGPTFeatureExtractor, ImageGPTForCausalImageModeling
|
6 |
+
import torch
|
7 |
+
import numpy as np
|
8 |
+
import requests
|
9 |
+
from PIL import Image
|
10 |
+
import matplotlib.pyplot as plt
|
11 |
+
|
12 |
+
feature_extractor = ImageGPTFeatureExtractor.from_pretrained("openai/imagegpt-medium")
|
13 |
+
model = ImageGPTForCausalImageModeling.from_pretrained("openai/imagegpt-medium")
|
14 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
15 |
+
model.to(device)
|
16 |
+
|
17 |
+
# load image examples
|
18 |
+
urls = ['https://i.imgflip.com/4/4t0m5.jpg',
|
19 |
+
'https://cdn.openai.com/image-gpt/completions/igpt-xl-miscellaneous-2-orig.png',
|
20 |
+
'https://cdn.openai.com/image-gpt/completions/igpt-xl-miscellaneous-29-orig.png',
|
21 |
+
'https://cdn.openai.com/image-gpt/completions/igpt-xl-openai-cooking-0-orig.png'
|
22 |
+
]
|
23 |
+
for idx, url in enumerate(urls):
|
24 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
25 |
+
image.save(f"image_{idx}.png")
|
26 |
+
|
27 |
+
def process_image(image):
|
28 |
+
# prepare 7 images, shape (7, 1024)
|
29 |
+
batch_size = 7
|
30 |
+
encoding = feature_extractor([image for _ in range(batch_size)], return_tensors="pt")
|
31 |
+
|
32 |
+
# create primers
|
33 |
+
samples = encoding.input_ids.numpy()
|
34 |
+
n_px = feature_extractor.size
|
35 |
+
clusters = feature_extractor.clusters
|
36 |
+
n_px_crop = 16
|
37 |
+
primers = samples.reshape(-1,n_px*n_px)[:,:n_px_crop*n_px] # crop top n_px_crop rows. These will be the conditioning tokens
|
38 |
+
|
39 |
+
# get conditioned image (from first primer tensor), padded with black pixels to be 32x32
|
40 |
+
primers_img = np.reshape(np.rint(127.5 * (clusters[primers[0]] + 1.0)), [n_px_crop,n_px, 3]).astype(np.uint8)
|
41 |
+
primers_img = np.pad(primers_img, pad_width=((0,16), (0,0), (0,0)), mode="constant")
|
42 |
+
|
43 |
+
# generate (no beam search)
|
44 |
+
context = np.concatenate((np.full((batch_size, 1), model.config.vocab_size - 1), primers), axis=1)
|
45 |
+
context = torch.tensor(context).to(device)
|
46 |
+
output = model.generate(input_ids=context, max_length=n_px*n_px + 1, temperature=1.0, do_sample=True, top_k=40)
|
47 |
+
|
48 |
+
# decode back to images (convert color cluster tokens back to pixels)
|
49 |
+
samples = output[:,1:].cpu().detach().numpy()
|
50 |
+
samples_img = [np.reshape(np.rint(127.5 * (clusters[s] + 1.0)), [n_px, n_px, 3]).astype(np.uint8) for s in samples]
|
51 |
+
|
52 |
+
samples_img = [primers_img] + samples_img
|
53 |
+
|
54 |
+
# stack images horizontally
|
55 |
+
row1 = np.hstack(samples_img[:4])
|
56 |
+
row2 = np.hstack(samples_img[4:])
|
57 |
+
result = np.vstack([row1, row2])
|
58 |
+
|
59 |
+
# return as PIL Image
|
60 |
+
completion = Image.fromarray(result)
|
61 |
+
|
62 |
+
return completion
|
63 |
+
|
64 |
+
title = "Interactive demo: ImageGPT"
|
65 |
+
description = "Demo for OpenAI's ImageGPT: Generative Pretraining from Pixels. To use it, simply upload an image or use the example image below and click 'submit'. Results will show up in a few seconds."
|
66 |
+
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2109.10282'>ImageGPT: Generative Pretraining from Pixels</a> | <a href='https://openai.com/blog/image-gpt/'>Official blog</a></p>"
|
67 |
+
examples =[f"image_{idx}.png" for idx in range(len(urls))]
|
68 |
+
|
69 |
+
iface = gr.Interface(fn=process_image,
|
70 |
+
inputs=gr.inputs.Image(type="pil"),
|
71 |
+
outputs=gr.outputs.Image(type="pil", label="Model input + completions"),
|
72 |
+
title=title,
|
73 |
+
description=description,
|
74 |
+
article=article,
|
75 |
+
examples=examples,
|
76 |
+
enable_queue=True)
|
77 |
+
iface.launch(debug=True)
|