scrubworks 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 scrubworks 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,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: scrubworks
3
+ Version: 0.1.0
4
+ Summary: Mask sensitive contact fields and remove JPEG metadata
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # scrubworks for Python
12
+
13
+ Mask contact fields and strip JPEG metadata locally. The package supports Python 3.10 or later and has zero runtime dependencies.
14
+
15
+ ```sh
16
+ python -m pip install scrubworks
17
+ ```
18
+
19
+ ```python
20
+ from pathlib import Path
21
+ from scrubworks import mask_email, mask_phone, strip_jpeg_metadata
22
+
23
+ assert mask_email("user@example.com") == "***@***"
24
+ assert mask_phone("+1 (202) 555-0134") == "***0134"
25
+
26
+ original = Path("upload.jpg").read_bytes()
27
+ clean = strip_jpeg_metadata(original, max_bytes=16 * 1024 * 1024)
28
+ Path("clean.jpg").write_bytes(clean)
29
+ ```
30
+
31
+ Email masking hides both parts by default and can expose the first local character or domain. Phone masking exposes up to four trailing digits and can hide all digits with `reveal_last=0`. These helpers operate on known fields.
32
+
33
+ JPEG cleaning removes APP and comment segments, including EXIF GPS, XMP, IPTC, thumbnails, and ICC profiles stored in those segments. It preserves compressed image data from baseline, extended sequential, and progressive Huffman JPEGs. Malformed framing, unsupported markers, oversized files, and trailing data are rejected. Removing orientation or ICC information can change the displayed orientation or colors. Use a decoder when you also need to verify image data or normalize orientation and color for export. Pixel content and other file formats require separate handling.
34
+
35
+ ## Development
36
+
37
+ Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package. FFmpeg enables the real JPEG decoder test.
38
+
39
+ ## License
40
+
41
+ MIT
@@ -0,0 +1,31 @@
1
+ # scrubworks for Python
2
+
3
+ Mask contact fields and strip JPEG metadata locally. The package supports Python 3.10 or later and has zero runtime dependencies.
4
+
5
+ ```sh
6
+ python -m pip install scrubworks
7
+ ```
8
+
9
+ ```python
10
+ from pathlib import Path
11
+ from scrubworks import mask_email, mask_phone, strip_jpeg_metadata
12
+
13
+ assert mask_email("user@example.com") == "***@***"
14
+ assert mask_phone("+1 (202) 555-0134") == "***0134"
15
+
16
+ original = Path("upload.jpg").read_bytes()
17
+ clean = strip_jpeg_metadata(original, max_bytes=16 * 1024 * 1024)
18
+ Path("clean.jpg").write_bytes(clean)
19
+ ```
20
+
21
+ Email masking hides both parts by default and can expose the first local character or domain. Phone masking exposes up to four trailing digits and can hide all digits with `reveal_last=0`. These helpers operate on known fields.
22
+
23
+ JPEG cleaning removes APP and comment segments, including EXIF GPS, XMP, IPTC, thumbnails, and ICC profiles stored in those segments. It preserves compressed image data from baseline, extended sequential, and progressive Huffman JPEGs. Malformed framing, unsupported markers, oversized files, and trailing data are rejected. Removing orientation or ICC information can change the displayed orientation or colors. Use a decoder when you also need to verify image data or normalize orientation and color for export. Pixel content and other file formats require separate handling.
24
+
25
+ ## Development
26
+
27
+ Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package. FFmpeg enables the real JPEG decoder test.
28
+
29
+ ## License
30
+
31
+ MIT
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scrubworks"
7
+ version = "0.1.0"
8
+ description = "Mask sensitive contact fields and remove JPEG metadata"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = []
14
+
15
+ [tool.setuptools.packages.find]
16
+ where = ["src"]
17
+
18
+ [tool.setuptools.package-data]
19
+ scrubworks = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Contact field masking and JPEG metadata removal."""
2
+
3
+ from .jpeg import JpegMetadataError, strip_jpeg_metadata
4
+ from .mask import mask_email, mask_phone
5
+
6
+ __all__ = ["JpegMetadataError", "mask_email", "mask_phone", "strip_jpeg_metadata"]
@@ -0,0 +1,94 @@
1
+ """Remove JPEG APP and comment markers while retaining scan bytes."""
2
+
3
+ _DEFAULT_SIZE = 32 * 1024 * 1024
4
+ _RESTARTS = range(0xD0, 0xD8)
5
+
6
+
7
+ class JpegMetadataError(ValueError):
8
+ def __init__(self, code: str, message: str):
9
+ super().__init__(message)
10
+ self.code = code
11
+
12
+
13
+ def _invalid(message: str) -> JpegMetadataError:
14
+ return JpegMetadataError("INVALID_JPEG", message)
15
+
16
+
17
+ def _word(data: bytes, offset: int) -> int:
18
+ if offset + 2 > len(data):
19
+ raise _invalid("Truncated JPEG segment.")
20
+ return (data[offset] << 8) | data[offset + 1]
21
+
22
+
23
+ def _scan_end(data: bytes, offset: int) -> int:
24
+ while (start := data.find(b"\xff", offset)) != -1:
25
+ offset = start + 1
26
+ while offset < len(data) and data[offset] == 0xFF:
27
+ offset += 1
28
+ if offset == len(data):
29
+ break
30
+ marker = data[offset]
31
+ if marker != 0 and marker not in _RESTARTS:
32
+ return start
33
+ offset += 1
34
+ raise _invalid("Unterminated JPEG scan.")
35
+
36
+
37
+ def strip_jpeg_metadata(source: bytes | bytearray | memoryview, *, max_bytes: int = _DEFAULT_SIZE) -> bytes:
38
+ """Return a JPEG without APP or COM segments."""
39
+ if type(max_bytes) is not int or max_bytes < 1:
40
+ raise ValueError("The JPEG size limit must be positive.")
41
+ if not isinstance(source, (bytes, bytearray, memoryview)):
42
+ raise TypeError("JPEG input must be bytes-like.")
43
+ size = source.nbytes if isinstance(source, memoryview) else len(source)
44
+ if size > max_bytes:
45
+ raise JpegMetadataError("JPEG_TOO_LARGE", "JPEG exceeds the size limit.")
46
+ data = bytes(source)
47
+ if _word(data, 0) != 0xFFD8:
48
+ raise _invalid("Missing JPEG start marker.")
49
+
50
+ offset, keep_from = 2, 0
51
+ output = bytearray()
52
+ has_frame, has_scan = False, False
53
+ while offset < len(data):
54
+ start = offset
55
+ if data[offset] != 0xFF:
56
+ raise _invalid("Expected a JPEG marker.")
57
+ while offset < len(data) and data[offset] == 0xFF:
58
+ offset += 1
59
+ if offset == len(data):
60
+ break
61
+ marker = data[offset]
62
+ offset += 1
63
+ if marker == 0xD9:
64
+ if not has_scan or offset != len(data):
65
+ raise _invalid("Incomplete JPEG or data after the end marker.")
66
+ output.extend(memoryview(data)[keep_from:])
67
+ return bytes(output)
68
+ if marker in {0, 0xD8} or marker in _RESTARTS:
69
+ raise _invalid("Unexpected JPEG marker.")
70
+ length = _word(data, offset)
71
+ end = offset + length
72
+ if length < 2 or end > len(data):
73
+ raise _invalid("Invalid JPEG segment length.")
74
+ if 0xE0 <= marker <= 0xEF or marker == 0xFE:
75
+ output.extend(memoryview(data)[keep_from:start])
76
+ keep_from = end
77
+ elif marker in {0xC0, 0xC1, 0xC2}:
78
+ if has_frame or length < 11 or not data[offset + 7] or length != 8 + 3 * data[offset + 7] or (
79
+ _word(data, offset + 3) == 0 or _word(data, offset + 5) == 0
80
+ ):
81
+ raise _invalid("Invalid JPEG frame header.")
82
+ has_frame = True
83
+ elif marker == 0xDA:
84
+ if not has_frame or length < 8 or not data[offset + 2] or length != 6 + 2 * data[offset + 2]:
85
+ raise _invalid("Invalid JPEG scan header.")
86
+ offset = _scan_end(data, end)
87
+ if offset == end:
88
+ raise _invalid("Empty JPEG scan.")
89
+ has_scan = True
90
+ continue
91
+ elif marker not in {0xC4, 0xDB, 0xDD}:
92
+ raise JpegMetadataError("UNSUPPORTED_JPEG", "Unsupported JPEG coding marker.")
93
+ offset = end
94
+ raise _invalid("Missing JPEG end marker.")
@@ -0,0 +1,33 @@
1
+ """Mask contact fields without echoing invalid input."""
2
+
3
+ import re
4
+
5
+ _LOCAL = re.compile(r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*",
6
+ re.IGNORECASE | re.ASCII)
7
+ _LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", re.IGNORECASE | re.ASCII)
8
+
9
+
10
+ def mask_email(value: str, *, reveal_first_character: bool = False,
11
+ reveal_domain: bool = False) -> str:
12
+ """Mask a common unquoted ASCII email address."""
13
+ if not isinstance(value, str) or len(value) > 254:
14
+ raise ValueError("Invalid email address.")
15
+ local, separator, domain = value.partition("@")
16
+ if not separator or len(local) > 64 or not _LOCAL.fullmatch(local) or not all(
17
+ _LABEL.fullmatch(label) for label in domain.split(".")
18
+ ):
19
+ raise ValueError("Invalid email address.")
20
+ prefix = local[0] if reveal_first_character and len(local) > 1 else ""
21
+ return f"{prefix}***@{domain if reveal_domain else '***'}"
22
+
23
+
24
+ def mask_phone(value: str, *, reveal_last: int = 4) -> str:
25
+ """Mask a phone number with optional formatting."""
26
+ if type(reveal_last) is not int or not 0 <= reveal_last <= 4:
27
+ raise ValueError("reveal_last must be an integer from 0 through 4.")
28
+ if not isinstance(value, str) or len(value) > 64 or not re.fullmatch(r"\+?[0-9 ().-]+", value):
29
+ raise ValueError("Invalid phone number format.")
30
+ digits = re.sub(r"[^0-9]", "", value)
31
+ if not 7 <= len(digits) <= 15:
32
+ raise ValueError("Invalid phone number length.")
33
+ return f"***{digits[-reveal_last:]}" if reveal_last else "***"
File without changes
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: scrubworks
3
+ Version: 0.1.0
4
+ Summary: Mask sensitive contact fields and remove JPEG metadata
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # scrubworks for Python
12
+
13
+ Mask contact fields and strip JPEG metadata locally. The package supports Python 3.10 or later and has zero runtime dependencies.
14
+
15
+ ```sh
16
+ python -m pip install scrubworks
17
+ ```
18
+
19
+ ```python
20
+ from pathlib import Path
21
+ from scrubworks import mask_email, mask_phone, strip_jpeg_metadata
22
+
23
+ assert mask_email("user@example.com") == "***@***"
24
+ assert mask_phone("+1 (202) 555-0134") == "***0134"
25
+
26
+ original = Path("upload.jpg").read_bytes()
27
+ clean = strip_jpeg_metadata(original, max_bytes=16 * 1024 * 1024)
28
+ Path("clean.jpg").write_bytes(clean)
29
+ ```
30
+
31
+ Email masking hides both parts by default and can expose the first local character or domain. Phone masking exposes up to four trailing digits and can hide all digits with `reveal_last=0`. These helpers operate on known fields.
32
+
33
+ JPEG cleaning removes APP and comment segments, including EXIF GPS, XMP, IPTC, thumbnails, and ICC profiles stored in those segments. It preserves compressed image data from baseline, extended sequential, and progressive Huffman JPEGs. Malformed framing, unsupported markers, oversized files, and trailing data are rejected. Removing orientation or ICC information can change the displayed orientation or colors. Use a decoder when you also need to verify image data or normalize orientation and color for export. Pixel content and other file formats require separate handling.
34
+
35
+ ## Development
36
+
37
+ Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package. FFmpeg enables the real JPEG decoder test.
38
+
39
+ ## License
40
+
41
+ MIT
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/scrubworks/__init__.py
5
+ src/scrubworks/jpeg.py
6
+ src/scrubworks/mask.py
7
+ src/scrubworks/py.typed
8
+ src/scrubworks.egg-info/PKG-INFO
9
+ src/scrubworks.egg-info/SOURCES.txt
10
+ src/scrubworks.egg-info/dependency_links.txt
11
+ src/scrubworks.egg-info/top_level.txt
12
+ tests/test_privacy.py
@@ -0,0 +1 @@
1
+ scrubworks
@@ -0,0 +1,48 @@
1
+ import subprocess
2
+ import shutil
3
+ import unittest
4
+
5
+ from scrubworks import JpegMetadataError, mask_email, mask_phone, strip_jpeg_metadata
6
+
7
+
8
+ def segment(marker, payload):
9
+ return bytes((255, marker)) + (len(payload) + 2).to_bytes(2, "big") + payload
10
+
11
+
12
+ class PrivacyTests(unittest.TestCase):
13
+ def test_mask_fields(self):
14
+ self.assertEqual(mask_email("user@example.com"), "***@***")
15
+ self.assertEqual(mask_email("user@example.com", reveal_domain=True), "***@example.com")
16
+ self.assertEqual(mask_phone("+1 (202) 555-0134"), "***0134")
17
+ self.assertEqual(mask_phone("2025550134", reveal_last=0), "***")
18
+ with self.assertRaisesRegex(ValueError, "^Invalid email address"):
19
+ mask_email("private value")
20
+
21
+ def test_removes_segments_between_scans(self):
22
+ frame = bytes((255, 194, 0, 11, 8, 0, 8, 0, 8, 1, 1, 17, 0))
23
+ scan = bytes((255, 218, 0, 8, 1, 1, 0, 0, 0, 0, 1, 255, 0, 2, 255, 208, 3))
24
+ start, end = b"\xff\xd8", b"\xff\xd9"
25
+ original = start + segment(225, b"Exif\0\0GPS") + frame + scan + segment(254, b"note") + scan + end
26
+ self.assertEqual(strip_jpeg_metadata(original), start + frame + scan + scan + end)
27
+ with self.assertRaises(JpegMetadataError):
28
+ strip_jpeg_metadata(original + b"trailer")
29
+ with self.assertRaises(JpegMetadataError) as exception:
30
+ strip_jpeg_metadata(original, max_bytes=1)
31
+ self.assertEqual(exception.exception.code, "JPEG_TOO_LARGE")
32
+
33
+ @unittest.skipUnless(shutil.which("ffmpeg"), "FFmpeg is required for the decoder integration.")
34
+ def test_preserves_decoded_pixels(self):
35
+ def run(*args, data=None):
36
+ return subprocess.run(["ffmpeg", "-v", "error", *args], input=data,
37
+ check=True, capture_output=True).stdout
38
+
39
+ jpeg = run("-f", "lavfi", "-i", "testsrc=size=48x32", "-frames:v", "1",
40
+ "-threads", "1", "-c:v", "mjpeg", "-f", "image2pipe", "pipe:1")
41
+ marker = segment(225, b"Exif\x00\x00Synthetic metadata")
42
+ original = jpeg[:2] + marker + jpeg[2:-2] + segment(254, b"Private note") + jpeg[-2:]
43
+ cleaned = strip_jpeg_metadata(original)
44
+ self.assertNotIn(marker, cleaned)
45
+ self.assertNotIn(b"Private note", cleaned)
46
+ decode = ("-f", "image2pipe", "-c:v", "mjpeg", "-i", "pipe:0", "-frames:v", "1",
47
+ "-threads", "1", "-c:v", "rawvideo", "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1")
48
+ self.assertEqual(run(*decode, data=original), run(*decode, data=cleaned))