import os os.system('pip install git+https://github.com/huggingface/transformers --upgrade') import gradio as gr from transformers import ImageGPTFeatureExtractor, ImageGPTForCausalLM import torch import requests from PIL import Image import os import matplotlib.pyplot as plt feature_extractor = ImageGPTFeatureExtractor.from_pretrained("openai/imagegpt-small") model = ImageGPTForCausalLM.from_pretrained("openai/imagegpt-small") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # load image examples urls = ['https://assetsnffrgf-a.akamaihd.net/assets/m/502013285/univ/art/502013285_univ_sqr_xl.jpg'] for idx, url in enumerate(urls): image = Image.open(requests.get(url, stream=True).raw) image.save(f"image_{idx}.png") def process_image(image): # prepare 8 images, shape (8, 1024) encoding = feature_extractor([image for _ in range(8)], return_tensors="pt") # create primers samples = encoding.pixel_values.numpy() n_px_crop = 16 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 # generate (no beam search) context = np.concatenate((np.full((batch_size, 1), model.config.vocab_size - 1), primers), axis=1) context = torch.tensor(context).to(device) output = model.generate(input_ids=context, max_length=n_px*n_px + 1, temperature=1.0, do_sample=True, top_k=40) # decode back to images samples = output[:,1:].cpu().detach().numpy() samples_img = [np.reshape(np.rint(127.5 * (clusters[s] + 1.0)), [n_px, n_px, 3]).astype(np.uint8) for s in samples] # convert color cluster tokens back to pixels # save as list of files completions = [] output_dir = '.' for i in range(len(samples_img)): fname = os.path.join(output_dir, "completion" + str(i) + ".png") plt.imsave(fname=fname, arr=samples_img[i], format='png') completions.append(fname) return completions title = "Interactive demo: ImageGPT" 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." article = "
ImageGPT: Generative Pretraining from Pixels | Official blog
" examples =[["image_0.png"]] iface = gr.Interface(fn=process_image, inputs=gr.inputs.Image(type="pil"), outputs=[gr.outputs.Image(type='file', label=f'completion_{i}') for i in range(len(samples_img))], title=title, description=description, article=article, examples=examples) iface.launch(debug=True)