File size: 11,897 Bytes
2e205f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import os
import re
import sys
import shutil
import time
import socket
import urllib.request
import json
import torch
import torch.nn.functional as F
import numpy as np
from PIL import Image, ImageDraw

REPORT_PATH = r"C:\ComfyUI\Articles\watermark_scan_report.md"
LAMA_MODEL_PATH = os.path.join(os.path.expanduser("~"), ".cache", "torch", "hub", "checkpoints", "big-lama.pt")

COMFYUI_URL = "http://127.0.0.1:7777"
COMFYUI_INPUT_DIR = r"C:\ComfyUI\input"
COMFYUI_OUTPUT_DIR = r"C:\ComfyUI\output"
WORKFLOW_PATH = r"C:\ComfyUI\Articles\watermark_inpaint_workflow.json"

def is_port_open(host, port):
    try:
        with socket.create_connection((host, port), timeout=1):
            return True
    except OSError:
        return False

def check_comfy_online():
    return is_port_open("127.0.0.1", 7777)

def create_mask(image_path, flagged_corners, mask_path):
    img = Image.open(image_path)
    w, h = img.size
    
    # Create black image
    mask = Image.new("L", (w, h), 0)
    
    # Detect if Guardian to use larger mask
    is_guardian = "guardian" in image_path.lower()
    
    if is_guardian:
        # Guardian banner is massive in bottom right
        rect_w = int(w * 0.38)
        rect_h = int(h * 0.35)
    else:
        # 25% width, 15% height is usually enough for standard watermarks
        rect_w = int(w * 0.25)
        rect_h = int(h * 0.15)
    
    draw = ImageDraw.Draw(mask)
    
    for corner in flagged_corners:
        if corner == 'top_left':
            draw.rectangle([0, 0, rect_w, rect_h], fill=255)
        elif corner == 'top_right':
            draw.rectangle([w - rect_w, 0, w, rect_h], fill=255)
        elif corner == 'bottom_left':
            draw.rectangle([0, h - rect_h, rect_w, h], fill=255)
        elif corner == 'bottom_right':
            draw.rectangle([w - rect_w, h - rect_h, w, h], fill=255)
            
    mask.save(mask_path)
    return mask

def get_all_jpgs(root_dir):
    jpgs = []
    for root, dirs, files in os.walk(root_dir):
        for f in files:
            if f.endswith('.jpg'):
                jpgs.append(os.path.join(root, f))
    return jpgs

def simplify_string(s):
    s = s.replace('.jpg', '')
    s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
    return s

