Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pathlib
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import open_clip
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 8 |
+
|
| 9 |
+
model, _, transform = open_clip.create_model_and_transforms(
|
| 10 |
+
"coca_ViT-L-14",
|
| 11 |
+
pretrained="mscoco_finetuned_laion2B-s13B-b90k"
|
| 12 |
+
)
|
| 13 |
+
model.to(device)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def output_generate(image):
|
| 17 |
+
im = transform(image).unsqueeze(0).to(device)
|
| 18 |
+
with torch.no_grad(), torch.cuda.amp.autocast():
|
| 19 |
+
generated = model.generate(im, seq_len=20)
|
| 20 |
+
return open_clip.decode(generated[0].detach()).split("<end_of_text>")[0].replace("<start_of_text>", "")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
paths = sorted(pathlib.Path("images").glob("*.jpg"))
|
| 24 |
+
|
| 25 |
+
iface = gr.Interface(
|
| 26 |
+
fn=output_generate,
|
| 27 |
+
inputs=gr.Image(label="Input image", type="pil"),
|
| 28 |
+
outputs=gr.Text(label="Caption output"),
|
| 29 |
+
title="CoCa: Contrastive Captioners",
|
| 30 |
+
description=(
|
| 31 |
+
"""<br> An open source implementation of <strong>CoCa: Contrastive Captioners are Image-Text Foundation Models</strong> <a href=https://arxiv.org/abs/2205.01917>https://arxiv.org/abs/2205.01917.</a>
|
| 32 |
+
<br> Built using <a href=https://github.com/mlfoundations/open_clip>open_clip</a> with an effort from <a href=https://laion.ai/>LAION</a>.
|
| 33 |
+
<br> For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.<a href="https://huggingface.co/spaces/laion/CoCa?duplicate=true"> <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>"""
|
| 34 |
+
),
|
| 35 |
+
article="""""",
|
| 36 |
+
examples=[path.as_posix() for path in paths],
|
| 37 |
+
)
|
| 38 |
+
iface.launch()
|