android-times-articles / batch_remove_watermarks.py
aoiandroid's picture
[UPLOAD] Sync Android Times articles archive
2e205f0 verified
Raw History Blame Contribute Delete
11.9 kB
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()