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()