Spaces:
Sleeping
Sleeping
Download app.py from Speshal89/blip2-captioning: direct link, hf CLI and curl.
- Browser
- Download file 973 Bytes
-
https://huggingface.co/spaces/Speshal89/blip2-captioning/resolve/main/app.py
- Command line
-
hf download hf://spaces/Speshal89/blip2-captioning/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Speshal89/blip2-captioning/resolve/main/app.py
973 Bytes
| 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() | |