import gradio as gr import numpy as np import cv2 from PIL import Image import torch import torchvision.transforms as T import os import random class TextErasingDemo: def __init__(self): # Initialize model components (placeholder for actual model loading) self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def erase_text(self, image, method="self_supervised", strength=0.7): """ Main function to erase text from images. This is a simplified implementation that simulates text erasing. """ try: # Convert PIL to numpy for processing if isinstance(image, Image.Image): img_np = np.array(image) else: img_np = image.copy() # Get image dimensions h, w = img_np.shape[:2] # Simulate text detection and erasing # In a real implementation, this would use the actual model if method == "self_supervised": # Create a mask for text regions (simulated) mask = np.zeros((h, w), dtype=np.uint8) # Randomly generate some rectangular regions as "text" num_regions = random.randint(3, 8) for _ in range(num_regions): # Random text region x1 = random.randint(0, w-50) y1 = random.randint(0, h-20) x2 = x1 + random.randint(30, 100) y2 = y1 + random.randint(15, 30) # Apply Gaussian blur to simulate text removal region = img_np[y1:y2, x1:x2] if region.size > 0: # Apply inpainting or blurring kernel_size = int(5 * strength) + 1 kernel_size = kernel_size if kernel_size % 2 == 1 else kernel_size + 1 blurred_region = cv2.GaussianBlur(region, (kernel_size, kernel_size), 0) # Blend the blurred region back alpha = 0.8 * strength img_np[y1:y2, x1:x2] = cv2.addWeighted( region, 1-alpha, blurred_region, alpha, 0 ) # Create a more realistic mask with text-like shapes for i in range(h)): for j in range(w)): # Simple pattern to simulate text if (i // 20 + j // 20) % 2 == 0: mask[i,j] = 255 # Apply inpainting using the mask result = cv2.inpaint(img_np, mask, 3, cv2.INPAINT_TELEA) else: # For other methods, use a different approach # Apply median filtering for text removal result = cv2.medianBlur(img_np, int(5 * strength) + 1) # Ensure we have a valid image if result is None or result.size == 0: result = img_np return result except Exception as e: print(f"Error in text erasing: {e}") return image def main(): demo = TextErasingDemo() def process_image(input_image, method, strength): """ Process the image with text erasing """ try: result = demo.erase_text(input_image, method, strength) return result except Exception as e: raise gr.Error(f"Failed to process image: {str(e)}") with gr.Blocks( title="Self-supervised Text Erasing", footer_links=[{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"] ) as app: gr.Markdown("# 🎨 Self-supervised Text Erasing") gr.Markdown("Upload an image containing text and see it get erased!") with gr.Row(): with gr.Column(): input_image = gr.Image( label="Input Image", type="pil", sources=["upload", "webcam"], interactive=True ) with gr.Column(): method_selector = gr.Dropdown( choices=["self_supervised", "traditional", "neural_network"], label="Erasing Method", value="self_supervised" ) strength_slider = gr.Slider( label="Erasing Strength", minimum=0.1, maximum=1.0, value=0.7, step=0.1 ) with gr.Column(): output_image = gr.Image( label="Output Image (Text Erased)") ) process_btn = gr.Button("Erase Text �", variant="primary") # Example images example_images = [ ["https://raw.githubusercontent.com/alimama-creative/Self-supervised-Text-Erasing/main/assets/example1.jpg"], ["https://raw.githubusercontent.com/alimama-creative/Self-supervised-Text-Erasing/main/assets/example2.jpg"], ["https://raw.githubusercontent.com/alimama-creative/Self-supervised-Text-Erasing/main/assets/example3.jpg"] ] gr.Examples( examples=example_images, inputs=input_image, outputs=output_image, fn=process_image, cache_examples=True ) # Event listener with Gradio 6 syntax process_btn.click( fn=process_image, inputs=[input_image, method_selector, strength_slider], outputs=output_image, api_visibility="public" ) # Additional information with gr.Accordion("About this Demo"): gr.Markdown(""" ## Self-supervised Text Erasing This demo showcases text erasing capabilities using self-supervised learning approaches. **Features:** - Multiple text erasing methods - Adjustable erasing strength - Real-time processing **How to use:** 1. Upload an image with text or use your webcam 2. Select the erasing method 3. Adjust the erasing strength 4. Click 'Erase Text' to process the image **Note:** This is a simulation of the actual text erasing process. """) app.launch( share=False, server_name="0.0.0.0", server_port=7860 ) if __name__ == "__main__": main()