naymark 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
naymark/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ from .core import (
2
+ RemovalResult,
3
+ WatermarkDetection,
4
+ WatermarkRemover,
5
+ detect_watermarks,
6
+ load_image,
7
+ remove_watermark,
8
+ save_image,
9
+ )
10
+
11
+ __all__ = [
12
+ "RemovalResult",
13
+ "WatermarkDetection",
14
+ "WatermarkRemover",
15
+ "detect_watermarks",
16
+ "load_image",
17
+ "remove_watermark",
18
+ "save_image",
19
+ ]
naymark/cli.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+
5
+ from .core import WatermarkRemover
6
+
7
+
8
+ def main() -> int:
9
+ parser = argparse.ArgumentParser(
10
+ description="Remove a matching watermark from an authorized image."
11
+ )
12
+ parser.add_argument("input", help="source image path")
13
+ parser.add_argument("output", help="destination image path")
14
+ parser.add_argument(
15
+ "--threshold",
16
+ type=float,
17
+ default=0.6,
18
+ help="match score threshold (default: %(default)s)",
19
+ )
20
+ parser.add_argument(
21
+ "--max-watermarks",
22
+ type=int,
23
+ default=5,
24
+ help="maximum number of matches to remove (default: %(default)s)",
25
+ )
26
+ args = parser.parse_args()
27
+
28
+ result = WatermarkRemover(
29
+ threshold=args.threshold,
30
+ max_watermarks=args.max_watermarks,
31
+ ).remove_file(args.input, args.output)
32
+ print(f"Saved cleaned image to {result.output_path}")
33
+ print(f"Detected watermarks: {len(result.detections)}")
34
+ return 0
35
+
36
+
37
+ if __name__ == "__main__":
38
+ raise SystemExit(main())
naymark/core.py ADDED
@@ -0,0 +1,288 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from importlib import resources
5
+ from pathlib import Path
6
+ from typing import Optional, Sequence, Union
7
+
8
+ import cv2
9
+ import numpy as np
10
+
11
+ from .templates import Template, load_templates
12
+
13
+ ImageInput = Union[str, Path, np.ndarray]
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class WatermarkDetection:
18
+ x: int
19
+ y: int
20
+ width: int
21
+ height: int
22
+ score: float
23
+ template: str
24
+ gain: Optional[float] = None
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class RemovalResult:
29
+ image: np.ndarray
30
+ detections: tuple[WatermarkDetection, ...]
31
+ output_path: Optional[Path] = None
32
+
33
+
34
+ def _validate_image(image: np.ndarray) -> np.ndarray:
35
+ if not isinstance(image, np.ndarray):
36
+ raise TypeError("image must be a numpy.ndarray")
37
+ if image.ndim != 3 or image.shape[2] != 3:
38
+ raise ValueError("image must be a three-channel BGR array")
39
+ if image.dtype != np.uint8:
40
+ raise ValueError("image must have dtype numpy.uint8")
41
+ if image.shape[0] == 0 or image.shape[1] == 0:
42
+ raise ValueError("image must not be empty")
43
+ return image
44
+
45
+
46
+ def load_image(path: Union[str, Path]) -> np.ndarray:
47
+ """Load an image as an 8-bit BGR array."""
48
+ image_path = Path(path)
49
+ if not image_path.is_file():
50
+ raise FileNotFoundError(f"Image file does not exist: {image_path}")
51
+ encoded = np.fromfile(image_path, dtype=np.uint8)
52
+ image = cv2.imdecode(encoded, cv2.IMREAD_COLOR)
53
+ if image is None:
54
+ raise ValueError(f"Could not decode image: {image_path}")
55
+ return image
56
+
57
+
58
+ def save_image(image: np.ndarray, path: Union[str, Path]) -> Path:
59
+ """Encode and save a BGR image, creating parent directories if needed."""
60
+ _validate_image(image)
61
+ image_path = Path(path)
62
+ extension = image_path.suffix.lower()
63
+ if not extension:
64
+ raise ValueError("path must have an image extension such as .png or .jpg")
65
+ image_path.parent.mkdir(parents=True, exist_ok=True)
66
+ try:
67
+ success, encoded = cv2.imencode(extension, image)
68
+ except cv2.error as exc:
69
+ raise ValueError(f"Unsupported image extension: {extension}") from exc
70
+ if not success:
71
+ raise ValueError(f"Could not encode image as {extension}")
72
+ image_path.write_bytes(encoded.tobytes())
73
+ return image_path
74
+
75
+
76
+ def _gray(image: np.ndarray) -> np.ndarray:
77
+ return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
78
+
79
+
80
+ def _high_pass(image: np.ndarray) -> np.ndarray:
81
+ image = image.astype(np.float32)
82
+ return image - cv2.GaussianBlur(image, (0, 0), 2)
83
+
84
+
85
+ def _normalized_correlation(left: np.ndarray, right: np.ndarray) -> float:
86
+ left = left - left.mean()
87
+ right = right - right.mean()
88
+ denominator = np.sqrt((left * left).sum() * (right * right).sum()) + 1e-8
89
+ return float((left * right).sum() / denominator)
90
+
91
+
92
+ def _detect_multiscale(
93
+ image: np.ndarray,
94
+ templates: Sequence[Template],
95
+ threshold: float,
96
+ ) -> dict | None:
97
+ height, width = image.shape[:2]
98
+ search_region = _high_pass(_gray(image))
99
+ best = None
100
+ for template in templates:
101
+ base = template.alpha * 255
102
+ for scale in np.linspace(0.6, 2.0, 29):
103
+ template_width = int(base.shape[1] * scale)
104
+ template_height = int(base.shape[0] * scale)
105
+ if (
106
+ template_width < 12
107
+ or template_height < 12
108
+ or template_height >= height
109
+ or template_width >= width
110
+ ):
111
+ continue
112
+ resized = cv2.resize(
113
+ base,
114
+ (template_width, template_height),
115
+ interpolation=cv2.INTER_AREA,
116
+ )
117
+ match = cv2.matchTemplate(
118
+ search_region,
119
+ _high_pass(resized),
120
+ cv2.TM_CCOEFF_NORMED,
121
+ )
122
+ _, score, _, location = cv2.minMaxLoc(match)
123
+ if best is None or score > best["score"]:
124
+ alpha = cv2.resize(
125
+ template.alpha,
126
+ (template_width, template_height),
127
+ interpolation=cv2.INTER_AREA,
128
+ )
129
+ best = {
130
+ "score": float(score),
131
+ "x": location[0],
132
+ "y": location[1],
133
+ "alpha": alpha,
134
+ "template": template.name,
135
+ }
136
+ return best if best is not None and best["score"] >= threshold else None
137
+
138
+
139
+ def _repair(image: np.ndarray, detection: dict, margin: int = 12) -> tuple[np.ndarray, float]:
140
+ alpha = detection["alpha"]
141
+ mark_height, mark_width = alpha.shape
142
+ image_height, image_width = image.shape[:2]
143
+ mark_x, mark_y = detection["x"], detection["y"]
144
+ x0, y0 = max(mark_x - margin, 0), max(mark_y - margin, 0)
145
+ x1 = min(mark_x + mark_width + margin, image_width)
146
+ y1 = min(mark_y + mark_height + margin, image_height)
147
+
148
+ roi = image[y0:y1, x0:x1].astype(np.float32)
149
+ mask = np.zeros(roi.shape[:2], np.float32)
150
+ mask[
151
+ mark_y - y0 : mark_y - y0 + mark_height,
152
+ mark_x - x0 : mark_x - x0 + mark_width,
153
+ ] = alpha
154
+ outer = (mask > 0.03).astype(np.uint8)
155
+ core = mask > 0.5 * mask.max()
156
+ kernel = lambda size: np.ones((size, size), np.uint8)
157
+ ring = (cv2.dilate(outer, kernel(15)) > 0) & ~(
158
+ cv2.dilate(outer, kernel(5)) > 0
159
+ )
160
+ if ring.sum() < 20:
161
+ ring = ~(cv2.dilate(outer, kernel(5)) > 0)
162
+ target = roi[ring].mean(axis=0) if ring.any() else roi.reshape(-1, 3).mean(axis=0)
163
+
164
+ best = None
165
+ for gain in np.arange(0.8, 3.01, 0.05):
166
+ alpha3 = np.clip(mask * gain, 0, 0.95)[..., None]
167
+ reconstructed = np.clip(
168
+ (roi - alpha3 * 255.0) / (1.0 - alpha3),
169
+ 0,
170
+ 255,
171
+ )
172
+ core_pixels = reconstructed[core]
173
+ score = np.abs(core_pixels.mean(axis=0) - target).sum()
174
+ score += 500 * ((core_pixels <= 0) | (core_pixels >= 255)).mean()
175
+ if best is None or score < best[0]:
176
+ best = (score, gain, reconstructed)
177
+ _, gain, reconstructed = best
178
+
179
+ output = image.copy()
180
+ output[y0:y1, x0:x1] = reconstructed.astype(np.uint8)
181
+ band = (
182
+ (cv2.dilate(outer, kernel(5)) > 0)
183
+ & ~(cv2.erode(outer, kernel(5)) > 0)
184
+ ).astype(np.uint8) * 255
185
+ roi_output = np.ascontiguousarray(output[y0:y1, x0:x1])
186
+ output[y0:y1, x0:x1] = cv2.inpaint(roi_output, band, 2, cv2.INPAINT_TELEA)
187
+ return output, round(float(gain), 2)
188
+
189
+
190
+ class WatermarkRemover:
191
+ """Detect and remove matches for the bundled or supplied watermark template."""
192
+
193
+ def __init__(
194
+ self,
195
+ threshold: float = 0.6,
196
+ max_watermarks: int = 5,
197
+ template_dir: Union[str, Path, None] = None,
198
+ ) -> None:
199
+ if not np.isfinite(threshold) or not 0 <= threshold <= 1:
200
+ raise ValueError("threshold must be between 0 and 1")
201
+ if isinstance(max_watermarks, bool) or max_watermarks < 1:
202
+ raise ValueError("max_watermarks must be at least 1")
203
+ self.threshold = float(threshold)
204
+ self.max_watermarks = int(max_watermarks)
205
+ self.templates = load_templates(template_dir)
206
+
207
+ def _process(
208
+ self,
209
+ image: np.ndarray,
210
+ ) -> tuple[np.ndarray, list[WatermarkDetection]]:
211
+ output = _validate_image(image).copy()
212
+ detections = []
213
+ for _ in range(self.max_watermarks):
214
+ match = _detect_multiscale(output, self.templates, self.threshold)
215
+ if match is None:
216
+ break
217
+ if any(
218
+ abs(match["x"] - hit.x) < 20 and abs(match["y"] - hit.y) < 20
219
+ for hit in detections
220
+ ):
221
+ break
222
+ output, gain = _repair(output, match)
223
+ alpha_height, alpha_width = match["alpha"].shape
224
+ detections.append(
225
+ WatermarkDetection(
226
+ x=match["x"],
227
+ y=match["y"],
228
+ width=alpha_width,
229
+ height=alpha_height,
230
+ score=match["score"],
231
+ template=match["template"],
232
+ gain=gain,
233
+ )
234
+ )
235
+ return output, detections
236
+
237
+ def detect(self, image: np.ndarray) -> list[WatermarkDetection]:
238
+ """Return detected matches, searching iteratively for multiple instances."""
239
+ _, detections = self._process(image)
240
+ return detections
241
+
242
+ def remove(self, image: np.ndarray) -> tuple[np.ndarray, list[WatermarkDetection]]:
243
+ """Return a cleaned BGR image and details for each detected match."""
244
+ return self._process(image)
245
+
246
+ def remove_file(
247
+ self,
248
+ input_path: Union[str, Path],
249
+ output_path: Union[str, Path, None] = None,
250
+ ) -> RemovalResult:
251
+ source = Path(input_path)
252
+ target = (
253
+ Path(output_path)
254
+ if output_path is not None
255
+ else source.with_name(f"{source.stem}_cleaned{source.suffix}")
256
+ )
257
+ cleaned, detections = self.remove(load_image(source))
258
+ saved_path = save_image(cleaned, target)
259
+ return RemovalResult(cleaned, tuple(detections), saved_path)
260
+
261
+
262
+ def detect_watermarks(
263
+ image: ImageInput,
264
+ threshold: float = 0.6,
265
+ max_watermarks: int = 5,
266
+ template_dir: Union[str, Path, None] = None,
267
+ ) -> list[WatermarkDetection]:
268
+ """Detect template matches in a file path or BGR image array."""
269
+ remover = WatermarkRemover(threshold, max_watermarks, template_dir)
270
+ image_array = load_image(image) if isinstance(image, (str, Path)) else image
271
+ return remover.detect(image_array)
272
+
273
+
274
+ def remove_watermark(
275
+ image: ImageInput,
276
+ output_path: Union[str, Path, None] = None,
277
+ threshold: float = 0.6,
278
+ max_watermarks: int = 5,
279
+ template_dir: Union[str, Path, None] = None,
280
+ ) -> RemovalResult:
281
+ """Remove matches from an array or file, saving file inputs by default."""
282
+ remover = WatermarkRemover(threshold, max_watermarks, template_dir)
283
+ if isinstance(image, (str, Path)):
284
+ return remover.remove_file(image, output_path)
285
+
286
+ cleaned, detections = remover.remove(image)
287
+ saved_path = save_image(cleaned, output_path) if output_path is not None else None
288
+ return RemovalResult(cleaned, tuple(detections), saved_path)
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from importlib import resources
5
+ from pathlib import Path
6
+ from typing import Union
7
+
8
+ import numpy as np
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Template:
13
+ name: str
14
+ alpha: np.ndarray
15
+ mx: int
16
+ my: int
17
+
18
+
19
+ def _read_template(path) -> Template:
20
+ with path.open("rb") as stream:
21
+ with np.load(stream, allow_pickle=False) as data:
22
+ alpha = np.asarray(data["alpha"], dtype=np.float32)
23
+ mx = int(data["mx"])
24
+ my = int(data["my"])
25
+ if alpha.ndim != 2 or not np.isfinite(alpha).all() or alpha.max(initial=0) <= 0:
26
+ raise ValueError(f"Invalid alpha mask in template: {path.name}")
27
+ alpha = np.clip(alpha, 0, 1)
28
+ return Template(path.name.rsplit(".", 1)[0], alpha, mx, my)
29
+
30
+
31
+ def load_templates(folder: Union[str, Path, None] = None) -> list[Template]:
32
+ """Load packaged templates, or compatible .npz files from a directory."""
33
+ if folder is None:
34
+ template_paths = [resources.files("naymark").joinpath("templates", "main.npz")]
35
+ else:
36
+ template_dir = Path(folder)
37
+ if not template_dir.is_dir():
38
+ raise FileNotFoundError(f"Template directory does not exist: {template_dir}")
39
+ template_paths = sorted(template_dir.glob("*.npz"))
40
+ if not template_paths:
41
+ raise ValueError("No .npz watermark templates were found")
42
+ return [_read_template(path) for path in template_paths]
Binary file
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: naymark
3
+ Version: 0.1.0
4
+ Summary: Remove an authorized, known watermark from images
5
+ License-Expression: MIT
6
+ Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.23
19
+ Requires-Dist: opencv-python-headless>=4.8
20
+ Dynamic: license-file
21
+
22
+ # Naymark
23
+
24
+ ![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776AB?logo=python&logoColor=white)
25
+ ![MIT License](https://img.shields.io/badge/License-MIT-green.svg)
26
+ ![Development status](https://img.shields.io/badge/Status-Alpha-orange)
27
+ ![NumPy](https://img.shields.io/badge/NumPy-1.23%2B-013243?logo=numpy&logoColor=white)
28
+ ![OpenCV](https://img.shields.io/badge/OpenCV-4.8%2B-5C3EE8?logo=opencv&logoColor=white)
29
+
30
+ Naymark is a small Python package for removing the supported **visible watermark**
31
+ from Gemini-generated images. It uses a bundled image template to find matches
32
+ and reconstruct the surrounding pixels.
33
+
34
+ Naymark is intended for images you created or are authorized to modify. It is an
35
+ independent project and is not affiliated with Google or Gemini.
36
+
37
+ ## What it does
38
+
39
+ - Finds matches for the bundled visible-watermark template across supported
40
+ image scales.
41
+ - Processes image files or OpenCV-style BGR arrays.
42
+ - Reports match locations and scores, and can save the cleaned image.
43
+ - Runs locally; images are not uploaded to a service.
44
+
45
+ Naymark is designed for this template, not as a general-purpose watermark
46
+ remover. Pixel reconstruction is approximate, so inspect the output. It does
47
+ not target invisible provenance signals; follow any disclosure or attribution
48
+ requirements that apply to your images.
49
+
50
+ ## For developers
51
+
52
+ ### Install
53
+
54
+ After the package is published on PyPI:
55
+
56
+ ```bash
57
+ python -m pip install naymark
58
+ ```
59
+
60
+ ### Python
61
+
62
+ ```python
63
+ from naymark import remove_watermark
64
+
65
+ result = remove_watermark("input.jpg", "output.png")
66
+ print("Saved:", result.output_path)
67
+ print("Matches:", len(result.detections))
68
+ ```
69
+
70
+ For file input, Naymark saves a sibling file named
71
+ `<filename>_cleaned<extension>` if no output path is supplied. For array input,
72
+ the cleaned image is available as `result.image`.
73
+
74
+ ### Command line
75
+
76
+ The input and output paths are required:
77
+
78
+ ```bash
79
+ naymark input.jpg output.png
80
+ ```
81
+
82
+ #### Optional arguments
83
+
84
+ Both tuning arguments are optional and use the defaults shown below.
85
+
86
+ | Argument | Default | Description |
87
+ | --- | ---: | --- |
88
+ | `--threshold FLOAT` | `0.6` | Minimum template-match score for a detection. |
89
+ | `--max-watermarks INTEGER` | `5` | Maximum number of matches to remove from the image. |
90
+
91
+ For example, override either or both values:
92
+
93
+ ```bash
94
+ naymark input.jpg output.png --threshold 0.7
95
+ naymark input.jpg output.png --max-watermarks 3
96
+ naymark input.jpg output.png --threshold 0.7 --max-watermarks 3
97
+ ```
98
+
99
+ ## For contributors
100
+
101
+ ### Set up a local checkout
102
+
103
+ Create and activate a virtual environment, then install Naymark in editable
104
+ mode:
105
+
106
+ ```bash
107
+ python -m venv .venv
108
+ python -m pip install -e .
109
+ ```
110
+
111
+ ### Run tests
112
+
113
+ ```bash
114
+ python -m unittest discover -s tests -v
115
+ ```
116
+
117
+ ### Build distributions
118
+
119
+ ```bash
120
+ python -m pip install build
121
+ python -m build
122
+ ```
123
+
124
+ Build artifacts are written to `dist/`.
125
+
126
+ ## License
127
+
128
+ Naymark is distributed under the MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ naymark/__init__.py,sha256=EZJ8AV7dQXRsp4JqQkb41TQQKxYjNeElnnx26Jo1HHk,354
2
+ naymark/cli.py,sha256=HsfXaItRLRyXhZjyzw9CeUJFJxcZP__2CvvgLEsR270,1091
3
+ naymark/core.py,sha256=S1kTVZlmZkHaXEccoKpj10W9NjXLST1rsvMUAFaH0XY,10538
4
+ naymark/templates/__init__.py,sha256=Vy5lMORM_3m1kifeJZtEGHDbTok44Z_hberIoR32vVI,1492
5
+ naymark/templates/main.npz,sha256=s1JSQDw4BCa0zZN7AqABqBM45El_HMksIO4P44kYJWI,11568
6
+ naymark-0.1.0.dist-info/licenses/LICENSE,sha256=1pdTHKV4xjqg-VK4zea3zQAG7IwMT4xjUoW7p1U_vP0,1098
7
+ naymark-0.1.0.dist-info/METADATA,sha256=usCizoxm3n0y8awTdN6qMITCdrQ2r45fn9n10p02aNw,3808
8
+ naymark-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ naymark-0.1.0.dist-info/entry_points.txt,sha256=_OjiCBfjkfXiAxx1F28ZmKwQwQigCSbeNHiO1okmEfk,45
10
+ naymark-0.1.0.dist-info/top_level.txt,sha256=GkdZZ-GGyRR3VCRY5j-VFf0pPa8ZVwFF3du3jJF7R-4,8
11
+ naymark-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ naymark = naymark.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Naymark contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ naymark