Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +48 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import csv
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
# --- Setup ---
|
| 9 |
+
output_csv = "alt_text_results_blip.csv"
|
| 10 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
|
| 12 |
+
# Load model
|
| 13 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 14 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(device)
|
| 15 |
+
|
| 16 |
+
# --- Main Function ---
|
| 17 |
+
def generate_alt_text(image: Image.Image):
|
| 18 |
+
try:
|
| 19 |
+
inputs = processor(images=image, return_tensors="pt").to(device)
|
| 20 |
+
out = model.generate(**inputs, max_new_tokens=50)
|
| 21 |
+
caption = processor.decode(out[0], skip_special_tokens=True).strip()
|
| 22 |
+
|
| 23 |
+
# Save to CSV
|
| 24 |
+
if not os.path.exists(output_csv):
|
| 25 |
+
with open(output_csv, "w", newline="") as f:
|
| 26 |
+
writer = csv.writer(f)
|
| 27 |
+
writer.writerow(["Filename", "Generated Caption"])
|
| 28 |
+
|
| 29 |
+
with open(output_csv, "a", newline="") as f:
|
| 30 |
+
writer = csv.writer(f)
|
| 31 |
+
writer.writerow(["[inline upload]", caption])
|
| 32 |
+
|
| 33 |
+
return caption
|
| 34 |
+
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"❌ Error: {e}"
|
| 37 |
+
|
| 38 |
+
# --- Gradio UI ---
|
| 39 |
+
demo = gr.Interface(
|
| 40 |
+
fn=generate_alt_text,
|
| 41 |
+
inputs=gr.Image(type="pil", label="Upload an Image"),
|
| 42 |
+
outputs=gr.Textbox(label="Generated Alt Text"),
|
| 43 |
+
title="Alt Text Generator",
|
| 44 |
+
description="Generates alt text for accessibility using the BLIP model from Hugging Face."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
transformers
|
| 3 |
+
torch
|
| 4 |
+
Pillow
|