CoolFace
Apppublic

twobob/imagegpt

sourceHugging Faceupdated 4y agoView on Hugging Face
2likes
app.py77 linesDownload Raw Back to root
1import os2os.system('pip install git+https://github.com/huggingface/transformers --upgrade')3 4import gradio as gr5from transformers import ImageGPTFeatureExtractor, ImageGPTForCausalImageModeling6import torch7import numpy as np8import requests9from PIL import Image10import matplotlib.pyplot as plt11 12feature_extractor = ImageGPTFeatureExtractor.from_pretrained("openai/imagegpt-medium")13model = ImageGPTForCausalImageModeling.from_pretrained("openai/imagegpt-medium")14device = torch.device("cuda" if torch.cuda.is_available() else "cpu")15model.to(device)16 17# load image examples18urls = ['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        ]23for idx, url in enumerate(urls):24  image = Image.open(requests.get(url, stream=True).raw)25  image.save(f"image_{idx}.png")26 27def process_image(image):28    # prepare 7 images, shape (7, 1024)29    batch_size = 730    encoding = feature_extractor([image for _ in range(batch_size)], return_tensors="pt")31 32    # create primers33    samples = encoding.input_ids.numpy()34    n_px = feature_extractor.size35    clusters = feature_extractor.clusters36    n_px_crop = 1637    primers = samples.reshape(-1,n_px*n_px)[:,:n_px_crop*n_px] # crop top n_px_crop rows. These will be the conditioning tokens38    39    # get conditioned image (from first primer tensor), padded with black pixels to be 32x3240    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_img53    54    # stack images horizontally55    row1 = np.hstack(samples_img[:4])56    row2 = np.hstack(samples_img[4:])57    result = np.vstack([row1, row2])58    59    # return as PIL Image60    completion = Image.fromarray(result)61 62    return completion63 64title = "Interactive demo: ImageGPT"65description = "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."66article = "<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>"67examples =[f"image_{idx}.png" for idx in range(len(urls))]68 69iface = 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)77iface.launch(debug=True)