Update app.py
Browse files
app.py
CHANGED
|
@@ -5,52 +5,66 @@ import easyocr
|
|
| 5 |
import torch
|
| 6 |
from PIL import Image
|
| 7 |
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
| 8 |
|
| 9 |
-
# 1. Ensure the API token is set or crash early
|
| 10 |
if "REPLICATE_API_TOKEN" not in os.environ:
|
| 11 |
raise RuntimeError("Missing REPLICATE_API_TOKEN in environment!")
|
| 12 |
|
| 13 |
-
# 2. Inject
|
| 14 |
replicate.api_token = os.environ["REPLICATE_API_TOKEN"]
|
| 15 |
|
| 16 |
-
# 3. Initialize the Replicate client and preload
|
| 17 |
client = replicate.Client()
|
| 18 |
-
|
| 19 |
|
| 20 |
# 4. Initialize EasyOCR with GPU support if available
|
| 21 |
gpu_flag = torch.cuda.is_available()
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
# Determine available CPU cores for parallel processing
|
| 25 |
-
cpu_cores = os.cpu_count() or 4
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
def process_file(file_obj):
|
| 29 |
"""
|
| 30 |
-
Process a single
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
"""
|
| 33 |
-
# Resolve file path
|
| 34 |
path = getattr(file_obj, 'name', file_obj)
|
|
|
|
| 35 |
|
| 36 |
-
# Open
|
| 37 |
try:
|
| 38 |
with Image.open(path).convert('RGB') as img:
|
| 39 |
-
img.verify()
|
| 40 |
except Exception:
|
| 41 |
-
return
|
| 42 |
|
| 43 |
# OCR extraction
|
| 44 |
try:
|
| 45 |
-
ocr_texts =
|
| 46 |
-
visible_text = ' '.join(ocr_texts).strip()
|
| 47 |
except Exception:
|
| 48 |
-
visible_text = '
|
| 49 |
|
| 50 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
with open(path, 'rb') as img_file:
|
| 53 |
-
result =
|
| 54 |
image=img_file,
|
| 55 |
num_beams=5,
|
| 56 |
max_length=75,
|
|
@@ -59,62 +73,90 @@ def process_file(file_obj):
|
|
| 59 |
)
|
| 60 |
base_caption = result[0] if isinstance(result, list) else str(result)
|
| 61 |
except Exception as e:
|
| 62 |
-
return f"Error generating caption: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
|
|
|
| 66 |
|
|
|
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
"""
|
| 70 |
-
|
| 71 |
"""
|
| 72 |
if not files:
|
| 73 |
-
return "
|
| 74 |
|
| 75 |
-
# Limit workers to number of files or CPU cores
|
| 76 |
max_workers = min(len(files), cpu_cores)
|
| 77 |
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 78 |
-
results = list(executor.map(process_file, files))
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
# Format as numbered list
|
| 81 |
-
return "\n".join(f"{i+1}. {caption}" for i, caption in enumerate(results))
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
# Build Gradio interface
|
| 85 |
-
demo = gr.Blocks(title="
|
| 86 |
with demo:
|
| 87 |
-
gr.Markdown("# Alt Text Generator
|
| 88 |
gr.Markdown(
|
| 89 |
-
"
|
| 90 |
-
"
|
| 91 |
)
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
# Controls
|
| 104 |
with gr.Row():
|
| 105 |
gen_btn = gr.Button("Generate Alt Text")
|
| 106 |
-
|
| 107 |
-
copy_btn = gr.Button("Copy to Clipboard")
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
|
| 112 |
-
#
|
| 113 |
file_input.upload(lambda files: files, inputs=file_input, outputs=gallery)
|
| 114 |
-
gen_btn.click(
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
# Launch app
|
| 119 |
if __name__ == "__main__":
|
| 120 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|
|
| 5 |
import torch
|
| 6 |
from PIL import Image
|
| 7 |
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
import pandas as pd
|
| 9 |
|
| 10 |
+
# 1. Ensure the Replicate API token is set or crash early
|
| 11 |
if "REPLICATE_API_TOKEN" not in os.environ:
|
| 12 |
raise RuntimeError("Missing REPLICATE_API_TOKEN in environment!")
|
| 13 |
|
| 14 |
+
# 2. Inject the token for all replicate calls
|
| 15 |
replicate.api_token = os.environ["REPLICATE_API_TOKEN"]
|
| 16 |
|
| 17 |
+
# 3. Initialize the Replicate client and preload BLIP model
|
| 18 |
client = replicate.Client()
|
| 19 |
+
blip_model = client.models.get("salesforce/blip-image-captioning-base")
|
| 20 |
|
| 21 |
# 4. Initialize EasyOCR with GPU support if available
|
| 22 |
gpu_flag = torch.cuda.is_available()
|
| 23 |
+
ocr_reader = easyocr.Reader(["en"], gpu=gpu_flag)
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# 5. Load YOLOv5 model for object detection
|
| 26 |
+
yolo_model = torch.hub.load("ultralytics/yolov5", "yolov5s", pretrained=True)
|
| 27 |
+
if gpu_flag:
|
| 28 |
+
yolo_model.to("cuda")
|
| 29 |
|
| 30 |
+
def process_file(file_obj, max_len):
|
| 31 |
"""
|
| 32 |
+
Process a single image file:
|
| 33 |
+
- Open & verify image
|
| 34 |
+
- Extract visible text via EasyOCR
|
| 35 |
+
- Detect objects via YOLOv5
|
| 36 |
+
- Generate base caption via BLIP
|
| 37 |
+
- Combine & truncate to max_len
|
| 38 |
"""
|
|
|
|
| 39 |
path = getattr(file_obj, 'name', file_obj)
|
| 40 |
+
filename = os.path.basename(path)
|
| 41 |
|
| 42 |
+
# Open & verify image
|
| 43 |
try:
|
| 44 |
with Image.open(path).convert('RGB') as img:
|
| 45 |
+
img.verify()
|
| 46 |
except Exception:
|
| 47 |
+
return (filename, "<Error opening file>")
|
| 48 |
|
| 49 |
# OCR extraction
|
| 50 |
try:
|
| 51 |
+
ocr_texts = ocr_reader.readtext(path, detail=0)
|
| 52 |
+
visible_text = ' '.join(ocr_texts).strip()
|
| 53 |
except Exception:
|
| 54 |
+
visible_text = ''
|
| 55 |
|
| 56 |
+
# Object detection
|
| 57 |
+
try:
|
| 58 |
+
results = yolo_model(path)
|
| 59 |
+
labels = results.pandas().xyxy[0]['name'].unique().tolist()
|
| 60 |
+
labels = ', '.join(labels[:5])
|
| 61 |
+
except Exception:
|
| 62 |
+
labels = ''
|
| 63 |
+
|
| 64 |
+
# Generate base caption via BLIP
|
| 65 |
try:
|
| 66 |
with open(path, 'rb') as img_file:
|
| 67 |
+
result = blip_model.predict(
|
| 68 |
image=img_file,
|
| 69 |
num_beams=5,
|
| 70 |
max_length=75,
|
|
|
|
| 73 |
)
|
| 74 |
base_caption = result[0] if isinstance(result, list) else str(result)
|
| 75 |
except Exception as e:
|
| 76 |
+
return (filename, f"Error generating caption: {e}")
|
| 77 |
+
|
| 78 |
+
# Compose final caption
|
| 79 |
+
parts = [base_caption.strip()]
|
| 80 |
+
if labels:
|
| 81 |
+
parts.append(f"Objects: {labels}")
|
| 82 |
+
if visible_text:
|
| 83 |
+
parts.append(f"Text: {visible_text}")
|
| 84 |
+
caption = '; '.join(parts)
|
| 85 |
|
| 86 |
+
# Truncate without cutting words
|
| 87 |
+
if len(caption) > max_len:
|
| 88 |
+
caption = caption[:max_len].rsplit(' ', 1)[0] + '…'
|
| 89 |
|
| 90 |
+
return (filename, caption)
|
| 91 |
|
| 92 |
+
# Determine available CPU cores for parallel processing
|
| 93 |
+
cpu_cores = os.cpu_count() or 4
|
| 94 |
+
|
| 95 |
+
def generate_alt_text(files, max_len):
|
| 96 |
"""
|
| 97 |
+
Generate alt text in parallel and return a DataFrame & CSV.
|
| 98 |
"""
|
| 99 |
if not files:
|
| 100 |
+
return pd.DataFrame(columns=["filename", "alt_text"]), ""
|
| 101 |
|
|
|
|
| 102 |
max_workers = min(len(files), cpu_cores)
|
| 103 |
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 104 |
+
results = list(executor.map(lambda f: process_file(f, max_len), files))
|
| 105 |
+
|
| 106 |
+
df = pd.DataFrame(results, columns=["filename", "alt_text"])
|
| 107 |
+
return df, df.to_csv(index=False)
|
| 108 |
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
def download_csv(csv_str):
|
| 111 |
+
"""
|
| 112 |
+
Save CSV string to a file and return its path for download.
|
| 113 |
+
"""
|
| 114 |
+
path = "alt_texts.csv"
|
| 115 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 116 |
+
f.write(csv_str)
|
| 117 |
+
return path
|
| 118 |
|
| 119 |
+
# Build the Gradio interface
|
| 120 |
+
demo = gr.Blocks(title="AI-Powered Alt Text Generator")
|
| 121 |
with demo:
|
| 122 |
+
gr.Markdown("# AI-Powered Alt Text Generator")
|
| 123 |
gr.Markdown(
|
| 124 |
+
"Generate concise, context-rich alt text using OCR, object detection, "
|
| 125 |
+
"and BLIP, all under a customizable character limit."
|
| 126 |
)
|
| 127 |
|
| 128 |
+
with gr.Row():
|
| 129 |
+
file_input = gr.File(
|
| 130 |
+
label="Upload Images",
|
| 131 |
+
file_count="multiple",
|
| 132 |
+
file_types=["image"]
|
| 133 |
+
)
|
| 134 |
+
max_len = gr.Slider(
|
| 135 |
+
minimum=50,
|
| 136 |
+
maximum=200,
|
| 137 |
+
step=5,
|
| 138 |
+
value=125,
|
| 139 |
+
label="Max Alt Text Length (chars)"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
gallery = gr.Gallery(label="Image Preview", columns=4).style(grid=[4], height="auto")
|
| 143 |
|
|
|
|
| 144 |
with gr.Row():
|
| 145 |
gen_btn = gr.Button("Generate Alt Text")
|
| 146 |
+
download_btn = gr.Button("Download CSV")
|
|
|
|
| 147 |
|
| 148 |
+
output_df = gr.Dataframe(headers=["filename", "alt_text"], label="Results Table")
|
| 149 |
+
download_file = gr.File(label="Download CSV File")
|
| 150 |
|
| 151 |
+
# Event bindings
|
| 152 |
file_input.upload(lambda files: files, inputs=file_input, outputs=gallery)
|
| 153 |
+
gen_btn.click(
|
| 154 |
+
fn=generate_alt_text,
|
| 155 |
+
inputs=[file_input, max_len],
|
| 156 |
+
outputs=[output_df, download_file]
|
| 157 |
+
)
|
| 158 |
+
download_btn.click(fn=download_csv, inputs=download_file, outputs=download_file)
|
| 159 |
|
| 160 |
+
# Launch the app
|
| 161 |
if __name__ == "__main__":
|
| 162 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|