Spaces:
Sleeping
Sleeping
File size: 1,724 Bytes
0045cd1 4bba8fd 0045cd1 4bba8fd 0045cd1 0d613c0 4bba8fd 0d613c0 4bba8fd 0045cd1 0d613c0 0045cd1 0d613c0 4bba8fd 0045cd1 0d613c0 0045cd1 4bba8fd 0045cd1 0d613c0 0045cd1 4bba8fd 0d613c0 0045cd1 0d613c0 0045cd1 4bba8fd | 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import os
import csv
import gradio as gr
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration
import torch
# --- Config ---
output_csv = "alt_text_results_blip2.csv"
device = "cuda" if torch.cuda.is_available() else "cpu"
# Load processor and model
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained(
"Salesforce/blip2-opt-2.7b",
torch_dtype=torch.float16 if device == "cuda" else torch.float32
).to(device)
# Alt text generation function (no prompt — captioning mode)
def generate_alt_text(image: Image.Image):
try:
inputs = processor(images=image, return_tensors="pt").to(device)
output = model.generate(**inputs, max_new_tokens=100)
caption = processor.decode(output[0], skip_special_tokens=True).strip()
# Save result to CSV
if not os.path.exists(output_csv):
with open(output_csv, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Filename", "Generated Caption"])
with open(output_csv, "a", newline="") as f:
writer = csv.writer(f)
writer.writerow(["[inline upload]", caption])
return caption
except Exception as e:
return f"❌ Error: {str(e)}"
# Gradio UI
demo = gr.Interface(
fn=generate_alt_text,
inputs=gr.Image(type="pil", label="Upload an Image"),
outputs=gr.Textbox(label="Generated Alt Text"),
title="Alt Text Generator (BLIP-2 OPT 2.7B)",
description="Generate concise, accessibility-friendly alt text using the Salesforce BLIP-2 OPT 2.7B model."
)
# Launch
if __name__ == "__main__":
demo.launch() |