Spaces:
Sleeping
Sleeping
Create image_to_text_blip.py
Browse files- image_to_text_blip.py +32 -0
image_to_text_blip.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# Load BLIP model and processor
|
| 7 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 8 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16)
|
| 9 |
+
model.eval()
|
| 10 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
model.to(device)
|
| 12 |
+
|
| 13 |
+
# Inference function
|
| 14 |
+
def generate_caption(image):
|
| 15 |
+
if image.mode != "RGB":
|
| 16 |
+
image = image.convert("RGB")
|
| 17 |
+
|
| 18 |
+
inputs = processor(image, return_tensors="pt").to(device, torch.float16)
|
| 19 |
+
output = model.generate(**inputs, max_new_tokens=50)
|
| 20 |
+
caption = processor.decode(output[0], skip_special_tokens=True)
|
| 21 |
+
return caption
|
| 22 |
+
|
| 23 |
+
# Gradio interface
|
| 24 |
+
iface = gr.Interface(
|
| 25 |
+
fn=generate_caption,
|
| 26 |
+
inputs=gr.Image(type="pil"),
|
| 27 |
+
outputs="text",
|
| 28 |
+
title="Construction Site Image-to-Text Generator",
|
| 29 |
+
description="Upload a site photo. The model will detect and describe construction activities."
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
iface.launch()
|