Spaces:
Runtime error
Runtime error
Update README.md
#1
by jhomes - opened
README.md
CHANGED
|
@@ -1,14 +1,36 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# Load BLIP model
|
| 7 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 8 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(
|
| 9 |
+
"cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
def caption_images(files):
|
| 13 |
+
results = {}
|
| 14 |
+
for file in files:
|
| 15 |
+
image = Image.open(file.name).convert("RGB")
|
| 16 |
+
inputs = processor(images=image, return_tensors="pt").to(model.device)
|
| 17 |
+
out = model.generate(**inputs, max_length=50)
|
| 18 |
+
caption = processor.decode(out[0], skip_special_tokens=True)
|
| 19 |
+
|
| 20 |
+
# Save caption
|
| 21 |
+
txt_path = file.name.replace(".png", ".txt")
|
| 22 |
+
with open(txt_path, "w") as f:
|
| 23 |
+
f.write(caption)
|
| 24 |
+
|
| 25 |
+
results[file.name] = caption
|
| 26 |
+
return results
|
| 27 |
+
|
| 28 |
+
demo = gr.Interface(
|
| 29 |
+
fn=caption_images,
|
| 30 |
+
inputs=gr.File(file_types=[".png"], file_types_allow_multiple=True),
|
| 31 |
+
outputs="json",
|
| 32 |
+
title="Batch BLIP Captioning"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
demo.launch()
|
| 36 |
+
|