def process_report():
    if not os.path.exists(REPORT_PATH):
        print(f"Report not found at {REPORT_PATH}")
        return []
        
    with open(REPORT_PATH, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        
    tasks = []
    current_filename = None
    current_corners = []
    
    for line in lines:
        line = line.strip()
        m_file = re.match(r"^### \d+\. (.+)$", line)
        if m_file:
            if current_filename and current_corners:
                tasks.append({
                    'image': current_filename,
                    'corners': current_corners
                })
            current_filename = m_file.group(1)
            current_corners = []
            continue
            
        m_flag = re.search(r"\*\*(top_left|top_right|bottom_left|bottom_right)\*\*:.*\(Flagged\)", line)
        if m_flag:
            current_corners.append(m_flag.group(1))
            
    if current_filename and current_corners:
        tasks.append({
            'image': current_filename,
            'corners': current_corners
        })
        
    all_jpgs = get_all_jpgs(r"C:\ComfyUI\Articles")
    jpg_map = []
    for path in all_jpgs:
        filename = os.path.basename(path)
        simple = simplify_string(filename)
        m = re.search(r'img(\d+)$', simple)
        img_num = m.group(1) if m else None
        jpg_map.append({'path': path, 'simple': simple, 'img_num': img_num})
        
    matched_tasks = []
    for task in tasks:
        rep_filename = os.path.basename(task['image'])
        rep_simple = simplify_string(rep_filename)
        m = re.search(r'img(\d+)$', rep_simple)
        rep_img_num = m.group(1) if m else None
        
        best_match = None
        for j in jpg_map:
            if rep_img_num and j['img_num']:
                if rep_img_num != j['img_num']: continue
            elif rep_img_num or j['img_num']: continue
                
            j_clean = j['simple'].replace('original', '')
            rep_clean = rep_simple.replace('original', '')
            if j_clean == rep_clean:
                best_match = j['path']
                break
                
        if best_match:
            matched_tasks.append({
                'image': best_match,
                'corners': task['corners']
            })
            
    return matched_tasks

def process_via_comfyui(img_path, corners):
    # Create mask locally first
    mask_path = img_path + "_mask.png"
    mask_pil = create_mask(img_path, corners, mask_path)
    
    # Save original backup
    backup_path = img_path.replace(".jpg", "_original.jpg").replace(".png", "_original.png")
    if not os.path.exists(backup_path):
        shutil.copy2(img_path, backup_path)
    
    # Copy input and mask to ComfyUI input directory
    unique_id = str(int(time.time())) + "_" + str(np.random.randint(1000, 9999))
    comfy_in_name = f"watermark_in_{unique_id}.jpg"
    comfy_mask_name = f"watermark_mask_{unique_id}.png"
    
    shutil.copy2(backup_path, os.path.join(COMFYUI_INPUT_DIR, comfy_in_name))
    shutil.copy2(mask_path, os.path.join(COMFYUI_INPUT_DIR, comfy_mask_name))
    
    # Load workflow template
    with open(WORKFLOW_PATH, 'r', encoding='utf-8') as f:
        workflow = json.load(f)
        
    # Update inputs
    workflow["39"]["inputs"]["image"] = comfy_in_name
    workflow["40"]["inputs"]["image"] = comfy_mask_name
    
    # Generate seed
    seed = int(np.random.randint(1, 10000000))
    workflow["43"]["inputs"]["seed"] = seed
    
    # Queue prompt
    print(f"  Sending to ComfyUI API...")
    payload = {"prompt": workflow, "client_id": "watermark_remover_agent"}
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(f"{COMFYUI_URL}/prompt", data=data, headers={'Content-Type': 'application/json'})
    
    try:
        with urllib.request.urlopen(req) as res:
            res_data = json.loads(res.read().decode('utf-8'))
            prompt_id = res_data["prompt_id"]
    except Exception as e:
        print(f"  Failed to queue prompt: {e}")
        return False
        
    print(f"  Prompt queued. ID: {prompt_id}. Waiting for completion...")
    
    # Poll for completion
    completed = False
    output_filename = None
    
    # Wait up to 120 seconds
    for _ in range(60):
        time.sleep(2)
        # Check history
        req_hist = urllib.request.Request(f"{COMFYUI_URL}/history/{prompt_id}")
        try:
            with urllib.request.urlopen(req_hist) as res_hist:
                hist_data = json.loads(res_hist.read().decode('utf-8'))
                if prompt_id in hist_data:
                    # Completed!
                    outputs = hist_data[prompt_id].get("outputs", {})
                    # Find output from node 99 (SaveImage)
                    save_node_out = outputs.get("99", {})
                    if "images" in save_node_out and len(save_node_out["images"]) > 0:
                        output_filename = save_node_out["images"][0]["filename"]
                        completed = True
                        break
        except Exception as e:
            # ComfyUI might still be processing
            pass
            
    if not completed:
        print("  Timeout waiting for ComfyUI to process.")
        return False
        
    # Copy completed image back
    comfy_out_path = os.path.join(COMFYUI_OUTPUT_DIR, output_filename)
    if os.path.exists(comfy_out_path):
        shutil.copy2(comfy_out_path, img_path)
        print(f"  Successfully removed watermark using ComfyUI! Saved to {img_path}")
        # Clean up input folder files
        try:
            os.remove(os.path.join(COMFYUI_INPUT_DIR, comfy_in_name))
            os.remove(os.path.join(COMFYUI_INPUT_DIR, comfy_mask_name))
            os.remove(mask_path)
        except:
            pass
        return True
    else:
        print(f"  ComfyUI output file not found at {comfy_out_path}")
        return False

def process_via_local_fallback(img_path, corners, model, device):
    mask_path = img_path + "_mask.png"
    mask_pil = create_mask(img_path, corners, mask_path)
    
    backup_path = img_path.replace(".jpg", "_original.jpg").replace(".png", "_original.png")
    if not os.path.exists(backup_path):
        shutil.copy2(img_path, backup_path)
        
    try:
        img_pil = Image.open(backup_path).convert("RGB")
    except Exception as e:
        print(f"  -> Error opening image: {e}")
        return False
        
    w, h = img_pil.size
    
    img_np = np.array(img_pil, dtype=np.float32) / 255.0
    mask_np = np.array(mask_pil, dtype=np.float32) / 255.0
    mask_np = (mask_np > 0.1).astype(np.float32)
    
    image_tensor = torch.from_numpy(img_np).permute(2, 0, 1).unsqueeze(0).to(device)
    mask_tensor = torch.from_numpy(mask_np).unsqueeze(0).unsqueeze(0).to(device)
    
    pad_mod = 8
    pad_h = (pad_mod - h % pad_mod) % pad_mod
    pad_w = (pad_mod - w % pad_mod) % pad_mod
    
    if pad_h > 0 or pad_w > 0:
        image_tensor = F.pad(image_tensor, (0, pad_w, 0, pad_h), mode='reflect')
        mask_tensor = F.pad(mask_tensor, (0, pad_w, 0, pad_h), mode='constant', value=0.0)
        
    with torch.no_grad():
        output = model(image_tensor, mask_tensor)
        
    if pad_h > 0 or pad_w > 0:
        output = output[:, :, :h, :w]
        
    output = output.squeeze(0).permute(1, 2, 0).cpu().numpy()
    output = np.clip(output * 255.0, 0, 255).astype(np.uint8)
    
    output_pil = Image.fromarray(output)
    output_pil.save(img_path)
    print("  -> Success (Local Fallback)")
    
    if os.path.exists(mask_path):
        os.remove(mask_path)
    return True

def main():
    import sys
    sys.stdout.reconfigure(encoding='utf-8')
    test_mode = "--test" in sys.argv
    tasks = process_report()
    print(f"Found {len(tasks)} images to process.")
    
    if test_mode:
        tasks = tasks[:2]
        print(f"Running in TEST mode. Only processing {len(tasks)} images.")
    
    if not tasks:
        sys.exit(0)

    comfy_online = check_comfy_online()
    local_model = None
    device = None
    
    if comfy_online:
        print("ComfyUI is ONLINE. Using ComfyUI API for high-quality removal.")
    else:
        print("ComfyUI is OFFLINE. Initializing local PyTorch LaMa fallback...")
        if not os.path.exists(LAMA_MODEL_PATH):
            print("LaMa model not found. Please run lama_inpaint.py once to download it.")
            sys.exit(1)
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print(f"Using device: {device}")
        local_model = torch.jit.load(LAMA_MODEL_PATH, map_location=device)
        local_model.eval()

    for i, task in enumerate(tasks):
        img_path = task['image']
        corners = task['corners']
        print(f"[{i+1}/{len(tasks)}] Processing {img_path}")
        
        if not os.path.exists(img_path):
            print("  -> File not found!")
            continue
            
        if comfy_online:
            success = process_via_comfyui(img_path, corners)
            if not success:
                print("  Failed via ComfyUI. Attempting local fallback...")
                if local_model is None:
                    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
                    local_model = torch.jit.load(LAMA_MODEL_PATH, map_location=device)
                    local_model.eval()
                process_via_local_fallback(img_path, corners, local_model, device)
        else:
            process_via_local_fallback(img_path, corners, local_model, device)

if __name__ == "__main__":
    main()