Spaces:
Sleeping
Sleeping
Update app with dual model loading and patched transformers (LFS)
Browse files- .gitattributes +2 -0
- app.py +306 -0
- examples/crack_1.jpg +3 -0
- examples/crack_2.jpg +3 -0
- examples/drywall_1.jpg +3 -0
- examples/drywall_2.jpg +3 -0
- requirements.txt +9 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
# Initialize device
|
| 9 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 10 |
+
|
| 11 |
+
# Patch to avoid additional_chat_templates 404 error
|
| 12 |
+
# We need to patch the function in the module where it is USED, not just where it's defined
|
| 13 |
+
print("Patching transformers to avoid additional_chat_templates 404 error...")
|
| 14 |
+
|
| 15 |
+
import transformers.tokenization_utils_base
|
| 16 |
+
import transformers.utils.hub
|
| 17 |
+
from huggingface_hub.errors import RemoteEntryNotFoundError
|
| 18 |
+
|
| 19 |
+
# Capture the original function carefully to avoid recursion
|
| 20 |
+
# We use a unique attribute to track if we've already patched it
|
| 21 |
+
if not hasattr(transformers.utils.hub.list_repo_templates, "_patched"):
|
| 22 |
+
_original_list_repo_templates = transformers.utils.hub.list_repo_templates
|
| 23 |
+
else:
|
| 24 |
+
# If already patched, use the stored original
|
| 25 |
+
_original_list_repo_templates = transformers.utils.hub.list_repo_templates._original
|
| 26 |
+
|
| 27 |
+
def patched_list_repo_templates(repo_id, *args, **kwargs):
|
| 28 |
+
"""Patch to catch and ignore additional_chat_templates 404 errors"""
|
| 29 |
+
try:
|
| 30 |
+
results = []
|
| 31 |
+
# Use the captured original function
|
| 32 |
+
for template in _original_list_repo_templates(repo_id, *args, **kwargs):
|
| 33 |
+
results.append(template)
|
| 34 |
+
return results
|
| 35 |
+
except (RemoteEntryNotFoundError, Exception) as e:
|
| 36 |
+
# Check if this is the additional_chat_templates error
|
| 37 |
+
error_str = str(e).lower()
|
| 38 |
+
if "additional_chat_templates" in error_str or "404" in error_str:
|
| 39 |
+
print(f"Suppressing additional_chat_templates 404 error for {repo_id}")
|
| 40 |
+
return []
|
| 41 |
+
raise
|
| 42 |
+
|
| 43 |
+
# Mark as patched and store original
|
| 44 |
+
patched_list_repo_templates._patched = True
|
| 45 |
+
patched_list_repo_templates._original = _original_list_repo_templates
|
| 46 |
+
|
| 47 |
+
# Apply the patch to BOTH locations
|
| 48 |
+
transformers.utils.hub.list_repo_templates = patched_list_repo_templates
|
| 49 |
+
transformers.tokenization_utils_base.list_repo_templates = patched_list_repo_templates
|
| 50 |
+
print("Patch applied to transformers.tokenization_utils_base.list_repo_templates")
|
| 51 |
+
|
| 52 |
+
# Load processor from original model
|
| 53 |
+
print("Loading processor from original model...")
|
| 54 |
+
try:
|
| 55 |
+
from transformers import CLIPTokenizer, CLIPImageProcessor
|
| 56 |
+
# Load components separately
|
| 57 |
+
tokenizer = CLIPTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
|
| 58 |
+
image_processor = CLIPImageProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
|
| 59 |
+
processor = CLIPSegProcessor(image_processor=image_processor, tokenizer=tokenizer)
|
| 60 |
+
print("Processor loaded successfully from original model components")
|
| 61 |
+
except Exception as e:
|
| 62 |
+
print(f"Error loading processor components: {e}")
|
| 63 |
+
# Fallback: try loading processor directly (should work with patch)
|
| 64 |
+
processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
|
| 65 |
+
print("Processor loaded directly with patched template check")
|
| 66 |
+
|
| 67 |
+
# Load models
|
| 68 |
+
print("Loading pretrained model...")
|
| 69 |
+
model_pretrained = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device)
|
| 70 |
+
model_pretrained.eval()
|
| 71 |
+
|
| 72 |
+
print("Loading fine-tuned model...")
|
| 73 |
+
try:
|
| 74 |
+
model_trained = CLIPSegForImageSegmentation.from_pretrained("smcs/clipseg_drywall").to(device)
|
| 75 |
+
model_trained.eval()
|
| 76 |
+
model_trained_available = True
|
| 77 |
+
print("Fine-tuned model loaded successfully from smcs/clipseg_drywall")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"Warning: Could not load fine-tuned model from smcs/clipseg_drywall: {e}")
|
| 80 |
+
model_trained = None
|
| 81 |
+
model_trained_available = False
|
| 82 |
+
|
| 83 |
+
# Define prompts
|
| 84 |
+
PROMPTS = {
|
| 85 |
+
"segment crack": "segment crack",
|
| 86 |
+
"segment taping area": "segment taping area"
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
# Example images
|
| 90 |
+
example_images = [
|
| 91 |
+
["examples/crack_1.jpg"],
|
| 92 |
+
["examples/crack_2.jpg"],
|
| 93 |
+
["examples/drywall_1.jpg"],
|
| 94 |
+
["examples/drywall_2.jpg"]
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def overlay_mask(image, mask, alpha=0.5, color=(255, 0, 0)):
|
| 99 |
+
"""Overlay mask on image with transparency and colored mask"""
|
| 100 |
+
if mask is None:
|
| 101 |
+
return image
|
| 102 |
+
|
| 103 |
+
# Ensure same size
|
| 104 |
+
if mask.size != image.size:
|
| 105 |
+
mask = mask.resize(image.size, Image.NEAREST)
|
| 106 |
+
|
| 107 |
+
# Convert mask to numpy array
|
| 108 |
+
mask_array = np.array(mask.convert('L'))
|
| 109 |
+
mask_binary = (mask_array > 127).astype(np.float32)
|
| 110 |
+
|
| 111 |
+
# Create colored mask
|
| 112 |
+
colored_mask = np.zeros((*mask_array.shape, 3), dtype=np.uint8)
|
| 113 |
+
colored_mask[:, :, 0] = color[0] # Red channel
|
| 114 |
+
colored_mask[:, :, 1] = color[1] # Green channel
|
| 115 |
+
colored_mask[:, :, 2] = color[2] # Blue channel
|
| 116 |
+
|
| 117 |
+
# Convert image to numpy array
|
| 118 |
+
img_array = np.array(image.convert('RGB'))
|
| 119 |
+
|
| 120 |
+
# Create overlay
|
| 121 |
+
overlay = img_array.copy().astype(np.float32)
|
| 122 |
+
for c in range(3):
|
| 123 |
+
overlay[:, :, c] = overlay[:, :, c] * (1 - alpha * mask_binary) + colored_mask[:, :, c] * (alpha * mask_binary)
|
| 124 |
+
|
| 125 |
+
overlay = overlay.astype(np.uint8)
|
| 126 |
+
return Image.fromarray(overlay)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def process_image(image, prompt_option):
|
| 130 |
+
"""
|
| 131 |
+
Process an image with both pretrained and fine-tuned models.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
image: PIL Image or numpy array
|
| 135 |
+
prompt_option: Selected prompt option ("segment crack" or "segment taping area")
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
Tuple of (pretrained_mask, trained_mask) or error message
|
| 139 |
+
"""
|
| 140 |
+
if image is None:
|
| 141 |
+
return None, None
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
# Convert to PIL Image if needed
|
| 145 |
+
if isinstance(image, np.ndarray):
|
| 146 |
+
image = Image.fromarray(image)
|
| 147 |
+
elif not isinstance(image, Image.Image):
|
| 148 |
+
image = Image.open(image).convert('RGB')
|
| 149 |
+
else:
|
| 150 |
+
image = image.convert('RGB')
|
| 151 |
+
|
| 152 |
+
# Get the prompt
|
| 153 |
+
prompt = PROMPTS.get(prompt_option, prompt_option)
|
| 154 |
+
|
| 155 |
+
# Resize image for processing
|
| 156 |
+
img_orig = image.copy()
|
| 157 |
+
img = img_orig.resize((352, 352), Image.BILINEAR)
|
| 158 |
+
|
| 159 |
+
# Prepare inputs
|
| 160 |
+
pixel_values = processor(images=[img], return_tensors="pt")['pixel_values'].to(device)
|
| 161 |
+
text_inputs = processor.tokenizer(
|
| 162 |
+
prompt, padding="max_length", max_length=77, truncation=True, return_tensors="pt"
|
| 163 |
+
).to(device)
|
| 164 |
+
|
| 165 |
+
# Process with pretrained model
|
| 166 |
+
with torch.no_grad():
|
| 167 |
+
outputs_pretrained = model_pretrained(
|
| 168 |
+
pixel_values=pixel_values,
|
| 169 |
+
input_ids=text_inputs['input_ids'],
|
| 170 |
+
attention_mask=text_inputs['attention_mask']
|
| 171 |
+
)
|
| 172 |
+
logits_pretrained = outputs_pretrained.logits[0].cpu().numpy()
|
| 173 |
+
|
| 174 |
+
pred_mask_pretrained = torch.sigmoid(torch.from_numpy(logits_pretrained)).numpy()
|
| 175 |
+
pred_mask_pretrained = (pred_mask_pretrained > 0.5).astype(np.uint8)
|
| 176 |
+
|
| 177 |
+
# Resize mask back to original image size
|
| 178 |
+
pred_mask_pretrained_img = Image.fromarray(pred_mask_pretrained * 255, mode='L')
|
| 179 |
+
if img_orig.size != (352, 352):
|
| 180 |
+
pred_mask_pretrained_img = pred_mask_pretrained_img.resize(
|
| 181 |
+
(img_orig.size[0], img_orig.size[1]), Image.NEAREST
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Create overlay for pretrained result (blue color)
|
| 185 |
+
pred_mask_pretrained_overlay = overlay_mask(img_orig.copy(), pred_mask_pretrained_img, alpha=0.5, color=(0, 100, 255))
|
| 186 |
+
|
| 187 |
+
# Process with fine-tuned model if available
|
| 188 |
+
if model_trained_available and model_trained is not None:
|
| 189 |
+
with torch.no_grad():
|
| 190 |
+
outputs_trained = model_trained(
|
| 191 |
+
pixel_values=pixel_values,
|
| 192 |
+
input_ids=text_inputs['input_ids'],
|
| 193 |
+
attention_mask=text_inputs['attention_mask']
|
| 194 |
+
)
|
| 195 |
+
logits_trained = outputs_trained.logits[0].cpu().numpy()
|
| 196 |
+
|
| 197 |
+
pred_mask_trained = torch.sigmoid(torch.from_numpy(logits_trained)).numpy()
|
| 198 |
+
pred_mask_trained = (pred_mask_trained > 0.5).astype(np.uint8)
|
| 199 |
+
|
| 200 |
+
# Resize mask back to original image size
|
| 201 |
+
pred_mask_trained_img = Image.fromarray(pred_mask_trained * 255, mode='L')
|
| 202 |
+
if img_orig.size != (352, 352):
|
| 203 |
+
pred_mask_trained_img = pred_mask_trained_img.resize(
|
| 204 |
+
(img_orig.size[0], img_orig.size[1]), Image.NEAREST
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Create overlay for fine-tuned result (green color)
|
| 208 |
+
pred_mask_trained_overlay = overlay_mask(img_orig.copy(), pred_mask_trained_img, alpha=0.5, color=(0, 255, 0))
|
| 209 |
+
else:
|
| 210 |
+
# Create a placeholder image with message
|
| 211 |
+
placeholder = Image.new('RGB', img_orig.size, color=(240, 240, 240))
|
| 212 |
+
pred_mask_trained_overlay = placeholder
|
| 213 |
+
|
| 214 |
+
return pred_mask_pretrained_overlay, pred_mask_trained_overlay
|
| 215 |
+
|
| 216 |
+
except Exception as e:
|
| 217 |
+
error_msg = f"Error processing image: {str(e)}"
|
| 218 |
+
print(error_msg)
|
| 219 |
+
return None, None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def create_interface():
|
| 223 |
+
"""Create the Gradio interface"""
|
| 224 |
+
|
| 225 |
+
with gr.Blocks(title="CLIPSeg Image Segmentation") as demo:
|
| 226 |
+
gr.Markdown(
|
| 227 |
+
"""
|
| 228 |
+
# CLIPSeg Image Segmentation Demo
|
| 229 |
+
|
| 230 |
+
This demo compares zero-shot pretrained CLIPSeg results with fine-tuned model results.
|
| 231 |
+
Select an example image or upload your own, then choose a prompt to see the segmentation results.
|
| 232 |
+
"""
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
with gr.Row():
|
| 236 |
+
with gr.Column():
|
| 237 |
+
image_input = gr.Image(
|
| 238 |
+
label="Input Image",
|
| 239 |
+
type="pil",
|
| 240 |
+
height=400
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
prompt_dropdown = gr.Dropdown(
|
| 244 |
+
choices=list(PROMPTS.keys()),
|
| 245 |
+
value=list(PROMPTS.keys())[0],
|
| 246 |
+
label="Select Prompt",
|
| 247 |
+
info="Choose the segmentation prompt"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
submit_btn = gr.Button("Segment", variant="primary")
|
| 251 |
+
|
| 252 |
+
with gr.Row():
|
| 253 |
+
with gr.Column():
|
| 254 |
+
pretrained_output = gr.Image(
|
| 255 |
+
label="Pretrained (Zero-shot) Result",
|
| 256 |
+
type="pil",
|
| 257 |
+
height=400
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
with gr.Column():
|
| 261 |
+
trained_output = gr.Image(
|
| 262 |
+
label="Fine-tuned Result" + (" (Not Available)" if not model_trained_available else ""),
|
| 263 |
+
type="pil",
|
| 264 |
+
height=400
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
if not model_trained_available:
|
| 268 |
+
gr.Markdown(
|
| 269 |
+
"⚠️ **Note:** Fine-tuned model could not be loaded from `smcs/clipseg_drywall`. "
|
| 270 |
+
"Only pretrained results will be shown."
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
gr.Examples(
|
| 274 |
+
examples=example_images,
|
| 275 |
+
inputs=image_input,
|
| 276 |
+
label="Example Images"
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
# Connect the function
|
| 280 |
+
submit_btn.click(
|
| 281 |
+
fn=process_image,
|
| 282 |
+
inputs=[image_input, prompt_dropdown],
|
| 283 |
+
outputs=[pretrained_output, trained_output]
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# Also process when example is selected
|
| 287 |
+
image_input.change(
|
| 288 |
+
fn=process_image,
|
| 289 |
+
inputs=[image_input, prompt_dropdown],
|
| 290 |
+
outputs=[pretrained_output, trained_output]
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
# Process when prompt changes
|
| 294 |
+
prompt_dropdown.change(
|
| 295 |
+
fn=process_image,
|
| 296 |
+
inputs=[image_input, prompt_dropdown],
|
| 297 |
+
outputs=[pretrained_output, trained_output]
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
return demo
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
if __name__ == "__main__":
|
| 304 |
+
demo = create_interface()
|
| 305 |
+
demo.launch(share=False)
|
| 306 |
+
|
examples/crack_1.jpg
ADDED
|
Git LFS Details
|
examples/crack_2.jpg
ADDED
|
Git LFS Details
|
examples/drywall_1.jpg
ADDED
|
Git LFS Details
|
examples/drywall_2.jpg
ADDED
|
Git LFS Details
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
transformers>=4.40.0
|
| 3 |
+
gradio>=4.0.0
|
| 4 |
+
pillow>=9.0.0
|
| 5 |
+
numpy>=1.24.0
|
| 6 |
+
tqdm>=4.65.0
|
| 7 |
+
python-multipart>=0.0.9
|
| 8 |
+
huggingface-hub>=0.20.0
|
| 9 |
+
|