Spaces:
Sleeping
Sleeping
Download app.py from siddhatey/alt-text-generator: direct link, hf CLI and curl.
- Browser
- Download file 1.72 kB
-
https://huggingface.co/spaces/siddhatey/alt-text-generator/resolve/main/app.py
- Command line
-
hf download hf://spaces/siddhatey/alt-text-generator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/siddhatey/alt-text-generator/resolve/main/app.py
1.72 kB
| 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() |