Update app.py
Browse files
app.py
CHANGED
|
@@ -7,78 +7,75 @@ from PIL import Image
|
|
| 7 |
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
import pandas as pd
|
| 9 |
|
| 10 |
-
# Local development: load
|
| 11 |
try:
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
load_dotenv()
|
| 14 |
except ImportError:
|
| 15 |
-
pass
|
| 16 |
|
| 17 |
-
#
|
| 18 |
REPLICATE_TOKEN = os.getenv("REPLICATE_API_TOKEN", "")
|
| 19 |
replicate.api_token = REPLICATE_TOKEN
|
| 20 |
|
| 21 |
-
|
|
|
|
| 22 |
token_available = bool(REPLICATE_TOKEN)
|
| 23 |
client = replicate.Client() if token_available else None
|
| 24 |
blip_model = client.models.get("salesforce/blip-image-captioning-base") if token_available else None
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
gpu_flag = torch.cuda.is_available()
|
| 28 |
ocr_reader = easyocr.Reader(["en"], gpu=gpu_flag)
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
use_yolo =
|
| 32 |
try:
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
except Exception as e:
|
| 37 |
print(f"Warning: YOLOv5 load failed ({e}); object detection disabled.")
|
| 38 |
use_yolo = False
|
| 39 |
yolo_model = None
|
| 40 |
|
| 41 |
-
# CPU cores for
|
| 42 |
cpu_cores = os.cpu_count() or 4
|
| 43 |
|
| 44 |
|
| 45 |
def process_file(file_obj, max_len):
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
"""
|
| 49 |
-
filename = os.path.basename(getattr(file_obj, 'name', file_obj))
|
| 50 |
|
| 51 |
-
# If no token, skip processing
|
| 52 |
if not token_available:
|
| 53 |
-
return (filename, "Error: REPLICATE_API_TOKEN not set.
|
| 54 |
|
| 55 |
-
# Verify image
|
| 56 |
try:
|
| 57 |
-
with Image.open(
|
| 58 |
img.verify()
|
| 59 |
except Exception:
|
| 60 |
return (filename, "<Error opening file>")
|
| 61 |
|
| 62 |
-
#
|
| 63 |
try:
|
| 64 |
-
texts = ocr_reader.readtext(
|
| 65 |
visible = ' '.join(texts).strip()
|
| 66 |
except Exception:
|
| 67 |
visible = ''
|
| 68 |
|
| 69 |
-
#
|
| 70 |
labels = ''
|
| 71 |
-
if use_yolo:
|
| 72 |
try:
|
| 73 |
-
res = yolo_model(
|
| 74 |
labels_list = res.pandas().xyxy[0]['name'].unique().tolist()[:5]
|
| 75 |
labels = ', '.join(labels_list)
|
| 76 |
except Exception:
|
| 77 |
labels = ''
|
| 78 |
|
| 79 |
-
# Generate
|
| 80 |
try:
|
| 81 |
-
with open(
|
| 82 |
output = blip_model.predict(
|
| 83 |
image=img_f,
|
| 84 |
num_beams=5,
|
|
@@ -90,7 +87,7 @@ def process_file(file_obj, max_len):
|
|
| 90 |
except Exception as e:
|
| 91 |
return (filename, f"Error generating caption: {e}")
|
| 92 |
|
| 93 |
-
# Assemble
|
| 94 |
parts = [base.strip()]
|
| 95 |
if labels:
|
| 96 |
parts.append(f"Objects: {labels}")
|
|
@@ -98,7 +95,6 @@ def process_file(file_obj, max_len):
|
|
| 98 |
parts.append(f"Text: {visible}")
|
| 99 |
caption = '; '.join(parts)
|
| 100 |
|
| 101 |
-
# Truncate cleanly
|
| 102 |
if len(caption) > max_len:
|
| 103 |
caption = caption[:max_len].rsplit(' ', 1)[0] + '…'
|
| 104 |
|
|
@@ -106,10 +102,7 @@ def process_file(file_obj, max_len):
|
|
| 106 |
|
| 107 |
|
| 108 |
def generate_alt_text(files, max_len):
|
| 109 |
-
|
| 110 |
-
Run processing in parallel and return a DataFrame + CSV for download.
|
| 111 |
-
"""
|
| 112 |
-
# Handle no-huggingface-token case
|
| 113 |
if not token_available:
|
| 114 |
df = pd.DataFrame(
|
| 115 |
[("", "Error: REPLICATE_API_TOKEN not set. Add it in Settings → Secrets and Variables.")],
|
|
@@ -129,33 +122,30 @@ def generate_alt_text(files, max_len):
|
|
| 129 |
|
| 130 |
|
| 131 |
def download_csv(csv_str):
|
| 132 |
-
"""
|
| 133 |
-
Save and return path for CSV download.
|
| 134 |
-
"""
|
| 135 |
path = "alt_texts.csv"
|
| 136 |
with open(path, 'w', encoding='utf-8') as f:
|
| 137 |
f.write(csv_str)
|
| 138 |
return path
|
| 139 |
|
| 140 |
-
# Build Gradio
|
| 141 |
-
demo = gr.Blocks(title="AI-Powered Alt Text Generator")
|
| 142 |
with demo:
|
| 143 |
-
gr.Markdown("# AI-Powered Alt Text Generator
|
| 144 |
gr.Markdown(
|
| 145 |
-
"Generate rich alt text with OCR, object detection, and BLIP
|
| 146 |
)
|
| 147 |
|
| 148 |
with gr.Row():
|
| 149 |
file_input = gr.File(label="Upload Images", file_count="multiple", file_types=["image"])
|
| 150 |
-
max_len = gr.Slider(50, 200, step=5, value=125, label="Max Alt Text Length
|
| 151 |
|
| 152 |
-
gallery = gr.Gallery(label="Preview", columns=4)
|
| 153 |
|
| 154 |
with gr.Row():
|
| 155 |
gen_btn = gr.Button("Generate Alt Text")
|
| 156 |
download_btn = gr.Button("Download CSV")
|
| 157 |
|
| 158 |
-
output_df = gr.Dataframe(headers=["filename", "alt_text"], label="Results")
|
| 159 |
download_file = gr.File(label="CSV File")
|
| 160 |
|
| 161 |
file_input.upload(lambda files: files, inputs=file_input, outputs=gallery)
|
|
|
|
| 7 |
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
import pandas as pd
|
| 9 |
|
| 10 |
+
# Local development: load .env variables
|
| 11 |
try:
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
load_dotenv()
|
| 14 |
except ImportError:
|
| 15 |
+
pass
|
| 16 |
|
| 17 |
+
# Hugging Face Spaces: set REPLICATE_API_TOKEN in Settings → Secrets and Variables
|
| 18 |
REPLICATE_TOKEN = os.getenv("REPLICATE_API_TOKEN", "")
|
| 19 |
replicate.api_token = REPLICATE_TOKEN
|
| 20 |
|
| 21 |
+
gpu_flag = torch.cuda.is_available()
|
| 22 |
+
|
| 23 |
token_available = bool(REPLICATE_TOKEN)
|
| 24 |
client = replicate.Client() if token_available else None
|
| 25 |
blip_model = client.models.get("salesforce/blip-image-captioning-base") if token_available else None
|
| 26 |
|
| 27 |
+
# Initialize EasyOCR reader
|
|
|
|
| 28 |
ocr_reader = easyocr.Reader(["en"], gpu=gpu_flag)
|
| 29 |
|
| 30 |
+
# Attempt to load YOLOv5 for object detection; disable if unavailable
|
| 31 |
+
use_yolo = True
|
| 32 |
try:
|
| 33 |
+
yolo_model = torch.hub.load("ultralytics/yolov5", "yolov5s", pretrained=True)
|
| 34 |
+
if gpu_flag:
|
| 35 |
+
yolo_model.to("cuda")
|
| 36 |
except Exception as e:
|
| 37 |
print(f"Warning: YOLOv5 load failed ({e}); object detection disabled.")
|
| 38 |
use_yolo = False
|
| 39 |
yolo_model = None
|
| 40 |
|
| 41 |
+
# Determine CPU cores for parallel processing
|
| 42 |
cpu_cores = os.cpu_count() or 4
|
| 43 |
|
| 44 |
|
| 45 |
def process_file(file_obj, max_len):
|
| 46 |
+
path = getattr(file_obj, 'name', file_obj)
|
| 47 |
+
filename = os.path.basename(path)
|
|
|
|
|
|
|
| 48 |
|
|
|
|
| 49 |
if not token_available:
|
| 50 |
+
return (filename, "Error: REPLICATE_API_TOKEN not set.")
|
| 51 |
|
| 52 |
+
# Verify and open image
|
| 53 |
try:
|
| 54 |
+
with Image.open(path).convert('RGB') as img:
|
| 55 |
img.verify()
|
| 56 |
except Exception:
|
| 57 |
return (filename, "<Error opening file>")
|
| 58 |
|
| 59 |
+
# OCR extraction
|
| 60 |
try:
|
| 61 |
+
texts = ocr_reader.readtext(path, detail=0)
|
| 62 |
visible = ' '.join(texts).strip()
|
| 63 |
except Exception:
|
| 64 |
visible = ''
|
| 65 |
|
| 66 |
+
# Object detection
|
| 67 |
labels = ''
|
| 68 |
+
if use_yolo and yolo_model:
|
| 69 |
try:
|
| 70 |
+
res = yolo_model(path)
|
| 71 |
labels_list = res.pandas().xyxy[0]['name'].unique().tolist()[:5]
|
| 72 |
labels = ', '.join(labels_list)
|
| 73 |
except Exception:
|
| 74 |
labels = ''
|
| 75 |
|
| 76 |
+
# Generate BLIP caption
|
| 77 |
try:
|
| 78 |
+
with open(path, 'rb') as img_f:
|
| 79 |
output = blip_model.predict(
|
| 80 |
image=img_f,
|
| 81 |
num_beams=5,
|
|
|
|
| 87 |
except Exception as e:
|
| 88 |
return (filename, f"Error generating caption: {e}")
|
| 89 |
|
| 90 |
+
# Assemble and truncate
|
| 91 |
parts = [base.strip()]
|
| 92 |
if labels:
|
| 93 |
parts.append(f"Objects: {labels}")
|
|
|
|
| 95 |
parts.append(f"Text: {visible}")
|
| 96 |
caption = '; '.join(parts)
|
| 97 |
|
|
|
|
| 98 |
if len(caption) > max_len:
|
| 99 |
caption = caption[:max_len].rsplit(' ', 1)[0] + '…'
|
| 100 |
|
|
|
|
| 102 |
|
| 103 |
|
| 104 |
def generate_alt_text(files, max_len):
|
| 105 |
+
# Handle missing token
|
|
|
|
|
|
|
|
|
|
| 106 |
if not token_available:
|
| 107 |
df = pd.DataFrame(
|
| 108 |
[("", "Error: REPLICATE_API_TOKEN not set. Add it in Settings → Secrets and Variables.")],
|
|
|
|
| 122 |
|
| 123 |
|
| 124 |
def download_csv(csv_str):
|
|
|
|
|
|
|
|
|
|
| 125 |
path = "alt_texts.csv"
|
| 126 |
with open(path, 'w', encoding='utf-8') as f:
|
| 127 |
f.write(csv_str)
|
| 128 |
return path
|
| 129 |
|
| 130 |
+
# Build Gradio interface
|
| 131 |
+
demo = gr.Blocks(title="AI-Powered Alt Text Generator (HF Spaces)")
|
| 132 |
with demo:
|
| 133 |
+
gr.Markdown("# AI-Powered Alt Text Generator")
|
| 134 |
gr.Markdown(
|
| 135 |
+
"Generate context-rich alt text with OCR, optional object detection, and BLIP captions."
|
| 136 |
)
|
| 137 |
|
| 138 |
with gr.Row():
|
| 139 |
file_input = gr.File(label="Upload Images", file_count="multiple", file_types=["image"])
|
| 140 |
+
max_len = gr.Slider(50, 200, step=5, value=125, label="Max Alt Text Length")
|
| 141 |
|
| 142 |
+
gallery = gr.Gallery(label="Preview", columns=4)
|
| 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="CSV File")
|
| 150 |
|
| 151 |
file_input.upload(lambda files: files, inputs=file_input, outputs=gallery)
|