File size: 973 Bytes
b3be43a
 
 
b25f5fe
b3be43a
d4036c2
b3be43a
d4036c2
 
 
 
b25f5fe
b3be43a
d4036c2
 
b25f5fe
d4036c2
 
b25f5fe
 
d4036c2
b25f5fe
d4036c2
b3be43a
d4036c2
 
 
 
 
 
b3be43a
d4036c2
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import gradio as gr
from transformers import Blip2Processor, Blip2ForConditionalGeneration
from PIL import Image
import torch

# Load model and processor
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained(
    "Salesforce/blip2-opt-2.7b",
    torch_dtype=torch.float16
)
model.eval()

def predict_caption(image):
    # Preprocess image
    inputs = processor(images=image, return_tensors="pt")
    
    # Generate caption
    with torch.no_grad():
        generated_ids = model.generate(**inputs, max_new_tokens=50)
    
    caption = processor.decode(generated_ids[0], skip_special_tokens=True)
    return caption  # must return raw string or JSON-serializable object

# Gradio Interface (this is what enables /predict)
demo = gr.Interface(
    fn=predict_caption,
    inputs=gr.Image(type="pil"),
    outputs=gr.Text(label="Caption")
)

# Run app (this registers /predict for POST)
demo.launch()