Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,17 +3,31 @@ from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
|
| 3 |
from PIL import Image
|
| 4 |
import torch
|
| 5 |
|
|
|
|
| 6 |
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 7 |
-
model = Blip2ForConditionalGeneration.from_pretrained(
|
|
|
|
|
|
|
|
|
|
| 8 |
model.eval()
|
| 9 |
|
| 10 |
-
def
|
|
|
|
| 11 |
inputs = processor(images=image, return_tensors="pt")
|
|
|
|
|
|
|
| 12 |
with torch.no_grad():
|
| 13 |
generated_ids = model.generate(**inputs, max_new_tokens=50)
|
|
|
|
| 14 |
caption = processor.decode(generated_ids[0], skip_special_tokens=True)
|
| 15 |
-
return
|
| 16 |
|
| 17 |
-
|
| 18 |
-
demo.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
|
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import torch
|
| 5 |
|
| 6 |
+
# Load model and processor
|
| 7 |
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 8 |
+
model = Blip2ForConditionalGeneration.from_pretrained(
|
| 9 |
+
"Salesforce/blip2-opt-2.7b",
|
| 10 |
+
torch_dtype=torch.float16
|
| 11 |
+
)
|
| 12 |
model.eval()
|
| 13 |
|
| 14 |
+
def predict_caption(image):
|
| 15 |
+
# Preprocess image
|
| 16 |
inputs = processor(images=image, return_tensors="pt")
|
| 17 |
+
|
| 18 |
+
# Generate caption
|
| 19 |
with torch.no_grad():
|
| 20 |
generated_ids = model.generate(**inputs, max_new_tokens=50)
|
| 21 |
+
|
| 22 |
caption = processor.decode(generated_ids[0], skip_special_tokens=True)
|
| 23 |
+
return caption # must return raw string or JSON-serializable object
|
| 24 |
|
| 25 |
+
# Gradio Interface (this is what enables /predict)
|
| 26 |
+
demo = gr.Interface(
|
| 27 |
+
fn=predict_caption,
|
| 28 |
+
inputs=gr.Image(type="pil"),
|
| 29 |
+
outputs=gr.Text(label="Caption")
|
| 30 |
+
)
|
| 31 |
|
| 32 |
+
# Run app (this registers /predict for POST)
|
| 33 |
+
demo.launch()
|