Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
# Load BLIP2 model and processor
|
| 7 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 8 |
+
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 9 |
+
model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16 if device == "cuda" else torch.float32)
|
| 10 |
+
model.to(device)
|
| 11 |
+
|
| 12 |
+
def caption_image(image):
|
| 13 |
+
inputs = processor(image, return_tensors="pt").to(device, torch.float16 if device == "cuda" else torch.float32)
|
| 14 |
+
output = model.generate(**inputs, max_new_tokens=30)
|
| 15 |
+
caption = processor.decode(output[0], skip_special_tokens=True)
|
| 16 |
+
return caption
|
| 17 |
+
|
| 18 |
+
# Gradio interface (no UI, just API endpoint)
|
| 19 |
+
iface = gr.Interface(fn=caption_image, inputs=gr.Image(type="pil"), outputs="text")
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
iface.launch()
|