Spaces:
Sleeping
Sleeping
Commit ·
69c1cd3
1
Parent(s): 257509a
fix some problems in app.py
Browse files
app.py
CHANGED
|
@@ -11,7 +11,6 @@ from PIL import Image
|
|
| 11 |
|
| 12 |
from custom_caption_model import LoadedCustomModel, load_custom_model
|
| 13 |
|
| 14 |
-
# Keep CPU use stable on Spaces.
|
| 15 |
torch.set_num_threads(max(1, min(4, os.cpu_count() or 1)))
|
| 16 |
|
| 17 |
ROOT = Path(__file__).resolve().parent
|
|
@@ -69,49 +68,44 @@ def _load_blip_lora():
|
|
| 69 |
return _blip_processor, _blip_model
|
| 70 |
|
| 71 |
|
| 72 |
-
def _caption_blip_lora(image: Image.Image
|
| 73 |
processor, model = _load_blip_lora()
|
| 74 |
image = image.convert("RGB")
|
| 75 |
inputs = processor(images=image, return_tensors="pt").to(DEVICE)
|
| 76 |
with torch.inference_mode():
|
| 77 |
-
output = model.generate(
|
| 78 |
-
pixel_values=inputs["pixel_values"],
|
| 79 |
-
max_length=int(max_len),
|
| 80 |
-
num_beams=int(beam_size),
|
| 81 |
-
)
|
| 82 |
return processor.decode(output[0], skip_special_tokens=True).strip()
|
| 83 |
|
| 84 |
|
| 85 |
-
def caption_one(image: Image.Image, model_choice: str, decoding: str
|
| 86 |
if image is None:
|
| 87 |
return "Please upload an image first."
|
| 88 |
|
| 89 |
try:
|
| 90 |
if model_choice == "Custom EfficientNet + Transformer — 5k":
|
| 91 |
model = _load_custom_5k()
|
| 92 |
-
return model.caption(image, decoding=decoding
|
| 93 |
|
| 94 |
if model_choice == "Custom EfficientNet + Transformer — 100k":
|
| 95 |
model = _load_custom_100k()
|
| 96 |
-
return model.caption(image, decoding=decoding
|
| 97 |
|
| 98 |
if model_choice == "BLIP + LoRA — COCO 2014":
|
| 99 |
-
|
| 100 |
-
return _caption_blip_lora(image, beam_size=beam_size, max_len=max_len)
|
| 101 |
|
| 102 |
return "Unknown model selected."
|
| 103 |
except Exception as exc:
|
| 104 |
-
return f"Error
|
| 105 |
|
| 106 |
|
| 107 |
-
def compare_all(image: Image.Image
|
| 108 |
if image is None:
|
| 109 |
return "Please upload an image first."
|
| 110 |
|
| 111 |
rows: List[str] = []
|
| 112 |
for choice in MODEL_CHOICES:
|
| 113 |
-
caption = caption_one(image, choice, "Beam search"
|
| 114 |
-
rows.append(f"
|
| 115 |
return "\n\n---\n\n".join(rows)
|
| 116 |
|
| 117 |
|
|
@@ -123,78 +117,107 @@ def unload_models() -> str:
|
|
| 123 |
gc.collect()
|
| 124 |
if torch.cuda.is_available():
|
| 125 |
torch.cuda.empty_cache()
|
| 126 |
-
return "All cached models
|
| 127 |
-
|
| 128 |
|
| 129 |
-
with gr.Blocks(title="Image Captioning Model Comparison") as demo:
|
| 130 |
-
gr.Markdown(
|
| 131 |
-
"""
|
| 132 |
-
# Image Captioning Model Comparison
|
| 133 |
|
| 134 |
-
|
|
|
|
| 135 |
|
| 136 |
-
1. Custom EfficientNet-V2-S + Transformer trained on 5k samples
|
| 137 |
-
2. Custom EfficientNet-V2-S + Transformer trained on 100k samples
|
| 138 |
-
3. BLIP image-captioning base fine-tuned with LoRA on COCO 2014
|
| 139 |
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
)
|
| 143 |
|
| 144 |
-
with gr.Row():
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
model_dropdown = gr.Dropdown(
|
| 148 |
choices=MODEL_CHOICES,
|
| 149 |
value=MODEL_CHOICES[2],
|
| 150 |
label="Model",
|
|
|
|
| 151 |
)
|
| 152 |
decoding_dropdown = gr.Dropdown(
|
| 153 |
choices=["Beam search", "Greedy"],
|
| 154 |
value="Beam search",
|
| 155 |
-
label="Decoding
|
|
|
|
|
|
|
| 156 |
)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
maximum=50,
|
| 167 |
-
value=30,
|
| 168 |
-
step=1,
|
| 169 |
-
label="Max caption length",
|
| 170 |
)
|
| 171 |
-
generate_btn = gr.Button("Generate Caption", variant="primary")
|
| 172 |
-
compare_btn = gr.Button("Compare All Models")
|
| 173 |
-
unload_btn = gr.Button("Unload Cached Models")
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
generate_btn.click(
|
| 178 |
fn=caption_one,
|
| 179 |
-
inputs=[image_input, model_dropdown, decoding_dropdown
|
| 180 |
outputs=output,
|
| 181 |
)
|
| 182 |
compare_btn.click(
|
| 183 |
fn=compare_all,
|
| 184 |
-
inputs=[image_input
|
| 185 |
outputs=output,
|
| 186 |
)
|
| 187 |
-
unload_btn.click(fn=unload_models, inputs=None, outputs=output)
|
| 188 |
-
|
| 189 |
-
gr.Markdown(
|
| 190 |
-
f"""
|
| 191 |
-
---
|
| 192 |
-
|
| 193 |
-
**Runtime device:** `{DEVICE}`
|
| 194 |
-
|
| 195 |
-
For faster inference, select GPU hardware in the Space settings. CPU inference works but can be slow, especially for the custom Transformer models.
|
| 196 |
-
"""
|
| 197 |
-
)
|
| 198 |
|
| 199 |
if __name__ == "__main__":
|
| 200 |
demo.launch()
|
|
|
|
| 11 |
|
| 12 |
from custom_caption_model import LoadedCustomModel, load_custom_model
|
| 13 |
|
|
|
|
| 14 |
torch.set_num_threads(max(1, min(4, os.cpu_count() or 1)))
|
| 15 |
|
| 16 |
ROOT = Path(__file__).resolve().parent
|
|
|
|
| 68 |
return _blip_processor, _blip_model
|
| 69 |
|
| 70 |
|
| 71 |
+
def _caption_blip_lora(image: Image.Image) -> str:
|
| 72 |
processor, model = _load_blip_lora()
|
| 73 |
image = image.convert("RGB")
|
| 74 |
inputs = processor(images=image, return_tensors="pt").to(DEVICE)
|
| 75 |
with torch.inference_mode():
|
| 76 |
+
output = model.generate(**inputs, max_new_tokens=50, num_beams=4)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
return processor.decode(output[0], skip_special_tokens=True).strip()
|
| 78 |
|
| 79 |
|
| 80 |
+
def caption_one(image: Image.Image, model_choice: str, decoding: str) -> str:
|
| 81 |
if image is None:
|
| 82 |
return "Please upload an image first."
|
| 83 |
|
| 84 |
try:
|
| 85 |
if model_choice == "Custom EfficientNet + Transformer — 5k":
|
| 86 |
model = _load_custom_5k()
|
| 87 |
+
return model.caption(image, decoding=decoding)
|
| 88 |
|
| 89 |
if model_choice == "Custom EfficientNet + Transformer — 100k":
|
| 90 |
model = _load_custom_100k()
|
| 91 |
+
return model.caption(image, decoding=decoding)
|
| 92 |
|
| 93 |
if model_choice == "BLIP + LoRA — COCO 2014":
|
| 94 |
+
return _caption_blip_lora(image)
|
|
|
|
| 95 |
|
| 96 |
return "Unknown model selected."
|
| 97 |
except Exception as exc:
|
| 98 |
+
return f"Error: {type(exc).__name__}: {exc}"
|
| 99 |
|
| 100 |
|
| 101 |
+
def compare_all(image: Image.Image) -> str:
|
| 102 |
if image is None:
|
| 103 |
return "Please upload an image first."
|
| 104 |
|
| 105 |
rows: List[str] = []
|
| 106 |
for choice in MODEL_CHOICES:
|
| 107 |
+
caption = caption_one(image, choice, "Beam search")
|
| 108 |
+
rows.append(f"**{choice}**\n\n> {caption}")
|
| 109 |
return "\n\n---\n\n".join(rows)
|
| 110 |
|
| 111 |
|
|
|
|
| 117 |
gc.collect()
|
| 118 |
if torch.cuda.is_available():
|
| 119 |
torch.cuda.empty_cache()
|
| 120 |
+
return "All cached models unloaded."
|
|
|
|
| 121 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
def update_decoding_visibility(model_choice: str):
|
| 124 |
+
return gr.update(visible="Custom" in model_choice)
|
| 125 |
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
CSS = """
|
| 128 |
+
.header-text { text-align: center; margin-bottom: 8px; }
|
| 129 |
+
.output-box textarea { font-size: 1.05em !important; line-height: 1.7 !important; }
|
| 130 |
+
.tag-row { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 4px; }
|
| 131 |
+
footer { display: none !important; }
|
| 132 |
"""
|
| 133 |
+
|
| 134 |
+
with gr.Blocks(
|
| 135 |
+
title="Image Captioning",
|
| 136 |
+
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="slate"),
|
| 137 |
+
css=CSS,
|
| 138 |
+
) as demo:
|
| 139 |
+
|
| 140 |
+
gr.Markdown(
|
| 141 |
+
"""
|
| 142 |
+
# 🖼️ Image Captioning
|
| 143 |
+
Upload a photo and generate a natural-language description using one of three trained models — or compare all at once.
|
| 144 |
+
""",
|
| 145 |
+
elem_classes=["header-text"],
|
| 146 |
)
|
| 147 |
|
| 148 |
+
with gr.Row(equal_height=False):
|
| 149 |
+
with gr.Column(scale=5):
|
| 150 |
+
image_input = gr.Image(
|
| 151 |
+
type="pil",
|
| 152 |
+
label="Upload Image",
|
| 153 |
+
height=360,
|
| 154 |
+
show_download_button=False,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
with gr.Column(scale=4):
|
| 158 |
model_dropdown = gr.Dropdown(
|
| 159 |
choices=MODEL_CHOICES,
|
| 160 |
value=MODEL_CHOICES[2],
|
| 161 |
label="Model",
|
| 162 |
+
info="BLIP + LoRA produces the best captions",
|
| 163 |
)
|
| 164 |
decoding_dropdown = gr.Dropdown(
|
| 165 |
choices=["Beam search", "Greedy"],
|
| 166 |
value="Beam search",
|
| 167 |
+
label="Decoding strategy",
|
| 168 |
+
info="Beam search is slower but produces better results",
|
| 169 |
+
visible=False,
|
| 170 |
)
|
| 171 |
+
|
| 172 |
+
gr.Markdown(
|
| 173 |
+
"""
|
| 174 |
+
<div style="font-size:0.82em; color:#6b7280; margin-top:4px;">
|
| 175 |
+
<b>Model details</b><br>
|
| 176 |
+
• <b>Custom 5k / 100k</b> — EfficientNet-V2-S + Transformer, trained from scratch on COCO subsets<br>
|
| 177 |
+
• <b>BLIP + LoRA</b> — Salesforce BLIP base fine-tuned with LoRA adapters on COCO 2014
|
| 178 |
+
</div>
|
| 179 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
)
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
+
with gr.Row():
|
| 183 |
+
generate_btn = gr.Button(
|
| 184 |
+
"Generate Caption", variant="primary", scale=3, size="lg"
|
| 185 |
+
)
|
| 186 |
+
compare_btn = gr.Button("Compare All", scale=2, size="lg")
|
| 187 |
+
|
| 188 |
+
with gr.Group():
|
| 189 |
+
output = gr.Markdown(
|
| 190 |
+
value="",
|
| 191 |
+
label="Caption",
|
| 192 |
+
elem_classes=["output-box"],
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
with gr.Accordion("Advanced", open=False):
|
| 196 |
+
unload_btn = gr.Button("Unload Cached Models", variant="stop", size="sm")
|
| 197 |
+
unload_status = gr.Textbox(label="Status", lines=1, interactive=False)
|
| 198 |
+
unload_btn.click(fn=unload_models, inputs=None, outputs=unload_status)
|
| 199 |
+
|
| 200 |
+
gr.Markdown(
|
| 201 |
+
f"<div style='text-align:center; font-size:0.8em; color:#9ca3af; margin-top:8px;'>"
|
| 202 |
+
f"Runtime device: <code>{DEVICE}</code> · First inference per model is slower (lazy loading)"
|
| 203 |
+
f"</div>"
|
| 204 |
+
)
|
| 205 |
|
| 206 |
+
model_dropdown.change(
|
| 207 |
+
fn=update_decoding_visibility,
|
| 208 |
+
inputs=model_dropdown,
|
| 209 |
+
outputs=decoding_dropdown,
|
| 210 |
+
)
|
| 211 |
generate_btn.click(
|
| 212 |
fn=caption_one,
|
| 213 |
+
inputs=[image_input, model_dropdown, decoding_dropdown],
|
| 214 |
outputs=output,
|
| 215 |
)
|
| 216 |
compare_btn.click(
|
| 217 |
fn=compare_all,
|
| 218 |
+
inputs=[image_input],
|
| 219 |
outputs=output,
|
| 220 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
if __name__ == "__main__":
|
| 223 |
demo.launch()
|