soundunity's picture
Add manual paint-to-select region protection tab
7e0a0f7 verified
Raw History Blame Contribute Delete
33.6 kB
"""Gradio interface for the complete remove-ai-watermarks operation catalog.
Direct image tabs cover provenance inspection, 10-provider generator attribution,
visible mark removal, and metadata stripping; catalog panels add video, text,
batch processing, and every installed command parameter.
"""
from __future__ import annotations
import shutil
import tempfile
import uuid
from pathlib import Path
from typing import Any
import gradio as gr
import numpy as np
from remove_ai_watermarks import image_io, metadata, remove_visible, watermark_registry
from remove_ai_watermarks.identify import ProvenanceReport, identify
from remove_ai_watermarks.source_classify import (
WEIGHTS_REPO,
SourceClassification,
classify_source,
)
from operation_ui import add_operation_tabs
from remove_ai_watermarks import remove_all as _remove_all, InvisibleOptions as _InvisibleOptions
REPO_URL = "https://github.com/wiltodelta/remove-ai-watermarks"
# UI label -> the library's Sensitivity literal (the API uses an underscore).
_SENSITIVITY = {
"auto (recommended)": "auto",
"strict": "strict",
}
def _bgr_to_rgb(bgr: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
"""3-channel BGR uint8 -> RGB uint8 for Gradio display."""
return bgr[..., :3][..., ::-1].copy()
def _temp_output(src: Path) -> Path:
"""Unique per-request output path so concurrent users never share files.
The Space is multi-user: a fixed ``clean_{name}`` in the shared temp dir let
one request overwrite or download another request's cleaned image.
"""
return Path(tempfile.gettempdir()) / f"clean_{src.stem}_{uuid.uuid4().hex[:8]}{src.suffix}"
# --- identify --------------------------------------------------------------
def _format_report(report: ProvenanceReport) -> str:
verdict = {True: "AI-generated", False: "not AI", None: "unknown"}[report.is_ai_generated]
lines = [
f"Verdict: {verdict} (confidence: {report.confidence})",
f"Platform: {report.platform or 'undetermined'}",
]
if report.ai_source_kind:
kind = {
"generated": "fully AI-generated",
"enhanced": "real photo with an AI-composited region",
}.get(report.ai_source_kind, report.ai_source_kind)
lines.append(f"Source: {kind}")
if report.is_ai_generated is None:
lines.append(
"\nNo locally-readable AI signal found. This is not the same as "
"'clean': metadata is often stripped by re-encoding, screenshots, "
"or upload, and SynthID-class pixel watermarks have no local detector."
)
if report.integrity_clashes:
lines.append("\nIntegrity clash (provenance signals contradict each other):")
lines.extend(f" - {c}" for c in report.integrity_clashes)
if report.signals:
lines.append("\nSignals:")
lines.extend(f" - {s.name}: {s.detail} ({s.confidence})" for s in report.signals)
if report.watermarks:
lines.append("\nWatermarks / provenance markers:")
lines.extend(f" - {w}" for w in report.watermarks)
else:
lines.append("\nNo watermarks or provenance markers found.")
if report.caveats:
lines.append("\nCaveats:")
lines.extend(f" - {c}" for c in report.caveats)
return "\n".join(lines)
def run_identify(path: str | None) -> str:
if not path:
return "Upload an image first."
report = identify(Path(path))
return _format_report(report)
# --- source-pipeline classifier --------------------------------------------
def _format_source_classification(result: SourceClassification) -> str:
lines = [
f"Label: {result.label} (reason: {result.reason})",
f"Version subfamily: {result.version_subfamily or 'none'}",
f"Confidence: {result.confidence:.4f}",
f"Model revision: {result.model_revision}",
f"Watermark truth: {result.watermark_truth}",
]
if result.margins:
ranked = sorted(
result.margins,
key=lambda p: result.margins[p] - result.thresholds[p],
reverse=True,
)[:3]
lines.append("\nTop providers (margin minus threshold):")
lines.extend(
f" - {p}: {result.margins[p] - result.thresholds[p]:+.4f} "
f"(margin: {result.margins[p]:.4f}, threshold: {result.thresholds[p]:.4f})"
for p in ranked
)
lines.append(
f"\nNote: pixel source-pipeline classification only ({WEIGHTS_REPO}). "
"It is separate from identify, is not cryptographic provenance, and does not detect "
"or verify SynthID or prove an image is human-made."
)
return "\n".join(lines)
def run_classify_source(path: str | None) -> str:
if not path:
return "Upload an image first."
try:
result = classify_source(Path(path))
except (OSError, RuntimeError, ValueError) as exc:
return f"Could not classify that image: {exc}"
return _format_source_classification(result)
# --- visible mark removal --------------------------------------------------
def run_detect(path: str | None) -> str:
if not path:
return "Upload an image first."
bgr = image_io.imread(Path(path))
if bgr is None:
return "Could not read that image."
detections = watermark_registry.detect_marks(bgr)
if not detections:
return "No known marks in the registry."
return "\n".join(
f"{d.label}: {'YES' if d.detected else 'no'} ({d.confidence:.2f})" for d in detections
)
def run_visible(
path: str | None, sensitivity_label: str
) -> tuple[np.ndarray[Any, Any] | None, str | None, str]:
if not path:
return None, None, "Upload an image first."
sensitivity = _SENSITIVITY.get(sensitivity_label, "auto")
src = Path(path)
out = _temp_output(src)
# remove_visible reads the file's metadata provenance (so sensitivity="auto"
# recovers a moved/faint mark whenever the file still carries its provenance),
# removes every detected mark by localize -> fill, and strips AI metadata from
# the written output. write_noop=False: if nothing is found, write no output.
result_bgr, removed = remove_visible(
src, output=out, sensitivity=sensitivity, strip_metadata=True, write_noop=False
)
after_rgb = _bgr_to_rgb(result_bgr)
if removed:
info = "Removed: " + ", ".join(removed) + ".\nOutput cleaned + AI metadata stripped."
return after_rgb, str(out), info
return after_rgb, None, "No known visible mark detected. The image was left unchanged."
# --- metadata --------------------------------------------------------------
def run_metadata_check(path: str | None) -> str:
if not path:
return "Upload an image first."
data = metadata.get_ai_metadata(Path(path))
if not data:
return "No AI / provenance metadata found."
return "\n".join(f"{k}: {v}" for k, v in data.items())
def run_metadata_strip(path: str | None) -> tuple[str | None, str]:
if not path:
return None, "Upload an image first."
src = Path(path)
out = _temp_output(src)
cleaned = metadata.remove_ai_metadata(src, out)
remaining = metadata.get_ai_metadata(cleaned)
note = (
"All AI metadata stripped (pixels untouched)."
if not remaining
else f"Stripped; {len(remaining)} marker(s) remain (container-embedded)."
)
return str(cleaned), note
# --- video & audio quick studios -------------------------------------------
def _video_mark_choices() -> list[str]:
try:
from remove_ai_watermarks.video_visible import VIDEO_VISIBLE_MARKS
return ["auto", *VIDEO_VISIBLE_MARKS]
except Exception: # noqa: BLE001
return [
"auto",
"sora",
"veo",
"dreamina",
"seedance",
"doubao",
"dola",
"hailuo",
"vidu",
"wan",
"kling",
"jimeng",
"jimeng_pill",
"qwen",
"yuanbao",
"baidu",
"runninghub",
"microsoft",
"generic_ai_label",
]
def _audio_method_choices() -> list[str]:
try:
from remove_ai_watermarks._internal.constants import AUDIO_METHODS
return list(AUDIO_METHODS)
except Exception: # noqa: BLE001
return ["auto", "spectral", "encodec", "combined", "dac", "snac"]
def _audio_vendor_choices() -> list[str]:
try:
from remove_ai_watermarks._internal.constants import AUDIO_VENDORS
return list(AUDIO_VENDORS)
except Exception: # noqa: BLE001
return [
"auto",
"google",
"elevenlabs",
"suno",
"udio",
"openai",
"cartesia",
"meta",
"resemble",
"microsoft",
]
def run_video_identify_quick(path: str | None) -> str:
if not path:
return "Upload a video first."
try:
from remove_ai_watermarks.video import identify_video
vid_rep = identify_video(Path(path), check_audio=True)
except (OSError, ImportError, RuntimeError, ValueError) as exc:
return f"Could not inspect that video: {exc}"
verdict = {True: "AI-generated", False: "not AI", None: "unknown"}[vid_rep.is_ai_generated]
lines = [
f"Verdict: {verdict} (confidence: {vid_rep.confidence})",
f"Platform: {vid_rep.platform or 'undetermined'}",
]
marks = vid_rep.visible_marks or ((vid_rep.visible_mark,) if vid_rep.visible_mark else ())
if marks:
lines.append(
f"Visible mark: {', '.join(marks)} "
f"({vid_rep.visible_detected_frames}/{vid_rep.total_frames or '?'} frames)"
)
if vid_rep.metadata_markers:
lines.append("\nMetadata markers:")
lines.extend(f" - {k}: {v}" for k, v in vid_rep.metadata_markers.items())
if vid_rep.invisible_watermark_hints:
lines.append("\nInvisible watermark hints:")
lines.extend(f" - {h}" for h in vid_rep.invisible_watermark_hints)
if vid_rep.caveats:
lines.append("\nCaveats:")
lines.extend(f" - {c}" for c in vid_rep.caveats)
return "\n".join(lines)
def run_video_clean_quick(
path: str | None, mark: str, trim_bumper: bool = False
) -> tuple[str | None, str | None, str]:
if not path:
return None, None, "Upload a video first."
import inspect
src = Path(path)
out = _temp_output(src)
try:
from remove_ai_watermarks.video import remove_video_all
kwargs: dict[str, Any] = {"mark": mark, "include_invisible": False}
if "trim_bumper" in inspect.signature(remove_video_all).parameters:
kwargs["trim_bumper"] = trim_bumper
res = remove_video_all(src, out, **kwargs)
except (OSError, ImportError, RuntimeError, ValueError) as exc:
return None, None, f"Could not clean that video: {exc}"
cleaned = Path(res.output)
if cleaned.suffix.lower() == ".mp4":
preview = _temp_output(cleaned)
shutil.copy2(cleaned, preview)
else:
preview = cleaned
summary = (
f"Visible mark: {res.visible_mark or 'none'} "
f"({res.visible_removed_frames}/{res.total_frames} frames cleaned).\n"
f"Metadata stripped: {len(res.detected_metadata)} marker(s) found, "
f"{len(res.remaining_metadata)} remaining."
)
return str(preview), str(cleaned), summary
def run_audio_identify_quick(path: str | None) -> str:
if not path:
return "Upload an audio file first."
try:
from remove_ai_watermarks.audio import identify_audio
rep = identify_audio(Path(path), scheme="auto")
except (OSError, ImportError, RuntimeError, ValueError) as exc:
return f"Could not inspect that audio file: {exc}"
lines = [
f"Format: {rep.stream.codec} ({rep.stream.sample_rate} Hz, {rep.stream.channels} ch)",
f"AI metadata: {'yes' if rep.metadata_markers else 'no'}",
f"Watermark status: {rep.watermark_status}",
]
if rep.metadata_markers:
lines.append("\nMetadata markers:")
lines.extend(f" - {k}: {v}" for k, v in rep.metadata_markers.items())
if rep.detections:
lines.append("\nDecoder checks:")
lines.extend(
f" - {d.scheme} ({d.decoder_sample_rate} Hz): {d.status}" for d in rep.detections
)
return "\n".join(lines)
def run_audio_clean_quick(
path: str | None, vendor: str, method: str = "auto"
) -> tuple[str | None, str | None, str]:
if not path:
return None, None, "Upload an audio file first."
import inspect
from operation_ui import _AUDIO_OUTPUT_SUFFIXES
src = Path(path)
suffix = src.suffix.lower()
out = _temp_output(src if suffix in _AUDIO_OUTPUT_SUFFIXES else src.with_suffix(".wav"))
try:
from remove_ai_watermarks.audio import remove_audio_all
sig = inspect.signature(remove_audio_all).parameters
kwargs: dict[str, Any] = {"include_invisible": True, "scheme": "auto"}
if method != "auto":
kwargs["method"] = method
if "vendor" in sig:
kwargs["vendor"] = vendor
elif vendor not in ("", "auto"):
kwargs.setdefault("method", "spectral" if vendor == "meta" else "dac")
kwargs["allow_unverified"] = True
res = remove_audio_all(src, out, **kwargs)
except (OSError, ImportError, RuntimeError, ValueError) as exc:
return None, None, f"Could not clean that audio file: {exc}"
out_str = str(res.output)
inv_res = res.invisible_result
inv_label = (
f"cleaned via {inv_res.method}"
if res.invisible_applied and inv_res is not None and not inv_res.skipped
else "skipped (metadata stripped only)"
)
note = (
f"Invisible stage: {inv_label}.\n"
f"Metadata markers removed: {len(res.detected_metadata)}."
)
return out_str, out_str, note
# --- UI --------------------------------------------------------------------
INTRO = f"""
# Remove AI Watermarks
Inspect AI provenance and clean content you generated or edited. Use the image,
video, audio, and text operations below. Images support PNG / JPEG / WebP / HEIC / AVIF.
Use the Video, Audio, Text, and Image tools tabs for the complete operation catalog.
Invisible image regeneration needs NVIDIA CUDA; video and audio profiles also support CPU and MPS.
Optional models download on first use.
Source, docs and issues: [{REPO_URL.split("//")[1]}]({REPO_URL}) (Apache-2.0).
"""
def run_invisible_qwen(path, strength=0.0, cnet=1.0, fid_anchor=False, max_res=0, polish=False):
"""Qwen-Image-2512 invisible-watermark regeneration (CUDA) with fidelity knobs."""
if not path:
return None, None, "Upload an image first."
import time
src = Path(path)
out = _temp_output(src)
try:
strength = float(strength)
except (TypeError, ValueError):
strength = 0.0
opts = _InvisibleOptions(
pipeline="qwen-zimage",
strength=(None if strength <= 0 else strength),
controlnet_conditioning_scale=float(cnet),
fidelity_anchor=bool(fid_anchor),
max_resolution=int(max_res or 0),
adaptive_polish=(True if polish else None),
)
t0 = time.time()
try:
res = _remove_all(src, out, invisible=opts, include_invisible=True, force=True)
except Exception as exc: # noqa: BLE001
return None, None, f"Error: {type(exc).__name__}: {exc}"
dt = time.time() - t0
inv = getattr(res, "invisible", "?")
report = (
f"invisible stage: {inv}\n"
f"strength: {'default' if strength <= 0 else strength} | cnet: {cnet} | "
f"fid_anchor: {bool(fid_anchor)} | max_res: {int(max_res or 0)} | polish: {bool(polish)}\n"
f"elapsed: {dt:.1f}s\noutput: {out.name}"
)
return str(out), str(out), report
def run_textsafe(path, strength=0.0):
"""Invisible removal with verified-text protection (OCR draft -> manifest -> restore)."""
if not path:
return None, None, "Upload an image first."
import json, time
from PIL import Image
from remove_ai_watermarks.text_draft import draft_text_lines
from remove_ai_watermarks._internal.text_restoration import source_pixel_sha256
src = Path(path)
out = _temp_output(src)
try:
strength = float(strength)
except (TypeError, ValueError):
strength = 0.0
img = Image.open(src).convert("RGB")
try:
draft = draft_text_lines(src)
except Exception as exc: # noqa: BLE001
return None, None, f"OCR draft failed: {type(exc).__name__}: {exc}"
lines = [
{"box": [int(v) for v in dl.box], "text": dl.text, "script": dl.script, "angle": 0.0}
for dl in draft.accepted
]
lines.sort(key=lambda l: (l["box"][1], l["box"][0]))
if not lines:
return None, None, f"No stable text lines detected (rejected {len(draft.rejected)})."
manifest = {
"schema_version": 1,
"verified": True,
"width": img.width,
"height": img.height,
"source_pixel_sha256": source_pixel_sha256(img),
"lines": lines,
}
mpath = out.with_suffix(".manifest.json")
mpath.write_text(json.dumps(manifest), encoding="utf-8")
opts = _InvisibleOptions(
pipeline="qwen-zimage",
strength=(None if strength <= 0 else strength),
text_manifest=mpath,
)
t0 = time.time()
try:
res = _remove_all(src, out, invisible=opts, include_invisible=True, force=True)
except Exception as exc: # noqa: BLE001
return None, None, f"Error: {type(exc).__name__}: {exc}\n(detected {len(lines)} text lines)"
dt = time.time() - t0
report = (
f"text lines protected: {len(lines)} (rejected {len(draft.rejected)})\n"
f"invisible stage: {getattr(res, 'invisible', '?')}\n"
f"strength: {'default' if strength <= 0 else strength}\n"
f"elapsed: {dt:.1f}s\noutput: {out.name}"
)
return str(out), str(out), report
def _boxes_from_paint(bg, layers):
"""Union painted layer alphas -> connected-component boxes in source pixels."""
import numpy as np, cv2
h, w = bg.shape[:2]
mask = np.zeros((h, w), np.uint8)
for lyr in (layers or []):
if lyr is None:
continue
lyr = np.asarray(lyr)
if lyr.ndim == 3 and lyr.shape[2] == 4:
a = lyr[..., 3]
elif lyr.ndim == 3:
a = (lyr.sum(axis=2) > 0).astype(np.uint8) * 255
else:
a = (lyr > 0).astype(np.uint8) * 255
mask = np.maximum(mask, (a > 10).astype(np.uint8) * 255)
if int(mask.sum()) == 0:
return []
n, _lab, stats, _c = cv2.connectedComponentsWithStats(mask, connectivity=8)
boxes = []
for i in range(1, n):
x, y, bw, bh, area = stats[i]
if area < 50:
continue
boxes.append([int(x), int(y), int(min(w, x + bw)), int(min(h, y + bh))])
boxes.sort(key=lambda b: (b[1], b[0]))
return boxes
def run_textsafe_manual(editor, strength=0.0):
"""Invisible removal that protects USER-PAINTED regions (manual selection)."""
import json, time
import numpy as np
from PIL import Image
from remove_ai_watermarks._internal.text_restoration import source_pixel_sha256
if not editor or editor.get("background") is None:
return None, None, "Load an image and paint over the regions to protect."
bg = np.asarray(editor["background"])[..., :3].astype("uint8")
boxes = _boxes_from_paint(bg, editor.get("layers"))
if not boxes:
return None, None, "No painted regions found — brush over the text/marks to protect."
try:
strength = float(strength)
except (TypeError, ValueError):
strength = 0.0
src_img = Image.fromarray(bg).convert("RGB")
src = _temp_output(Path("manual_src.png"))
src_img.save(src)
out = _temp_output(src)
lines = [{"box": b, "text": "manual", "script": "alphabetic", "angle": 0.0} for b in boxes]
manifest = {
"schema_version": 1,
"verified": True,
"width": src_img.width,
"height": src_img.height,
"source_pixel_sha256": source_pixel_sha256(src_img),
"lines": lines,
}
mpath = out.with_suffix(".manifest.json")
mpath.write_text(json.dumps(manifest), encoding="utf-8")
opts = _InvisibleOptions(
pipeline="qwen-zimage",
strength=(None if strength <= 0 else strength),
text_manifest=mpath,
)
t0 = time.time()
try:
res = _remove_all(src, out, invisible=opts, include_invisible=True, force=True)
except Exception as exc: # noqa: BLE001
return None, None, f"Error: {type(exc).__name__}: {exc}\n({len(boxes)} painted regions)"
dt = time.time() - t0
report = (
f"regions protected: {len(boxes)}\n"
f"invisible stage: {getattr(res, 'invisible', '?')}\n"
f"strength: {'default' if strength <= 0 else strength}\n"
f"elapsed: {dt:.1f}s"
)
return str(out), str(out), report
with gr.Blocks(title="Remove AI Watermarks") as demo:
gr.Markdown(INTRO)
with gr.Tab("Identify"):
gr.Markdown(
"Read every locally-readable provenance signal (C2PA issuer, EXIF/XMP "
"generator, IPTC 'Made with AI', China TC260 AIGC label, xAI signature, "
"SynthID metadata proxy, visible marks) into one verdict."
)
id_in = gr.Image(type="filepath", label="Image")
id_btn = gr.Button("Identify", variant="primary")
id_out = gr.Textbox(label="Provenance report", lines=14)
gr.Examples(
examples=[
["examples/chatgpt-openai.png"],
["examples/google-nano-banana.png"],
["examples/microsoft-invismark.png"],
["examples/adobe-trustmark-p.png"],
["examples/sdxl-dwt-dct.png"],
["examples/doubao-aigc.png"],
["examples/recraft-v3.webp"],
],
inputs=id_in,
label="Examples (OpenAI SynthID/C2PA, Gemini, Microsoft InvisMark, Adobe TrustMark, SDXL DWT-DCT, Doubao, Recraft WebP)",
)
id_btn.click(run_identify, id_in, id_out)
with gr.Tab("Classify AI generator"):
gr.Markdown(
"Estimate the likely AI generator family (OpenAI, Google, ByteDance, FLUX, "
"Stable Diffusion, Meta, Midjourney, Ideogram, Adobe Firefly, xAI, or `unknown`) "
"and model version from pixel statistics alone "
f"([`{WEIGHTS_REPO}`](https://huggingface.co/{WEIGHTS_REPO})). "
"Runs on CPU in pure NumPy without metadata and abstains as `unknown` on camera "
"photos or unrecognized pipelines. Separate from `identify` and not SynthID "
"watermark detection."
)
cls_in = gr.Image(type="filepath", label="Image")
cls_btn = gr.Button("Classify generator", variant="primary")
cls_out = gr.Textbox(label="Generator attribution", lines=14)
gr.Examples(
examples=[
["examples/chatgpt-openai.png"],
["examples/google-nano-banana.png"],
["examples/microsoft-invismark.png"],
["examples/sdxl-dwt-dct.png"],
["examples/doubao-aigc.png"],
],
inputs=cls_in,
label="Examples (OpenAI, Google Gemini, Microsoft, SDXL, ByteDance Doubao)",
)
cls_btn.click(run_classify_source, cls_in, cls_out)
with gr.Tab("Remove visible mark"):
gr.Markdown(
"Detect and remove **every** registered visible AI-provenance mark in one "
"pass by localize -> fill. "
"Only the mark footprint is touched; the rest of the image is left alone. "
"**Sensitivity** sets how hard a borderline mark is trusted: *auto* relaxes "
"only on same-vendor evidence, while *strict* never relaxes. The fill here "
"is the classical cv2 inpaint; MI-GAN / LaMa run locally."
)
with gr.Row():
vis_in = gr.Image(type="filepath", label="Input")
vis_out = gr.Image(type="numpy", label="Cleaned")
vis_sensitivity = gr.Dropdown(
list(_SENSITIVITY), value="auto (recommended)", label="Sensitivity"
)
with gr.Row():
vis_detect_btn = gr.Button("Detect")
vis_btn = gr.Button("Remove", variant="primary")
vis_info = gr.Textbox(label="Result", lines=4)
vis_file = gr.File(label="Cleaned image")
gr.Examples(
examples=[["examples/doubao-aigc.png"], ["examples/google-nano-banana.png"]],
inputs=vis_in,
label="Examples (ByteDance Doubao text mark / Google Gemini sparkle)",
)
vis_btn.click(run_visible, [vis_in, vis_sensitivity], [vis_out, vis_file, vis_info])
vis_detect_btn.click(run_detect, vis_in, vis_info)
with gr.Tab("Strip metadata"):
gr.Markdown(
"Inspect or losslessly strip AI / provenance metadata (C2PA, EXIF, XMP, "
"IPTC, PNG chunks, the China TC260 AIGC label). Stripping never touches "
"the pixels: PNG/WebP stay pixel-identical and JPEG keeps its DCT scan "
"bit-for-bit."
)
meta_in = gr.Image(type="filepath", label="Image")
with gr.Row():
meta_check_btn = gr.Button("Check")
meta_strip_btn = gr.Button("Strip", variant="primary")
meta_out = gr.Textbox(label="Metadata", lines=10)
meta_file = gr.File(label="Cleaned image")
gr.Examples(
examples=[
["examples/chatgpt-openai.png"],
["examples/microsoft-invismark.png"],
["examples/recraft-v3.webp"],
["examples/doubao-aigc.png"],
],
inputs=meta_in,
label="Examples (PNG / WebP with C2PA & TC260)",
)
meta_check_btn.click(run_metadata_check, meta_in, meta_out)
meta_strip_btn.click(run_metadata_strip, meta_in, [meta_file, meta_out])
with gr.Tab("Clean video"):
gr.Markdown(
"Inspect video provenance or remove registered visible AI generator marks "
"(18 marks including Sora, Veo, Dreamina, Seedance, Doubao, Dola, Hailuo, "
"Vidu, Wan, Kling, Jimeng, Qwen, Yuanbao, Baidu, RunningHub, Microsoft) "
"and strip container/SEI/AV1 OBU/C2PA metadata across `.mp4`, `.mov`, `.m4v`, "
"`.mkv`, `.webm`, `.avi`, and `.flv` while preserving 10-bit HDR. "
"For `synthid`, `seedance`, `wan21-synthid`, and `wan21-seedance` invisible "
"video profiles, use the **Video** catalog tab."
)
with gr.Row():
vid_in = gr.Video(label="Input video")
vid_out = gr.Video(label="Cleaned video")
with gr.Row():
vid_mark = gr.Dropdown(_video_mark_choices(), value="auto", label="Visible mark")
vid_trim_bumper = gr.Checkbox(value=False, label="Trim trailing AI bumper")
with gr.Row():
vid_id_btn = gr.Button("Identify")
vid_clean_btn = gr.Button("Clean visible + metadata", variant="primary")
vid_info = gr.Textbox(label="Result", lines=6)
vid_file = gr.File(label="Cleaned video file")
gr.Examples(
examples=[
["examples/google-gemini-omni-app.mp4"],
["examples/dreamina-seedance-2-mini.mp4"],
],
inputs=vid_in,
label="Examples (Google Veo visible + SynthID / ByteDance Seedance)",
)
vid_id_btn.click(run_video_identify_quick, vid_in, vid_info)
vid_clean_btn.click(
run_video_clean_quick, [vid_in, vid_mark, vid_trim_bumper], [vid_out, vid_file, vid_info]
)
with gr.Tab("Clean audio"):
gr.Markdown(
"Inspect audio provenance and compatible waveform watermarks (AudioSeal, "
"WavMark, Perth, SilentCipher) or clean metadata and waveform marks across "
"`.wav`, `.flac`, `.mp3`, `.m4a`, `.ogg`, `.oga`, `.opus`, `.aac`, and `.mka` "
"via DAC 44.1 kHz, SNAC 44.1 kHz, EnCodec, combined, or spectral profiles. "
"Select a known generator cohort (`vendor`) when metadata was already stripped."
)
with gr.Row():
aud_in = gr.Audio(type="filepath", label="Input audio")
aud_out = gr.Audio(type="filepath", label="Cleaned audio")
with gr.Row():
aud_vendor = gr.Dropdown(_audio_vendor_choices(), value="auto", label="Vendor cohort")
aud_method = gr.Dropdown(_audio_method_choices(), value="auto", label="Cleaning method")
with gr.Row():
aud_id_btn = gr.Button("Identify")
aud_clean_btn = gr.Button("Clean audio", variant="primary")
aud_info = gr.Textbox(label="Result", lines=6)
aud_file = gr.File(label="Cleaned audio file")
gr.Examples(
examples=[
["examples/audioseal-stereo-48k.wav"],
["examples/veo-synthid-audio.wav"],
],
inputs=aud_in,
label="Examples (48 kHz stereo AudioSeal / Google Veo SynthID audio)",
)
aud_id_btn.click(run_audio_identify_quick, aud_in, aud_info)
aud_clean_btn.click(
run_audio_clean_quick, [aud_in, aud_vendor, aud_method], [aud_out, aud_file, aud_info]
)
with gr.Tab("Remove invisible (Qwen)"):
gr.Markdown(
"Qwen-Image-2512 invisible-watermark regeneration (CUDA, force=on). "
"First run downloads ~80GB of weights to the mounted cache; later runs are fast."
)
inv_in = gr.Image(type="filepath", label="Image")
inv_strength = gr.Slider(0.0, 1.0, value=0.0, step=0.05, label="Strength (0 = profile default; lower = closer to input)")
inv_cnet = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="ControlNet conditioning scale (higher = lock to input edges)")
inv_fid = gr.Checkbox(value=False, label="Fidelity anchor")
inv_maxres = gr.Number(value=0, precision=0, label="Max resolution (0 = default; 1254 = native)")
inv_polish = gr.Checkbox(value=False, label="Adaptive polish")
inv_btn = gr.Button("Remove invisible (Qwen)", variant="primary")
inv_prev = gr.Image(label="Cleaned", type="filepath")
inv_file = gr.File(label="Download cleaned")
inv_rep = gr.Textbox(label="Report", lines=8)
inv_btn.click(
run_invisible_qwen,
[inv_in, inv_strength, inv_cnet, inv_fid, inv_maxres, inv_polish],
[inv_prev, inv_file, inv_rep],
api_name="remove_invisible",
)
with gr.Tab("Remove invisible + text-safe (Qwen)"):
gr.Markdown(
"Invisible removal that **protects text**: OCR-drafts the page's text lines, "
"binds them to the source, and restores original glyphs after regeneration. "
"First run also downloads OCR + LaMa models."
)
ts_in = gr.Image(type="filepath", label="Image")
ts_strength = gr.Slider(0.0, 1.0, value=0.0, step=0.05, label="Strength (0 = profile default)")
ts_btn = gr.Button("Remove invisible + protect text", variant="primary")
ts_prev = gr.Image(label="Cleaned", type="filepath")
ts_file = gr.File(label="Download cleaned")
ts_rep = gr.Textbox(label="Report", lines=8)
ts_btn.click(
run_textsafe,
[ts_in, ts_strength],
[ts_prev, ts_file, ts_rep],
api_name="remove_textsafe",
)
with gr.Tab("Protect painted regions (Qwen)"):
gr.Markdown(
"**Paint the regions to keep faithful** (text, logos, marks); everything else "
"regenerates to disrupt invisible watermarks. Works best on dark text/marks over "
"a lighter background. Load an image, brush over what to protect, then run."
)
ts2_edit = gr.ImageEditor(type="numpy", label="Paint regions to protect",
brush=gr.Brush(colors=["#ff3b30"], default_size=24))
ts2_strength = gr.Slider(0.0, 1.0, value=0.0, step=0.05, label="Strength (0 = profile default)")
ts2_btn = gr.Button("Remove invisible + protect painted regions", variant="primary")
ts2_prev = gr.Image(label="Cleaned", type="filepath")
ts2_file = gr.File(label="Download cleaned")
ts2_rep = gr.Textbox(label="Report", lines=6)
ts2_btn.click(
run_textsafe_manual,
[ts2_edit, ts2_strength],
[ts2_prev, ts2_file, ts2_rep],
api_name="remove_textsafe_manual",
)
add_operation_tabs()
gr.Markdown(
"Watermarking is a weak trust signal: a mark that is almost always "
"present yet removable can make a cleaned forgery look more trustworthy. "
"Half of this tool is `identify`, which reads provenance rather than "
"removing it. The point is user autonomy over your **own** AI generations, "
"not stripping a third party's paid asset. See the repo for the legal limits "
"on removing AI labels."
)
if __name__ == "__main__":
demo.launch()