File size: 6,816 Bytes
c159ca8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
            if method == "self_supervised":
                # Create a mask for text regions (simulated)
                mask = np.zeros((h, w), dtype=np.uint8)
                
                # Generate random 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
                )
                
                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()