segmentation-claim-audit 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.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .audit import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,191 @@
1
+ """Offline documentation and AST inspection. Source is never executed."""
2
+ import argparse
3
+ import ast
4
+ import fnmatch
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import sys
10
+
11
+ from . import __version__
12
+ from .phrases import SEGMENTATION, NOSEGMENTATION
13
+
14
+
15
+ def normalize(text):
16
+ return re.sub(r'\s+', ' ', text.lower().replace("n't", ' not').replace('-', ' ')).strip()
17
+
18
+
19
+ def _pattern(phrases):
20
+ return re.compile(r'\b(?:' + '|'.join(re.escape(p) for p in sorted(phrases, key=len, reverse=True)) + r')\b')
21
+
22
+
23
+ def claims(text):
24
+ lines = []
25
+ fence = None
26
+ for line in text.splitlines():
27
+ match = re.match(r'^ {0,3}(`{3,}|~{3,})(.*)$', line)
28
+ if fence:
29
+ if match and match[1][0] == fence[0] and len(match[1]) >= len(fence) and not match[2].strip():
30
+ fence = None
31
+ lines.append('')
32
+ elif match:
33
+ fence = match[1]
34
+ lines.append('')
35
+ else:
36
+ lines.append(line)
37
+ positive = negative = False
38
+ for paragraph in re.split(r'\n\s*\n', '\n'.join(lines)):
39
+ paragraph = normalize(paragraph)
40
+ neg = _pattern(NOSEGMENTATION)
41
+ negative |= bool(neg.search(paragraph))
42
+ positive |= bool(_pattern(SEGMENTATION).search(neg.sub(' ', paragraph)))
43
+ return positive, negative
44
+
45
+
46
+ def evidence(text):
47
+ try:
48
+ tree = ast.parse(text)
49
+ except (SyntaxError, ValueError):
50
+ return False
51
+ aliases = {}
52
+ shadow = set()
53
+ for node in ast.walk(tree):
54
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
55
+ shadow.add(node.name)
56
+ elif isinstance(node, ast.arg):
57
+ shadow.add(node.arg)
58
+ elif isinstance(node, ast.Import):
59
+ for item in node.names:
60
+ aliases[item.asname or item.name.split('.')[0]] = item.name if item.asname else item.name.split('.')[0]
61
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
62
+ for item in node.names:
63
+ aliases[item.asname or item.name] = node.module + '.' + item.name
64
+ bindings = {}
65
+
66
+ def key(node):
67
+ if isinstance(node, ast.Name):
68
+ return node.id
69
+ if isinstance(node, ast.Attribute):
70
+ base = key(node.value)
71
+ return base + '.' + node.attr if base else None
72
+ return None
73
+
74
+ def resolve(node):
75
+ name = key(node)
76
+ if not name or name.split('.')[0] in shadow:
77
+ return ''
78
+ head, *tail = name.split('.')
79
+ return '.'.join([aliases.get(head, ''), *tail]) if head in aliases else ''
80
+
81
+ def construction(node):
82
+ if not isinstance(node, ast.Call):
83
+ return None
84
+ path = resolve(node.func)
85
+ if not path.startswith('mediapipe.'):
86
+ return None
87
+ if path.endswith('.selfie_segmentation.SelfieSegmentation'):
88
+ return 'selfie'
89
+ if path.endswith(('.ImageSegmenter', '.ImageSegmenter.create_from_options')):
90
+ return 'tasks'
91
+ return None
92
+
93
+ # Fixed point supports attribute, annotated, with-target and alias bindings.
94
+ for _ in range(len(list(ast.walk(tree))) + 1):
95
+ changed = False
96
+ for node in ast.walk(tree):
97
+ pairs = []
98
+ if isinstance(node, ast.Assign):
99
+ pairs = [(target, node.value) for target in node.targets]
100
+ elif isinstance(node, ast.AnnAssign) and node.value:
101
+ pairs = [(node.target, node.value)]
102
+ elif isinstance(node, (ast.With, ast.AsyncWith)):
103
+ pairs = [(item.optional_vars, item.context_expr) for item in node.items if item.optional_vars]
104
+ for target, value in pairs:
105
+ kind = construction(value) or bindings.get(key(value))
106
+ target_key = key(target)
107
+ if kind and target_key and bindings.get(target_key) != kind:
108
+ bindings[target_key] = kind
109
+ changed = True
110
+ if not changed:
111
+ break
112
+ for node in ast.walk(tree):
113
+ if construction(node):
114
+ return True
115
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
116
+ kind = construction(node.func.value) or bindings.get(key(node.func.value))
117
+ if kind and node.func.attr in (('segment',) if kind == 'selfie' else ('segment', 'segment_for_video', 'segment_async')):
118
+ return True
119
+ return False
120
+
121
+
122
+ def audit(root, ignore=()):
123
+ root = Path(root)
124
+ if not root.is_dir() or not os.access(root, os.R_OK | os.X_OK) or not root.stat().st_mode & 0o444:
125
+ raise ValueError('invalid or unreadable root')
126
+ positive = negative = production = tests = False
127
+ count = 0
128
+ for directory, dirs, files in os.walk(root, followlinks=False):
129
+ dirs[:] = sorted(d for d in dirs if not (Path(directory) / d).is_symlink())
130
+ for filename in sorted(files):
131
+ path = Path(directory) / filename
132
+ rel = path.relative_to(root)
133
+ if path.is_symlink() or any(fnmatch.fnmatchcase(rel.as_posix(), glob) for glob in ignore):
134
+ continue
135
+ doc = rel.as_posix() == 'README.md' or (path.suffix == '.md' and 'docs' in rel.parts[:-1])
136
+ source = path.suffix == '.py'
137
+ if not (doc or source):
138
+ continue
139
+ try:
140
+ text = path.read_text(encoding='utf-8')
141
+ except (OSError, UnicodeError) as exc:
142
+ raise ValueError('unreadable input: ' + rel.as_posix()) from exc
143
+ count += 1
144
+ if doc:
145
+ pos, neg = claims(text)
146
+ positive |= pos
147
+ negative |= neg
148
+ if source and not set(rel.parts[:-1]) & {'fixtures', 'docs', 'examples'}:
149
+ is_test = 'tests' in rel.parts[:-1] or filename.startswith('test_') or filename.endswith('_test.py')
150
+ if evidence(text):
151
+ if is_test:
152
+ tests = True
153
+ else:
154
+ production = True
155
+ findings = []
156
+ if positive and not production:
157
+ findings.append(dict(rule='documented-segmentation-claim-false', severity='MEDIUM' if tests else 'HIGH', message='Documented capability has no production source evidence.'))
158
+ if negative and production:
159
+ findings.append(dict(rule='documented-no-segmentation-claim-false', severity='HIGH', message='Documented absence conflicts with production source evidence.'))
160
+ return dict(verdict='FAIL' if findings else 'PASS', findings=findings, files_scanned=count)
161
+
162
+
163
+ class Parser(argparse.ArgumentParser):
164
+ def error(self, message):
165
+ self.print_usage(sys.stderr)
166
+ self.exit(1, self.prog + ': error: ' + message + '\n')
167
+
168
+
169
+ def main(argv=None):
170
+ parser = Parser(description=__doc__)
171
+ parser.add_argument('root')
172
+ parser.add_argument('--json', action='store_true')
173
+ parser.add_argument('--verbose', action='store_true')
174
+ parser.add_argument('--ignore', action='append', default=[])
175
+ parser.add_argument('--fail-on', choices=('HIGH', 'MEDIUM'), default='HIGH')
176
+ parser.add_argument('--version', action='version', version=__version__)
177
+ args = parser.parse_args(argv)
178
+ try:
179
+ result = audit(args.root, args.ignore)
180
+ except (ValueError, OSError) as exc:
181
+ print(str(exc), file=sys.stderr)
182
+ return 1
183
+ if args.json:
184
+ print(json.dumps(result))
185
+ else:
186
+ print(result['verdict'])
187
+ for finding in result['findings']:
188
+ print('{severity} {rule}: {message}'.format(**finding))
189
+ if args.verbose:
190
+ print('Files scanned: ' + str(result['files_scanned']))
191
+ return 2 if any(f['severity'] == 'HIGH' or args.fail_on == 'MEDIUM' for f in result['findings']) else 0
@@ -0,0 +1,108 @@
1
+ """Exact documentation templates, ordered by descending length."""
2
+
3
+ SEGMENTATION = (
4
+ 'separates the foreground from the background',
5
+ 'separate the foreground from the background',
6
+ 'segments the foreground from the background',
7
+ 'segment the foreground from the background',
8
+ 'supports background segmentation',
9
+ 'background segmentation support',
10
+ 'support background segmentation',
11
+ 'supports semantic segmentation',
12
+ 'supports instance segmentation',
13
+ 'support instance segmentation',
14
+ 'semantic segmentation support',
15
+ 'instance segmentation support',
16
+ 'support semantic segmentation',
17
+ 'supports selfie segmentation',
18
+ 'segments images into regions',
19
+ 'supports background removal',
20
+ 'supports image segmentation',
21
+ 'selfie segmentation support',
22
+ 'support selfie segmentation',
23
+ 'segment images into regions',
24
+ 'image segmentation support',
25
+ 'segments regions in images',
26
+ 'support image segmentation',
27
+ 'segments objects in images',
28
+ 'support background removal',
29
+ 'background removal support',
30
+ 'segment objects in images',
31
+ 'segments people in images',
32
+ 'segment regions in images',
33
+ 'identifies image segments',
34
+ 'segment people in images',
35
+ 'pixel level segmentation',
36
+ 'background segmentation',
37
+ 'identify image segments',
38
+ 'segments the background',
39
+ 'removes the background',
40
+ 'segment the background',
41
+ 'instance segmentation',
42
+ 'segments video frames',
43
+ 'semantic segmentation',
44
+ 'remove the background',
45
+ 'finds image segments',
46
+ 'segment video frames',
47
+ 'person segmentation',
48
+ 'selfie segmentation',
49
+ 'find image segments',
50
+ 'background removal',
51
+ 'image segmentation',
52
+ 'segments regions',
53
+ 'segments objects',
54
+ 'segments people',
55
+ 'segment objects',
56
+ 'segment regions',
57
+ 'segments images',
58
+ 'segment images',
59
+ 'segment people',
60
+ 'segments image',
61
+ 'segment image',
62
+ )
63
+
64
+ NOSEGMENTATION = (
65
+ 'does not separate the foreground from the background',
66
+ 'does not segment the foreground from the background',
67
+ 'does not support background segmentation',
68
+ 'does not support instance segmentation',
69
+ 'does not support semantic segmentation',
70
+ 'background segmentation not supported',
71
+ 'does not support selfie segmentation',
72
+ 'instance segmentation not supported',
73
+ 'does not support image segmentation',
74
+ 'semantic segmentation not supported',
75
+ 'does not support background removal',
76
+ 'does not segment regions in images',
77
+ 'does not segment objects in images',
78
+ 'does not segment people in images',
79
+ 'selfie segmentation not supported',
80
+ 'image segmentation not supported',
81
+ 'background removal not supported',
82
+ 'does not segment the background',
83
+ 'without background segmentation',
84
+ 'does not remove the background',
85
+ 'without semantic segmentation',
86
+ 'does not support segmentation',
87
+ 'without image segmentation',
88
+ 'no background segmentation',
89
+ 'without background removal',
90
+ 'segmentation not supported',
91
+ 'no instance segmentation',
92
+ 'does not segment objects',
93
+ 'does not segment regions',
94
+ 'no semantic segmentation',
95
+ 'does not segment images',
96
+ 'does not segment people',
97
+ 'never segments objects',
98
+ 'does not segment image',
99
+ 'no selfie segmentation',
100
+ 'no background removal',
101
+ 'no image segmentation',
102
+ 'never segments people',
103
+ 'never segments images',
104
+ 'without segmentation',
105
+ 'does not segment',
106
+ 'no segmentation',
107
+ 'never segments',
108
+ )
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: segmentation-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline audit of documented pixel-region capabilities against Python source
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # segmentation-claim-audit
12
+
13
+ An offline static checker for documentation about pixel-region processing.
14
+ Version 0.1.0 requires Python 3.9 or newer and has no runtime dependencies.
15
+ Source files are parsed with the standard AST module and never executed.
16
+
17
+ Install and run:
18
+
19
+ ```sh
20
+ pip install segmentation-claim-audit
21
+ segmentation-claim-audit . --json
22
+ python3 -m segmentation_claim_audit . --verbose
23
+ segmentation-claim-audit . --ignore 'vendor/*' --fail-on MEDIUM
24
+ segmentation-claim-audit --version
25
+ ```
26
+
27
+ The checker reads the root README.md and Markdown files beneath any docs
28
+ path component. It skips backtick and tilde fences; inline code counts.
29
+ Paragraphs are normalized for case, contractions, hyphens and whitespace.
30
+ Exact bounded templates are matched longest first, with negative spans
31
+ removed before positive matching. The complete vocabulary is in phrases.py.
32
+
33
+ Examples of recognized wording and the two rule identifiers:
34
+
35
+ ```text
36
+ segments images
37
+ does not segment images
38
+ documented-segmentation-claim-false
39
+ documented-no-segmentation-claim-false
40
+ ```
41
+
42
+ Evidence comes from provider-resolved MediaPipe SelfieSegmentation and
43
+ ImageSegmenter constructors, including the tasks create_from_options factory.
44
+ Calls through bound objects are recognized for segment, segment_for_video and
45
+ segment_async as appropriate. Aliases, annotated assignments, attribute
46
+ assignments, context managers and chained calls are handled. Local definitions
47
+ shadow imported names. Construction alone counts; successful runtime output
48
+ is not established.
49
+
50
+ Bare imports, image loading, camera capture, supplied-mask drawing, thresholds,
51
+ face/hand/pose detectors, box detectors, strings and subprocess commands do
52
+ not establish evidence. Invalid Python yields no evidence. Symlinks are
53
+ excluded. Sources within fixtures, docs and examples are excluded; tests,
54
+ test_*.py and *_test.py contribute only test evidence.
55
+
56
+ Each family produces at most one finding. A positive assertion lacking
57
+ production evidence is HIGH, or MEDIUM when only test evidence exists.
58
+ A negative assertion conflicting with production evidence is HIGH. With no
59
+ assertions the result is PASS. Static analysis is module-local, does not follow
60
+ cross-module bindings, and cannot establish runtime correctness or coverage.
61
+ Exact vocabulary can miss paraphrases. This is a review aid.
62
+
63
+ JSON contains verdict, findings (rule, severity, message), and files_scanned.
64
+ Human output includes each finding; --verbose adds the scanned file count.
65
+ A result with findings displays FAIL even when its severity is below the exit
66
+ threshold. Exit 0 means no finding meets the threshold; exit 2 means one does;
67
+ exit 1 means invalid usage or unreadable input. The default threshold is HIGH;
68
+ --fail-on MEDIUM includes both levels. Repeat --ignore for relative POSIX-path
69
+ fnmatch patterns. The scanned count includes eligible documents and Python
70
+ files read, including excluded evidence locations.
71
+
72
+ Development checks:
73
+
74
+ ```sh
75
+ python3 -m unittest discover
76
+ python3 -m build
77
+ ```
78
+
79
+ Distributed under the MIT license.
@@ -0,0 +1,10 @@
1
+ segmentation_claim_audit/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ segmentation_claim_audit/__main__.py,sha256=W9ZI6M_4Op40gY2nrj7UlPotIJeeSozS-vPag6LYJfo,50
3
+ segmentation_claim_audit/audit.py,sha256=hoQQZhVxtUjgwvwuUhCxAoLcrZn2AgSZ_kxxuqN66GI,7777
4
+ segmentation_claim_audit/phrases.py,sha256=Wcfx2ExysD7_YvnE0oEYReNtsuuhqZkBm14ybU0eezQ,3572
5
+ segmentation_claim_audit-0.1.0.dist-info/licenses/LICENSE,sha256=Gc8WsYvemdscK930C7N7nfThBNQZzeLxocU2ANznXgo,1094
6
+ segmentation_claim_audit-0.1.0.dist-info/METADATA,sha256=pjgaaVoxPTT3KBWZtrr-FrJux-DytMvu-GLsNKin_Zc,3308
7
+ segmentation_claim_audit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ segmentation_claim_audit-0.1.0.dist-info/entry_points.txt,sha256=Mo4teEsVFPHwzIzXz8o6CiIBok0BZJwuQlgVQ70OZL4,81
9
+ segmentation_claim_audit-0.1.0.dist-info/top_level.txt,sha256=N-puNgt0OWFJyr-PAZRy8eT3XC0qW_hQH_IOvKTS8JU,25
10
+ segmentation_claim_audit-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
+ segmentation-claim-audit = segmentation_claim_audit.audit:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 segmentation-claim-audit 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
+ segmentation_claim_audit