Update app.py
Browse files
app.py
CHANGED
|
@@ -5,23 +5,23 @@ import torch
|
|
| 5 |
from PIL import Image
|
| 6 |
from concurrent.futures import ThreadPoolExecutor
|
| 7 |
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 8 |
-
from functools import lru_cache
|
|
|
|
| 9 |
|
| 10 |
# 1. Configuration and Global Variables
|
| 11 |
-
# Centralize configuration for easier modification
|
| 12 |
class Config:
|
| 13 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
BLIP_MODEL_NAME = "Salesforce/blip-image-captioning-base"
|
| 15 |
-
YOLO_MODEL_NAME = "yolov5s"
|
| 16 |
EASYOCR_LANGUAGES = ["en"]
|
| 17 |
-
MAX_CAPTION_LENGTH = 75
|
| 18 |
-
MIN_CAPTION_LENGTH = 5
|
| 19 |
NUM_BLIP_BEAMS = 5
|
| 20 |
NO_REPEAT_NGRAM_SIZE = 2
|
| 21 |
-
CPU_CORES = os.cpu_count() or 4
|
| 22 |
|
| 23 |
# 2. Model Loading (with caching for efficiency)
|
| 24 |
-
@lru_cache(maxsize=1)
|
| 25 |
def load_blip_model():
|
| 26 |
"""Loads the BLIP model and processor."""
|
| 27 |
print(f"Loading BLIP model '{Config.BLIP_MODEL_NAME}' to {Config.DEVICE}...")
|
|
@@ -30,13 +30,13 @@ def load_blip_model():
|
|
| 30 |
print("BLIP model loaded.")
|
| 31 |
return processor, model
|
| 32 |
|
| 33 |
-
@lru_cache(maxsize=1)
|
| 34 |
def load_ocr_reader():
|
| 35 |
"""Initializes EasyOCR reader."""
|
| 36 |
print(f"Initializing EasyOCR reader for languages {Config.EASYOCR_LANGUAGES} (GPU: {torch.cuda.is_available()})...")
|
| 37 |
return easyocr.Reader(Config.EASYOCR_LANGUAGES, gpu=torch.cuda.is_available())
|
| 38 |
|
| 39 |
-
@lru_cache(maxsize=1)
|
| 40 |
def load_yolo_model():
|
| 41 |
"""Optionally loads YOLOv5 for object detection."""
|
| 42 |
try:
|
|
@@ -54,11 +54,42 @@ def load_yolo_model():
|
|
| 54 |
print(f"Error loading YOLO model: {e}. Object detection will be disabled.")
|
| 55 |
return None
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# Load models once at startup
|
| 58 |
blip_processor, blip_model = load_blip_model()
|
| 59 |
ocr_reader = load_ocr_reader()
|
| 60 |
yolo_model = load_yolo_model()
|
| 61 |
-
use_yolo = yolo_model is not None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
# 3. Core Processing Function
|
| 64 |
def process_single_image(image_path, max_alt_text_len):
|
|
@@ -70,14 +101,13 @@ def process_single_image(image_path, max_alt_text_len):
|
|
| 70 |
print(f"Processing image: {filename}")
|
| 71 |
|
| 72 |
try:
|
| 73 |
-
# Open and convert image once
|
| 74 |
image = Image.open(image_path).convert('RGB')
|
| 75 |
-
image.verify()
|
| 76 |
except Exception as e:
|
| 77 |
print(f"Error opening or verifying file {filename}: {e}")
|
|
|
|
| 78 |
return filename, f"<Error opening or verifying file: {e}>"
|
| 79 |
|
| 80 |
-
# Initialize results
|
| 81 |
blip_caption = ""
|
| 82 |
object_labels = ""
|
| 83 |
ocr_text = ""
|
|
@@ -89,107 +119,104 @@ def process_single_image(image_path, max_alt_text_len):
|
|
| 89 |
**inputs,
|
| 90 |
num_beams=Config.NUM_BLIP_BEAMS,
|
| 91 |
max_length=Config.MAX_CAPTION_LENGTH,
|
| 92 |
-
min_length=Config.MIN_CAPTION_LENGTH,
|
| 93 |
no_repeat_ngram_size=Config.NO_REPEAT_NGRAM_SIZE
|
| 94 |
)
|
| 95 |
blip_caption = blip_processor.decode(output_ids[0], skip_special_tokens=True).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
print(f"Error generating BLIP caption for {filename}: {e}")
|
| 98 |
-
|
| 99 |
-
blip_caption = f"BLIP error: {e}" # Indicate BLIP error within caption if others succeed
|
| 100 |
|
| 101 |
-
# OCR
|
| 102 |
try:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
ocr_text = ' '.join(texts).strip()
|
| 107 |
except Exception as e:
|
| 108 |
print(f"Error performing OCR for {filename}: {e}")
|
| 109 |
-
ocr_text = ''
|
| 110 |
|
| 111 |
# Object detection
|
| 112 |
if use_yolo:
|
| 113 |
try:
|
| 114 |
-
# YOLO can also take file path directly
|
| 115 |
results = yolo_model(image_path)
|
| 116 |
-
# Access results based on ultralytics YOLO's structure
|
| 117 |
-
# For a single image, results will be a list with one item
|
| 118 |
if results and len(results) > 0:
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
# or results[0].names might be needed for direct access.
|
| 122 |
-
# Assuming .pandas() for compatibility with original code's approach.
|
| 123 |
-
df = results[0].pandas().xyxy[0] # Assuming results[0] is the detection object
|
| 124 |
-
labels_list = df['name'].unique().tolist()[:5] # Limit to top 5 unique objects
|
| 125 |
object_labels = ', '.join(labels_list)
|
|
|
|
|
|
|
|
|
|
| 126 |
else:
|
| 127 |
object_labels = ''
|
| 128 |
except Exception as e:
|
| 129 |
print(f"Error performing object detection for {filename}: {e}")
|
| 130 |
-
object_labels = ''
|
| 131 |
|
| 132 |
-
# Assemble
|
| 133 |
parts = []
|
| 134 |
-
# Always
|
| 135 |
if blip_caption:
|
| 136 |
parts.append(blip_caption)
|
| 137 |
|
|
|
|
| 138 |
if object_labels:
|
| 139 |
-
parts.append(f"Objects: {object_labels}")
|
| 140 |
-
if ocr_text:
|
| 141 |
-
parts.append(f"Text: {ocr_text}")
|
| 142 |
|
| 143 |
-
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
#
|
|
|
|
|
|
|
| 146 |
if len(alt_text) > max_alt_text_len:
|
| 147 |
-
# Find the last space before truncation point
|
| 148 |
truncated_text = alt_text[:max_alt_text_len]
|
| 149 |
last_space_index = truncated_text.rfind(' ')
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
alt_text = truncated_text[:last_space_index] + '…'
|
| 154 |
else:
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
print(f"Finished processing {filename}. Alt text length: {len(alt_text)}")
|
| 159 |
-
return filename, alt_text
|
| 160 |
|
| 161 |
def generate_alt_text_for_files(file_objs, max_alt_text_len):
|
| 162 |
"""
|
| 163 |
Generates alt text for multiple image files in parallel.
|
|
|
|
| 164 |
"""
|
| 165 |
if not file_objs:
|
| 166 |
return "No files uploaded."
|
| 167 |
|
| 168 |
-
# file_obj.name gives the path for temp files uploaded to Gradio
|
| 169 |
image_paths = [getattr(f, 'name', f) for f in file_objs]
|
| 170 |
print(f"Generating alt text for {len(image_paths)} files.")
|
| 171 |
|
| 172 |
-
# Use ThreadPoolExecutor for concurrent processing
|
| 173 |
-
# The number of workers can be tuned, but Config.CPU_CORES is a good starting point.
|
| 174 |
-
# For GPU-heavy tasks like BLIP, too many threads might saturate the GPU.
|
| 175 |
-
# Consider adjusting based on your specific GPU/CPU setup.
|
| 176 |
max_workers = min(len(image_paths), Config.CPU_CORES)
|
| 177 |
|
| 178 |
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 179 |
-
# Map the single image processing function to each file path
|
| 180 |
-
# executor.map returns results in the order the tasks were submitted
|
| 181 |
results = list(executor.map(lambda p: process_single_image(p, max_alt_text_len), image_paths))
|
| 182 |
|
| 183 |
-
#
|
| 184 |
-
lines = [f"{
|
| 185 |
return "\n".join(lines)
|
| 186 |
|
| 187 |
# 4. Gradio Interface (UI/UX Improvements)
|
| 188 |
-
with gr.Blocks(title="AI-Powered Alt Text Generator", theme=gr.themes.Soft()) as app:
|
| 189 |
gr.Markdown("# ✨ AI-Powered Alt Text Generator ✨")
|
| 190 |
gr.Markdown(
|
| 191 |
"Upload images to generate rich alt text using **BLIP** for captions, "
|
| 192 |
-
"**EasyOCR** for visible text, and optional **YOLOv5** for object detection. "
|
| 193 |
"Models are loaded once for faster subsequent processing."
|
| 194 |
)
|
| 195 |
|
|
@@ -199,72 +226,61 @@ with gr.Blocks(title="AI-Powered Alt Text Generator", theme=gr.themes.Soft()) as
|
|
| 199 |
label="Upload Images",
|
| 200 |
file_count="multiple",
|
| 201 |
file_types=["image"],
|
| 202 |
-
interactive=True,
|
| 203 |
height=200
|
| 204 |
)
|
| 205 |
-
# Moved slider to be more prominent and clearer
|
| 206 |
max_len_slider = gr.Slider(
|
| 207 |
-
50, 500, step=10, value=250,
|
| 208 |
label="Maximum Alt Text Length (characters)",
|
| 209 |
info="Truncates the generated alt text to this length, preserving word boundaries.",
|
| 210 |
interactive=True
|
| 211 |
)
|
| 212 |
|
| 213 |
with gr.Row():
|
| 214 |
-
gen_btn = gr.Button("🚀 Generate Alt Text", variant="primary")
|
| 215 |
-
copy_btn = gr.Button("📋 Copy to Clipboard", variant="secondary")
|
| 216 |
|
| 217 |
with gr.Column(scale=3):
|
| 218 |
-
# Gallery to preview uploaded images
|
| 219 |
gallery = gr.Gallery(
|
| 220 |
label="Uploaded Image Previews",
|
| 221 |
columns=4,
|
| 222 |
rows=1,
|
| 223 |
object_fit="contain",
|
| 224 |
-
height="auto"
|
| 225 |
)
|
| 226 |
-
# Output textbox with a clear ID for JS
|
| 227 |
output_text = gr.Textbox(
|
| 228 |
label="Generated Alt Text",
|
| 229 |
-
lines=15,
|
| 230 |
interactive=False,
|
| 231 |
-
elem_id="output_text",
|
| 232 |
-
show_copy_button=True
|
| 233 |
)
|
| 234 |
|
| 235 |
-
# Event Handlers
|
| 236 |
-
# Using 'change' for file_input to update gallery immediately on upload
|
| 237 |
file_input.change(fn=lambda files: files, inputs=file_input, outputs=gallery)
|
| 238 |
|
| 239 |
-
# Main generation button click
|
| 240 |
gen_btn.click(
|
| 241 |
fn=generate_alt_text_for_files,
|
| 242 |
inputs=[file_input, max_len_slider],
|
| 243 |
outputs=[output_text],
|
| 244 |
-
queue=True,
|
| 245 |
-
# show_progress=True # Gradio 4.x handles progress bar by default now for queued functions
|
| 246 |
)
|
| 247 |
|
| 248 |
-
# Custom JS for copy to clipboard if show_copy_button is not enough or for older Gradio versions
|
| 249 |
-
# Note: Gradio 4.x has `show_copy_button=True` for Textbox which is often sufficient.
|
| 250 |
-
# This custom JS is provided as an alternative if needed, but the built-in one is generally better.
|
| 251 |
copy_btn.click(
|
| 252 |
-
None,
|
| 253 |
-
inputs=None,
|
| 254 |
-
outputs=None,
|
| 255 |
js="""
|
| 256 |
() => {
|
| 257 |
const outputElement = document.getElementById('output_text');
|
| 258 |
if (outputElement) {
|
| 259 |
-
// Use the modern clipboard API if available, fallback to execCommand
|
| 260 |
if (navigator.clipboard && navigator.clipboard.writeText) {
|
| 261 |
navigator.clipboard.writeText(outputElement.value)
|
| 262 |
.then(() => alert('Alt text copied to clipboard!'))
|
| 263 |
.catch(err => console.error('Failed to copy text: ', err));
|
| 264 |
} else {
|
| 265 |
-
outputElement.select();
|
| 266 |
-
document.execCommand('copy');
|
| 267 |
-
alert('Alt text copied to clipboard!');
|
| 268 |
}
|
| 269 |
} else {
|
| 270 |
alert('Output text element not found.');
|
|
@@ -278,7 +294,7 @@ with gr.Blocks(title="AI-Powered Alt Text Generator", theme=gr.themes.Soft()) as
|
|
| 278 |
---
|
| 279 |
**How it works:**
|
| 280 |
- **BLIP:** Generates a descriptive caption of the image's content.
|
| 281 |
-
- **EasyOCR:** Detects and extracts visible text within the image.
|
| 282 |
- **YOLOv5 (Optional):** Identifies and lists prominent objects. (Requires `ultralytics` library)
|
| 283 |
|
| 284 |
This tool is a demonstration and may not be perfect for all images.
|
|
@@ -286,15 +302,14 @@ with gr.Blocks(title="AI-Powered Alt Text Generator", theme=gr.themes.Soft()) as
|
|
| 286 |
"""
|
| 287 |
)
|
| 288 |
|
| 289 |
-
# For local testing
|
| 290 |
def main():
|
| 291 |
print(f"\nStarting Gradio app on device: {Config.DEVICE}")
|
| 292 |
print(f"YOLO enabled: {use_yolo}\n")
|
| 293 |
app.launch(
|
| 294 |
-
server_name="0.0.0.0",
|
| 295 |
-
server_port=7860,
|
| 296 |
-
share=True,
|
| 297 |
-
debug=True
|
| 298 |
)
|
| 299 |
|
| 300 |
if __name__ == "__main__":
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
from concurrent.futures import ThreadPoolExecutor
|
| 7 |
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 8 |
+
from functools import lru_cache
|
| 9 |
+
from spellchecker import SpellChecker # Import for spell checking
|
| 10 |
|
| 11 |
# 1. Configuration and Global Variables
|
|
|
|
| 12 |
class Config:
|
| 13 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
BLIP_MODEL_NAME = "Salesforce/blip-image-captioning-base"
|
| 15 |
+
YOLO_MODEL_NAME = "yolov5s"
|
| 16 |
EASYOCR_LANGUAGES = ["en"]
|
| 17 |
+
MAX_CAPTION_LENGTH = 75
|
| 18 |
+
MIN_CAPTION_LENGTH = 5
|
| 19 |
NUM_BLIP_BEAMS = 5
|
| 20 |
NO_REPEAT_NGRAM_SIZE = 2
|
| 21 |
+
CPU_CORES = os.cpu_count() or 4
|
| 22 |
|
| 23 |
# 2. Model Loading (with caching for efficiency)
|
| 24 |
+
@lru_cache(maxsize=1)
|
| 25 |
def load_blip_model():
|
| 26 |
"""Loads the BLIP model and processor."""
|
| 27 |
print(f"Loading BLIP model '{Config.BLIP_MODEL_NAME}' to {Config.DEVICE}...")
|
|
|
|
| 30 |
print("BLIP model loaded.")
|
| 31 |
return processor, model
|
| 32 |
|
| 33 |
+
@lru_cache(maxsize=1)
|
| 34 |
def load_ocr_reader():
|
| 35 |
"""Initializes EasyOCR reader."""
|
| 36 |
print(f"Initializing EasyOCR reader for languages {Config.EASYOCR_LANGUAGES} (GPU: {torch.cuda.is_available()})...")
|
| 37 |
return easyocr.Reader(Config.EASYOCR_LANGUAGES, gpu=torch.cuda.is_available())
|
| 38 |
|
| 39 |
+
@lru_cache(maxsize=1)
|
| 40 |
def load_yolo_model():
|
| 41 |
"""Optionally loads YOLOv5 for object detection."""
|
| 42 |
try:
|
|
|
|
| 54 |
print(f"Error loading YOLO model: {e}. Object detection will be disabled.")
|
| 55 |
return None
|
| 56 |
|
| 57 |
+
@lru_cache(maxsize=1)
|
| 58 |
+
def load_spell_checker():
|
| 59 |
+
"""Loads a spell checker."""
|
| 60 |
+
print("Loading spell checker...")
|
| 61 |
+
return SpellChecker()
|
| 62 |
+
|
| 63 |
# Load models once at startup
|
| 64 |
blip_processor, blip_model = load_blip_model()
|
| 65 |
ocr_reader = load_ocr_reader()
|
| 66 |
yolo_model = load_yolo_model()
|
| 67 |
+
use_yolo = yolo_model is not None
|
| 68 |
+
spell = load_spell_checker() # Initialize spell checker
|
| 69 |
+
|
| 70 |
+
# Helper function for OCR text cleanup
|
| 71 |
+
def clean_ocr_text(text):
|
| 72 |
+
if not text:
|
| 73 |
+
return ""
|
| 74 |
+
|
| 75 |
+
# 1. Basic Spell Correction
|
| 76 |
+
words = text.split()
|
| 77 |
+
corrected_words = [spell.correction(word) if spell.correction(word) is not None else word for word in words]
|
| 78 |
+
cleaned_text = ' '.join(corrected_words)
|
| 79 |
+
|
| 80 |
+
# 2. Case Normalization (e.g., sentence case)
|
| 81 |
+
cleaned_text = cleaned_text.lower() # Convert to lowercase first
|
| 82 |
+
if cleaned_text:
|
| 83 |
+
cleaned_text = cleaned_text[0].upper() + cleaned_text[1:] # Capitalize first letter
|
| 84 |
+
|
| 85 |
+
# 3. Add punctuation (simple heuristic: add a period if missing)
|
| 86 |
+
if cleaned_text and not cleaned_text.endswith(('.', '!', '?')):
|
| 87 |
+
cleaned_text += '.'
|
| 88 |
+
|
| 89 |
+
# Remove excessive spaces
|
| 90 |
+
cleaned_text = ' '.join(cleaned_text.split())
|
| 91 |
+
|
| 92 |
+
return cleaned_text
|
| 93 |
|
| 94 |
# 3. Core Processing Function
|
| 95 |
def process_single_image(image_path, max_alt_text_len):
|
|
|
|
| 101 |
print(f"Processing image: {filename}")
|
| 102 |
|
| 103 |
try:
|
|
|
|
| 104 |
image = Image.open(image_path).convert('RGB')
|
| 105 |
+
image.verify()
|
| 106 |
except Exception as e:
|
| 107 |
print(f"Error opening or verifying file {filename}: {e}")
|
| 108 |
+
# Return only the error message, not filename in output string
|
| 109 |
return filename, f"<Error opening or verifying file: {e}>"
|
| 110 |
|
|
|
|
| 111 |
blip_caption = ""
|
| 112 |
object_labels = ""
|
| 113 |
ocr_text = ""
|
|
|
|
| 119 |
**inputs,
|
| 120 |
num_beams=Config.NUM_BLIP_BEAMS,
|
| 121 |
max_length=Config.MAX_CAPTION_LENGTH,
|
| 122 |
+
min_length=Config.MIN_CAPTION_LENGTH,
|
| 123 |
no_repeat_ngram_size=Config.NO_REPEAT_NGRAM_SIZE
|
| 124 |
)
|
| 125 |
blip_caption = blip_processor.decode(output_ids[0], skip_special_tokens=True).strip()
|
| 126 |
+
# Capitalize BLIP caption for better sentence structure
|
| 127 |
+
if blip_caption:
|
| 128 |
+
blip_caption = blip_caption[0].upper() + blip_caption[1:]
|
| 129 |
+
if not blip_caption.endswith(('.', '!', '?')):
|
| 130 |
+
blip_caption += '.'
|
| 131 |
except Exception as e:
|
| 132 |
print(f"Error generating BLIP caption for {filename}: {e}")
|
| 133 |
+
blip_caption = f"Error generating primary caption."
|
|
|
|
| 134 |
|
| 135 |
+
# OCR and Cleanup
|
| 136 |
try:
|
| 137 |
+
texts = ocr_reader.readtext(image_path, detail=0)
|
| 138 |
+
raw_ocr = ' '.join(texts).strip()
|
| 139 |
+
ocr_text = clean_ocr_text(raw_ocr) # Apply cleanup
|
|
|
|
| 140 |
except Exception as e:
|
| 141 |
print(f"Error performing OCR for {filename}: {e}")
|
| 142 |
+
ocr_text = ''
|
| 143 |
|
| 144 |
# Object detection
|
| 145 |
if use_yolo:
|
| 146 |
try:
|
|
|
|
| 147 |
results = yolo_model(image_path)
|
|
|
|
|
|
|
| 148 |
if results and len(results) > 0:
|
| 149 |
+
df = results[0].pandas().xyxy[0]
|
| 150 |
+
labels_list = df['name'].unique().tolist()[:5]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
object_labels = ', '.join(labels_list)
|
| 152 |
+
# Capitalize object labels for consistency
|
| 153 |
+
if object_labels:
|
| 154 |
+
object_labels = object_labels[0].upper() + object_labels[1:]
|
| 155 |
else:
|
| 156 |
object_labels = ''
|
| 157 |
except Exception as e:
|
| 158 |
print(f"Error performing object detection for {filename}: {e}")
|
| 159 |
+
object_labels = ''
|
| 160 |
|
| 161 |
+
# Assemble alt text
|
| 162 |
parts = []
|
| 163 |
+
# Always start with BLIP caption as the primary description
|
| 164 |
if blip_caption:
|
| 165 |
parts.append(blip_caption)
|
| 166 |
|
| 167 |
+
# Add objects if detected
|
| 168 |
if object_labels:
|
| 169 |
+
parts.append(f"Objects detected: {object_labels}.") # More natural phrasing
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
# Add cleaned OCR text if found
|
| 172 |
+
if ocr_text:
|
| 173 |
+
parts.append(f"Visible text: \"{ocr_text}\"") # Clearly distinguish OCR text
|
| 174 |
|
| 175 |
+
alt_text = ' '.join(filter(None, parts)) # Join with space, not semicolon, for better flow
|
| 176 |
+
|
| 177 |
+
# Final truncation, ensuring word boundaries and ellipsis
|
| 178 |
if len(alt_text) > max_alt_text_len:
|
|
|
|
| 179 |
truncated_text = alt_text[:max_alt_text_len]
|
| 180 |
last_space_index = truncated_text.rfind(' ')
|
| 181 |
|
| 182 |
+
if last_space_index != -1 and last_space_index > max_alt_text_len * 0.8: # Ensure meaningful truncation
|
| 183 |
+
alt_text = truncated_text[:last_space_index].strip() + '…'
|
|
|
|
| 184 |
else:
|
| 185 |
+
alt_text = truncated_text.strip() + '…' # Fallback for short texts or no spaces
|
| 186 |
+
|
| 187 |
+
# Remove any trailing periods before adding ellipsis if truncation happened
|
| 188 |
+
if alt_text.endswith('…') and alt_text.endswith('.…'):
|
| 189 |
+
alt_text = alt_text[:-2] + '…'
|
| 190 |
|
| 191 |
print(f"Finished processing {filename}. Alt text length: {len(alt_text)}")
|
| 192 |
+
return filename, alt_text # Keep filename in this return for internal processing
|
| 193 |
|
| 194 |
def generate_alt_text_for_files(file_objs, max_alt_text_len):
|
| 195 |
"""
|
| 196 |
Generates alt text for multiple image files in parallel.
|
| 197 |
+
Removes the filename from the final displayed output.
|
| 198 |
"""
|
| 199 |
if not file_objs:
|
| 200 |
return "No files uploaded."
|
| 201 |
|
|
|
|
| 202 |
image_paths = [getattr(f, 'name', f) for f in file_objs]
|
| 203 |
print(f"Generating alt text for {len(image_paths)} files.")
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
max_workers = min(len(image_paths), Config.CPU_CORES)
|
| 206 |
|
| 207 |
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
|
|
|
|
|
| 208 |
results = list(executor.map(lambda p: process_single_image(p, max_alt_text_len), image_paths))
|
| 209 |
|
| 210 |
+
# FORMATTING THE OUTPUT: Exclude filename from the final display string
|
| 211 |
+
lines = [f"{txt}" for fn, txt in results] # Only the generated text, not filename
|
| 212 |
return "\n".join(lines)
|
| 213 |
|
| 214 |
# 4. Gradio Interface (UI/UX Improvements)
|
| 215 |
+
with gr.Blocks(title="AI-Powered Alt Text Generator", theme=gr.themes.Soft()) as app:
|
| 216 |
gr.Markdown("# ✨ AI-Powered Alt Text Generator ✨")
|
| 217 |
gr.Markdown(
|
| 218 |
"Upload images to generate rich alt text using **BLIP** for captions, "
|
| 219 |
+
"**EasyOCR** for visible text (with basic spell correction), and optional **YOLOv5** for object detection. "
|
| 220 |
"Models are loaded once for faster subsequent processing."
|
| 221 |
)
|
| 222 |
|
|
|
|
| 226 |
label="Upload Images",
|
| 227 |
file_count="multiple",
|
| 228 |
file_types=["image"],
|
| 229 |
+
interactive=True,
|
| 230 |
height=200
|
| 231 |
)
|
|
|
|
| 232 |
max_len_slider = gr.Slider(
|
| 233 |
+
50, 500, step=10, value=250,
|
| 234 |
label="Maximum Alt Text Length (characters)",
|
| 235 |
info="Truncates the generated alt text to this length, preserving word boundaries.",
|
| 236 |
interactive=True
|
| 237 |
)
|
| 238 |
|
| 239 |
with gr.Row():
|
| 240 |
+
gen_btn = gr.Button("🚀 Generate Alt Text", variant="primary")
|
| 241 |
+
copy_btn = gr.Button("📋 Copy to Clipboard", variant="secondary")
|
| 242 |
|
| 243 |
with gr.Column(scale=3):
|
|
|
|
| 244 |
gallery = gr.Gallery(
|
| 245 |
label="Uploaded Image Previews",
|
| 246 |
columns=4,
|
| 247 |
rows=1,
|
| 248 |
object_fit="contain",
|
| 249 |
+
height="auto"
|
| 250 |
)
|
|
|
|
| 251 |
output_text = gr.Textbox(
|
| 252 |
label="Generated Alt Text",
|
| 253 |
+
lines=15,
|
| 254 |
interactive=False,
|
| 255 |
+
elem_id="output_text",
|
| 256 |
+
show_copy_button=True
|
| 257 |
)
|
| 258 |
|
|
|
|
|
|
|
| 259 |
file_input.change(fn=lambda files: files, inputs=file_input, outputs=gallery)
|
| 260 |
|
|
|
|
| 261 |
gen_btn.click(
|
| 262 |
fn=generate_alt_text_for_files,
|
| 263 |
inputs=[file_input, max_len_slider],
|
| 264 |
outputs=[output_text],
|
| 265 |
+
queue=True,
|
|
|
|
| 266 |
)
|
| 267 |
|
|
|
|
|
|
|
|
|
|
| 268 |
copy_btn.click(
|
| 269 |
+
None,
|
| 270 |
+
inputs=None,
|
| 271 |
+
outputs=None,
|
| 272 |
js="""
|
| 273 |
() => {
|
| 274 |
const outputElement = document.getElementById('output_text');
|
| 275 |
if (outputElement) {
|
|
|
|
| 276 |
if (navigator.clipboard && navigator.clipboard.writeText) {
|
| 277 |
navigator.clipboard.writeText(outputElement.value)
|
| 278 |
.then(() => alert('Alt text copied to clipboard!'))
|
| 279 |
.catch(err => console.error('Failed to copy text: ', err));
|
| 280 |
} else {
|
| 281 |
+
outputElement.select();
|
| 282 |
+
document.execCommand('copy');
|
| 283 |
+
alert('Alt text copied to clipboard!');
|
| 284 |
}
|
| 285 |
} else {
|
| 286 |
alert('Output text element not found.');
|
|
|
|
| 294 |
---
|
| 295 |
**How it works:**
|
| 296 |
- **BLIP:** Generates a descriptive caption of the image's content.
|
| 297 |
+
- **EasyOCR:** Detects and extracts visible text within the image, then applies basic spell correction and formatting.
|
| 298 |
- **YOLOv5 (Optional):** Identifies and lists prominent objects. (Requires `ultralytics` library)
|
| 299 |
|
| 300 |
This tool is a demonstration and may not be perfect for all images.
|
|
|
|
| 302 |
"""
|
| 303 |
)
|
| 304 |
|
|
|
|
| 305 |
def main():
|
| 306 |
print(f"\nStarting Gradio app on device: {Config.DEVICE}")
|
| 307 |
print(f"YOLO enabled: {use_yolo}\n")
|
| 308 |
app.launch(
|
| 309 |
+
server_name="0.0.0.0",
|
| 310 |
+
server_port=7860,
|
| 311 |
+
share=True,
|
| 312 |
+
debug=True
|
| 313 |
)
|
| 314 |
|
| 315 |
if __name__ == "__main__":
|