detection-claim-audit 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.
Files changed (27) hide show
  1. detection_claim_audit-0.1.0/LICENSE +21 -0
  2. detection_claim_audit-0.1.0/MANIFEST.in +2 -0
  3. detection_claim_audit-0.1.0/PKG-INFO +88 -0
  4. detection_claim_audit-0.1.0/README.md +78 -0
  5. detection_claim_audit-0.1.0/detection_claim_audit/__init__.py +1 -0
  6. detection_claim_audit-0.1.0/detection_claim_audit/__main__.py +41 -0
  7. detection_claim_audit-0.1.0/detection_claim_audit/audit.py +219 -0
  8. detection_claim_audit-0.1.0/detection_claim_audit/phrases.py +4 -0
  9. detection_claim_audit-0.1.0/detection_claim_audit.egg-info/PKG-INFO +88 -0
  10. detection_claim_audit-0.1.0/detection_claim_audit.egg-info/SOURCES.txt +25 -0
  11. detection_claim_audit-0.1.0/detection_claim_audit.egg-info/dependency_links.txt +1 -0
  12. detection_claim_audit-0.1.0/detection_claim_audit.egg-info/entry_points.txt +2 -0
  13. detection_claim_audit-0.1.0/detection_claim_audit.egg-info/top_level.txt +1 -0
  14. detection_claim_audit-0.1.0/pyproject.toml +17 -0
  15. detection_claim_audit-0.1.0/setup.cfg +4 -0
  16. detection_claim_audit-0.1.0/tests/__init__.py +0 -0
  17. detection_claim_audit-0.1.0/tests/fixtures/bad/README.md +1 -0
  18. detection_claim_audit-0.1.0/tests/fixtures/bad/app.py +1 -0
  19. detection_claim_audit-0.1.0/tests/fixtures/good/README.md +1 -0
  20. detection_claim_audit-0.1.0/tests/fixtures/good/app.py +2 -0
  21. detection_claim_audit-0.1.0/tests/fixtures/no_claim/README.md +1 -0
  22. detection_claim_audit-0.1.0/tests/fixtures/no_claim/app.py +1 -0
  23. detection_claim_audit-0.1.0/tests/fixtures/no_detection/README.md +1 -0
  24. detection_claim_audit-0.1.0/tests/fixtures/no_detection/app.py +2 -0
  25. detection_claim_audit-0.1.0/tests/fixtures/testonly/README.md +1 -0
  26. detection_claim_audit-0.1.0/tests/fixtures/testonly/tests/test_model.py +2 -0
  27. detection_claim_audit-0.1.0/tests/test_audit.py +165 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 detection-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,2 @@
1
+ include LICENSE
2
+ recursive-include tests *.py *.md
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: detection-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline audit of documented box-level vision assertions
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # Box-level assertion auditor
12
+
13
+ An offline static auditor comparing documented box-level finding promises with
14
+ Python provider evidence. Version 0.1.0; Python 3.9 or newer; no runtime dependencies.
15
+ Source is parsed with AST and never executed.
16
+
17
+ ```sh
18
+ pip install detection-claim-audit
19
+ detection-claim-audit ./project --json
20
+ python3 -m detection_claim_audit ./project --verbose
21
+ detection-claim-audit ./project --ignore 'vendor/*' --fail-on MEDIUM
22
+ detection-claim-audit --version
23
+ ```
24
+
25
+ The root README.md and Markdown files beneath any docs path component supply
26
+ assertions. Backtick and tilde fences are excluded; inline code counts.
27
+ Blank lines separate paragraphs; wrapped lines join. Case, hyphens, whitespace,
28
+ and contracted negatives are normalized. Exact templates use word boundaries,
29
+ with longer templates first and negative spans removed before positive matching.
30
+ The complete template tuples are in phrases.py.
31
+
32
+ Python files supply evidence, except symlinks and files beneath fixtures, docs,
33
+ or examples. Files beneath tests or named test_*.py or *_test.py supply only
34
+ test evidence. Invalid syntax supplies none. Repeat --ignore to exclude relative
35
+ POSIX paths using fnmatch globs. The scanned count includes eligible documents
36
+ and source files after exclusions.
37
+
38
+ Supported providers are ultralytics YOLO, mediapipe tasks ObjectDetector,
39
+ torchvision's nine listed box-model constructors, detectron2 DefaultPredictor,
40
+ and transformers pipeline with the literal task shown below. Imports and aliases
41
+ are resolved within each module; local definitions shadow imported names.
42
+ Construction counts; supported bound calls, annotated assignments, attribute
43
+ assignments, context-manager targets, and chained constructions are recognized.
44
+ YOLO predict and direct calls, mediapipe detect, detect_for_video, detect_async,
45
+ and DefaultPredictor direct calls are supported.
46
+
47
+ ```text
48
+ object-detection
49
+ fasterrcnn_resnet50_fpn
50
+ fasterrcnn_resnet50_fpn_v2
51
+ fasterrcnn_mobilenet_v3_large_fpn
52
+ fasterrcnn_mobilenet_v3_large_320_fpn
53
+ retinanet_resnet50_fpn
54
+ retinanet_resnet50_fpn_v2
55
+ ssd300_vgg16
56
+ ssdlite320_mobilenet_v3_large
57
+ fcos_resnet50_fpn
58
+ ```
59
+
60
+ At most one finding is emitted for each assertion family:
61
+
62
+ ```text
63
+ documented-detection-claim-false: HIGH without production evidence;
64
+ MEDIUM if evidence exists only in tests.
65
+ documented-no-detection-claim-false: HIGH when production evidence contradicts
66
+ a negative assertion.
67
+ ```
68
+
69
+ Without an assertion the result is PASS. HIGH fails by default; --fail-on MEDIUM
70
+ also fails on MEDIUM. JSON contains verdict, findings (rule, severity, message),
71
+ and files_scanned. Human output includes the verdict and each finding;
72
+ --verbose adds the count. Exit codes: 0 for PASS, 2 for FAIL, 1 for invalid or
73
+ unreadable roots and argument errors. --version prints 0.1.0.
74
+
75
+ Limitations: this checks syntax-level fingerprints, not runtime success, model
76
+ weights, accuracy, or whether a constructed model is ever used. Bare imports,
77
+ image loading, camera capture, supplied-box drawing, whole-image classification,
78
+ face/hand/pose processing, pixel segmentation, tracking, strings, shell commands,
79
+ and subprocess helpers supply no evidence. Generic cv2.dnn readNet/forward and
80
+ torch.hub loaded models are intentionally ambiguous and unsupported. Dynamic
81
+ imports, intermodule bindings, and runtime task strings are unsupported.
82
+
83
+ ```sh
84
+ python3 -m unittest discover
85
+ python3 -m build
86
+ ```
87
+
88
+ The source distribution includes the tests and fixtures. Licensed under MIT.
@@ -0,0 +1,78 @@
1
+ # Box-level assertion auditor
2
+
3
+ An offline static auditor comparing documented box-level finding promises with
4
+ Python provider evidence. Version 0.1.0; Python 3.9 or newer; no runtime dependencies.
5
+ Source is parsed with AST and never executed.
6
+
7
+ ```sh
8
+ pip install detection-claim-audit
9
+ detection-claim-audit ./project --json
10
+ python3 -m detection_claim_audit ./project --verbose
11
+ detection-claim-audit ./project --ignore 'vendor/*' --fail-on MEDIUM
12
+ detection-claim-audit --version
13
+ ```
14
+
15
+ The root README.md and Markdown files beneath any docs path component supply
16
+ assertions. Backtick and tilde fences are excluded; inline code counts.
17
+ Blank lines separate paragraphs; wrapped lines join. Case, hyphens, whitespace,
18
+ and contracted negatives are normalized. Exact templates use word boundaries,
19
+ with longer templates first and negative spans removed before positive matching.
20
+ The complete template tuples are in phrases.py.
21
+
22
+ Python files supply evidence, except symlinks and files beneath fixtures, docs,
23
+ or examples. Files beneath tests or named test_*.py or *_test.py supply only
24
+ test evidence. Invalid syntax supplies none. Repeat --ignore to exclude relative
25
+ POSIX paths using fnmatch globs. The scanned count includes eligible documents
26
+ and source files after exclusions.
27
+
28
+ Supported providers are ultralytics YOLO, mediapipe tasks ObjectDetector,
29
+ torchvision's nine listed box-model constructors, detectron2 DefaultPredictor,
30
+ and transformers pipeline with the literal task shown below. Imports and aliases
31
+ are resolved within each module; local definitions shadow imported names.
32
+ Construction counts; supported bound calls, annotated assignments, attribute
33
+ assignments, context-manager targets, and chained constructions are recognized.
34
+ YOLO predict and direct calls, mediapipe detect, detect_for_video, detect_async,
35
+ and DefaultPredictor direct calls are supported.
36
+
37
+ ```text
38
+ object-detection
39
+ fasterrcnn_resnet50_fpn
40
+ fasterrcnn_resnet50_fpn_v2
41
+ fasterrcnn_mobilenet_v3_large_fpn
42
+ fasterrcnn_mobilenet_v3_large_320_fpn
43
+ retinanet_resnet50_fpn
44
+ retinanet_resnet50_fpn_v2
45
+ ssd300_vgg16
46
+ ssdlite320_mobilenet_v3_large
47
+ fcos_resnet50_fpn
48
+ ```
49
+
50
+ At most one finding is emitted for each assertion family:
51
+
52
+ ```text
53
+ documented-detection-claim-false: HIGH without production evidence;
54
+ MEDIUM if evidence exists only in tests.
55
+ documented-no-detection-claim-false: HIGH when production evidence contradicts
56
+ a negative assertion.
57
+ ```
58
+
59
+ Without an assertion the result is PASS. HIGH fails by default; --fail-on MEDIUM
60
+ also fails on MEDIUM. JSON contains verdict, findings (rule, severity, message),
61
+ and files_scanned. Human output includes the verdict and each finding;
62
+ --verbose adds the count. Exit codes: 0 for PASS, 2 for FAIL, 1 for invalid or
63
+ unreadable roots and argument errors. --version prints 0.1.0.
64
+
65
+ Limitations: this checks syntax-level fingerprints, not runtime success, model
66
+ weights, accuracy, or whether a constructed model is ever used. Bare imports,
67
+ image loading, camera capture, supplied-box drawing, whole-image classification,
68
+ face/hand/pose processing, pixel segmentation, tracking, strings, shell commands,
69
+ and subprocess helpers supply no evidence. Generic cv2.dnn readNet/forward and
70
+ torch.hub loaded models are intentionally ambiguous and unsupported. Dynamic
71
+ imports, intermodule bindings, and runtime task strings are unsupported.
72
+
73
+ ```sh
74
+ python3 -m unittest discover
75
+ python3 -m build
76
+ ```
77
+
78
+ The source distribution includes the tests and fixtures. Licensed under MIT.
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,41 @@
1
+ """Command line interface."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ from . import __version__
6
+ from .audit import audit
7
+
8
+
9
+ class Parser(argparse.ArgumentParser):
10
+ def error(self, message):
11
+ self.print_usage(sys.stderr)
12
+ self.exit(1, self.prog + ': error: ' + message + '\n')
13
+
14
+
15
+ def main(argv=None):
16
+ parser = Parser(prog='detection-claim-audit')
17
+ parser.add_argument('root')
18
+ parser.add_argument('--json', action='store_true')
19
+ parser.add_argument('--verbose', action='store_true')
20
+ parser.add_argument('--ignore', action='append', default=[])
21
+ parser.add_argument('--fail-on', choices=['HIGH', 'MEDIUM'], default='HIGH')
22
+ parser.add_argument('--version', action='version', version=__version__)
23
+ args = parser.parse_args(argv)
24
+ try:
25
+ result = audit(args.root, args.ignore, args.fail_on)
26
+ except ValueError as error:
27
+ print(str(error), file=sys.stderr)
28
+ return 1
29
+ if args.json:
30
+ print(json.dumps(result))
31
+ else:
32
+ print(result['verdict'])
33
+ for finding in result['findings']:
34
+ print('{severity} {rule}: {message}'.format(**finding))
35
+ if args.verbose:
36
+ print('Files scanned: {}'.format(result['files_scanned']))
37
+ return 2 if result['verdict'] == 'FAIL' else 0
38
+
39
+
40
+ if __name__ == '__main__':
41
+ sys.exit(main())
@@ -0,0 +1,219 @@
1
+ """Offline documentation assertions and provider-resolved Python evidence."""
2
+ import ast
3
+ import fnmatch
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ from .phrases import DETECTION, NODETECTION
8
+
9
+ MODELS = {'fasterrcnn_resnet50_fpn', 'fasterrcnn_resnet50_fpn_v2',
10
+ 'fasterrcnn_mobilenet_v3_large_fpn', 'fasterrcnn_mobilenet_v3_large_320_fpn',
11
+ 'retinanet_resnet50_fpn', 'retinanet_resnet50_fpn_v2', 'ssd300_vgg16',
12
+ 'ssdlite320_mobilenet_v3_large', 'fcos_resnet50_fpn'}
13
+
14
+
15
+ def normalize(text):
16
+ return ' '.join(text.lower().replace("n't", ' not').replace('-', ' ').split())
17
+
18
+
19
+ def prose(text):
20
+ lines = []
21
+ fence = None
22
+ for line in text.splitlines():
23
+ if fence:
24
+ if re.match(r'^ {0,3}' + re.escape(fence[0]) + '{' + str(fence[1]) + r',}\s*$', line):
25
+ fence = None
26
+ continue
27
+ match = re.match(r'^ {0,3}(`{3,}|~{3,})', line)
28
+ if match:
29
+ fence = (match[1][0], len(match[1]))
30
+ lines.append('')
31
+ else:
32
+ lines.append(line)
33
+ return '\n'.join(lines)
34
+
35
+
36
+ def matches(text, phrases):
37
+ found = []
38
+ for phrase in sorted(phrases, key=len, reverse=True):
39
+ pattern = r'\b' + re.escape(phrase) + r'\b'
40
+ if re.search(pattern, text):
41
+ found.append(phrase)
42
+ text = re.sub(pattern, ' ', text)
43
+ return found, text
44
+
45
+
46
+ def claims(text):
47
+ positive = negative = False
48
+ for paragraph in re.split(r'\n\s*\n', prose(text)):
49
+ negatives, remainder = matches(normalize(paragraph), NODETECTION)
50
+ positives, _ = matches(remainder, DETECTION)
51
+ positive |= bool(positives)
52
+ negative |= bool(negatives)
53
+ return positive, negative
54
+
55
+
56
+ class Evidence(ast.NodeVisitor):
57
+ def __init__(self):
58
+ self.aliases = {}
59
+ self.bound = {}
60
+ self.found = False
61
+
62
+ def path(self, node):
63
+ if isinstance(node, ast.Name):
64
+ return self.aliases.get(node.id, '')
65
+ if isinstance(node, ast.Attribute):
66
+ base = self.path(node.value)
67
+ return base + '.' + node.attr if base else ''
68
+ return ''
69
+
70
+ def key(self, node):
71
+ if isinstance(node, ast.Name):
72
+ return node.id
73
+ if isinstance(node, ast.Attribute):
74
+ base = self.key(node.value)
75
+ return base + '.' + node.attr if base else ''
76
+ return ''
77
+
78
+ def kind(self, node):
79
+ if not isinstance(node, ast.Call):
80
+ return self.bound.get(self.key(node))
81
+ path = self.path(node.func)
82
+ if path.startswith('ultralytics.') and path.endswith('.YOLO'):
83
+ return 'yolo'
84
+ if path.startswith('mediapipe.') and (path.endswith('.ObjectDetector') or path.endswith('.ObjectDetector.create_from_options')):
85
+ return 'mp'
86
+ if path.startswith('detectron2.') and path.endswith('.DefaultPredictor'):
87
+ return 'd2'
88
+ if path.startswith('torchvision.models.detection.') and path.split('.')[-1] in MODELS:
89
+ return 'tv'
90
+ if path == 'transformers.pipeline':
91
+ args = list(node.args[:1]) + [kw.value for kw in node.keywords if kw.arg == 'task']
92
+ if any(isinstance(a, ast.Constant) and a.value == 'object-detection' for a in args):
93
+ return 'pipeline'
94
+ return None
95
+
96
+ def visit_Import(self, node):
97
+ for item in node.names:
98
+ name = item.asname or item.name.split('.')[0]
99
+ self.aliases[name] = item.name if item.asname else name
100
+ self.bound.pop(name, None)
101
+
102
+ def visit_ImportFrom(self, node):
103
+ for item in node.names:
104
+ name = item.asname or item.name
105
+ self.aliases[name] = (node.module + '.' + item.name) if node.module and not node.level else ''
106
+ self.bound.pop(name, None)
107
+
108
+ def bind(self, target, value):
109
+ key = self.key(target)
110
+ if key:
111
+ kind = self.kind(value)
112
+ self.bound.pop(key, None)
113
+ self.aliases.pop(key, None)
114
+ if kind:
115
+ self.bound[key] = kind
116
+ elif isinstance(target, (ast.Tuple, ast.List)):
117
+ for child in target.elts:
118
+ self.bind(child, None)
119
+
120
+ def visit_Assign(self, node):
121
+ self.visit(node.value)
122
+ for target in node.targets:
123
+ self.bind(target, node.value)
124
+
125
+ def visit_AnnAssign(self, node):
126
+ if node.value:
127
+ self.visit(node.value)
128
+ self.bind(node.target, node.value)
129
+
130
+ def visit_With(self, node):
131
+ for item in node.items:
132
+ self.visit(item.context_expr)
133
+ if item.optional_vars:
134
+ self.bind(item.optional_vars, item.context_expr)
135
+ for statement in node.body:
136
+ self.visit(statement)
137
+
138
+ visit_AsyncWith = visit_With
139
+
140
+ def visit_Call(self, node):
141
+ if self.kind(node):
142
+ self.found = True
143
+ kind = self.kind(node.func)
144
+ if kind in {'yolo', 'd2'}:
145
+ self.found = True
146
+ if isinstance(node.func, ast.Attribute):
147
+ kind = self.kind(node.func.value)
148
+ if (kind == 'yolo' and node.func.attr == 'predict') or (kind == 'mp' and node.func.attr in {'detect', 'detect_for_video', 'detect_async'}):
149
+ self.found = True
150
+ self.generic_visit(node)
151
+
152
+ def definition(self, node):
153
+ self.aliases.pop(node.name, None)
154
+ self.bound.pop(node.name, None)
155
+ # Definitions shadow imported providers throughout this module. Function
156
+ # bodies share import resolution but their local bindings do not leak.
157
+ aliases, bound = self.aliases.copy(), self.bound.copy()
158
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
159
+ for arg in node.args.posonlyargs + node.args.args + node.args.kwonlyargs:
160
+ self.aliases.pop(arg.arg, None)
161
+ self.bound.pop(arg.arg, None)
162
+ for statement in node.body:
163
+ self.visit(statement)
164
+ self.aliases, self.bound = aliases, bound
165
+
166
+ visit_FunctionDef = definition
167
+ visit_AsyncFunctionDef = definition
168
+ visit_ClassDef = definition
169
+
170
+
171
+ def evidence(source):
172
+ try:
173
+ tree = ast.parse(source)
174
+ except (SyntaxError, ValueError):
175
+ return False
176
+ visitor = Evidence()
177
+ visitor.visit(tree)
178
+ return visitor.found
179
+
180
+
181
+ def audit(root, ignore=(), fail_on='HIGH'):
182
+ root = Path(root)
183
+ if not root.is_dir() or not os.access(root, os.R_OK | os.X_OK):
184
+ raise ValueError('Root must be a readable directory')
185
+ positive = negative = production = test = False
186
+ count = 0
187
+ def walk_error(error):
188
+ raise ValueError(str(error))
189
+ for directory, dirs, files in os.walk(root, followlinks=False, onerror=walk_error):
190
+ dirs[:] = sorted(d for d in dirs if not Path(directory, d).is_symlink())
191
+ for filename in sorted(files):
192
+ path = Path(directory, filename)
193
+ rel = path.relative_to(root)
194
+ if path.is_symlink() or any(fnmatch.fnmatchcase(rel.as_posix(), pattern) for pattern in ignore):
195
+ continue
196
+ doc = rel.as_posix() == 'README.md' or (path.suffix == '.md' and 'docs' in rel.parts[:-1])
197
+ source = path.suffix == '.py' and not set(rel.parts[:-1]) & {'fixtures', 'docs', 'examples'}
198
+ if not (doc or source):
199
+ continue
200
+ try:
201
+ content = path.read_text(encoding='utf-8')
202
+ except (OSError, UnicodeError) as error:
203
+ raise ValueError(str(error)) from error
204
+ count += 1
205
+ if doc:
206
+ pos, neg = claims(content)
207
+ positive |= pos
208
+ negative |= neg
209
+ if source and evidence(content):
210
+ is_test = 'tests' in rel.parts[:-1] or filename.startswith('test_') or filename.endswith('_test.py')
211
+ test |= is_test
212
+ production |= not is_test
213
+ findings = []
214
+ if positive and not production:
215
+ findings.append(dict(rule='documented-detection-claim-false', severity='MEDIUM' if test else 'HIGH', message='Positive assertion lacks production provider evidence.'))
216
+ if negative and production:
217
+ findings.append(dict(rule='documented-no-detection-claim-false', severity='HIGH', message='Negative assertion conflicts with production provider evidence.'))
218
+ failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
219
+ return dict(verdict='FAIL' if failed else 'PASS', findings=findings, files_scanned=count)
@@ -0,0 +1,4 @@
1
+ """Exact assertion templates, ordered by descending length."""
2
+ DETECTION = ('draws bounding boxes around objects', 'supports real time object detection', 'detects objects in video frames', 'detect objects in video frames', 'bounding boxes around objects', 'detects objects in real time', 'identifies objects in images', 'supports instance detection', 'identify objects in images', 'instance detection support', 'real time object detection', 'support instance detection', 'detects objects in frames', 'detects objects in images', 'locates objects in images', 'performs object detection', 'supports object detection', 'detect objects in frames', 'detect objects in images', 'detects multiple objects', 'detects objects in video', 'detects people in images', 'locate objects in images', 'object detection support', 'perform object detection', 'support object detection', 'detect multiple objects', 'detect objects in video', 'detect people in images', 'finds objects in images', 'object detection models', 'bounding box detection', 'detects bounding boxes', 'find objects in images', 'object detection model', 'detect bounding boxes', 'detection of objects', 'object localization', 'real time detection', 'localizes objects', 'localize objects', 'object detection', 'object detectors', 'detects objects', 'object detector', 'detect objects', 'detects object', 'detect object')
3
+
4
+ NODETECTION = ('does not detect objects in video frames', 'does not identify objects in images', 'does not support instance detection', 'does not detect objects in frames', 'does not detect objects in images', 'does not locate objects in images', 'does not perform object detection', 'does not support object detection', 'does not detect objects in video', 'does not detect people in images', 'instance detection not supported', 'does not find objects in images', 'does not detect bounding boxes', 'object detection not available', 'object detection not supported', 'does not draw bounding boxes', 'does not support detection', 'without object detection', 'detection not supported', 'does not detect objects', 'without object detector', 'does not detect object', 'without bounding boxes', 'never detects objects', 'never detects object', 'no object detection', 'no object detector', 'no bounding boxes', 'without detection', 'does not detect', 'never detects', 'no detection')
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: detection-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline audit of documented box-level vision assertions
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # Box-level assertion auditor
12
+
13
+ An offline static auditor comparing documented box-level finding promises with
14
+ Python provider evidence. Version 0.1.0; Python 3.9 or newer; no runtime dependencies.
15
+ Source is parsed with AST and never executed.
16
+
17
+ ```sh
18
+ pip install detection-claim-audit
19
+ detection-claim-audit ./project --json
20
+ python3 -m detection_claim_audit ./project --verbose
21
+ detection-claim-audit ./project --ignore 'vendor/*' --fail-on MEDIUM
22
+ detection-claim-audit --version
23
+ ```
24
+
25
+ The root README.md and Markdown files beneath any docs path component supply
26
+ assertions. Backtick and tilde fences are excluded; inline code counts.
27
+ Blank lines separate paragraphs; wrapped lines join. Case, hyphens, whitespace,
28
+ and contracted negatives are normalized. Exact templates use word boundaries,
29
+ with longer templates first and negative spans removed before positive matching.
30
+ The complete template tuples are in phrases.py.
31
+
32
+ Python files supply evidence, except symlinks and files beneath fixtures, docs,
33
+ or examples. Files beneath tests or named test_*.py or *_test.py supply only
34
+ test evidence. Invalid syntax supplies none. Repeat --ignore to exclude relative
35
+ POSIX paths using fnmatch globs. The scanned count includes eligible documents
36
+ and source files after exclusions.
37
+
38
+ Supported providers are ultralytics YOLO, mediapipe tasks ObjectDetector,
39
+ torchvision's nine listed box-model constructors, detectron2 DefaultPredictor,
40
+ and transformers pipeline with the literal task shown below. Imports and aliases
41
+ are resolved within each module; local definitions shadow imported names.
42
+ Construction counts; supported bound calls, annotated assignments, attribute
43
+ assignments, context-manager targets, and chained constructions are recognized.
44
+ YOLO predict and direct calls, mediapipe detect, detect_for_video, detect_async,
45
+ and DefaultPredictor direct calls are supported.
46
+
47
+ ```text
48
+ object-detection
49
+ fasterrcnn_resnet50_fpn
50
+ fasterrcnn_resnet50_fpn_v2
51
+ fasterrcnn_mobilenet_v3_large_fpn
52
+ fasterrcnn_mobilenet_v3_large_320_fpn
53
+ retinanet_resnet50_fpn
54
+ retinanet_resnet50_fpn_v2
55
+ ssd300_vgg16
56
+ ssdlite320_mobilenet_v3_large
57
+ fcos_resnet50_fpn
58
+ ```
59
+
60
+ At most one finding is emitted for each assertion family:
61
+
62
+ ```text
63
+ documented-detection-claim-false: HIGH without production evidence;
64
+ MEDIUM if evidence exists only in tests.
65
+ documented-no-detection-claim-false: HIGH when production evidence contradicts
66
+ a negative assertion.
67
+ ```
68
+
69
+ Without an assertion the result is PASS. HIGH fails by default; --fail-on MEDIUM
70
+ also fails on MEDIUM. JSON contains verdict, findings (rule, severity, message),
71
+ and files_scanned. Human output includes the verdict and each finding;
72
+ --verbose adds the count. Exit codes: 0 for PASS, 2 for FAIL, 1 for invalid or
73
+ unreadable roots and argument errors. --version prints 0.1.0.
74
+
75
+ Limitations: this checks syntax-level fingerprints, not runtime success, model
76
+ weights, accuracy, or whether a constructed model is ever used. Bare imports,
77
+ image loading, camera capture, supplied-box drawing, whole-image classification,
78
+ face/hand/pose processing, pixel segmentation, tracking, strings, shell commands,
79
+ and subprocess helpers supply no evidence. Generic cv2.dnn readNet/forward and
80
+ torch.hub loaded models are intentionally ambiguous and unsupported. Dynamic
81
+ imports, intermodule bindings, and runtime task strings are unsupported.
82
+
83
+ ```sh
84
+ python3 -m unittest discover
85
+ python3 -m build
86
+ ```
87
+
88
+ The source distribution includes the tests and fixtures. Licensed under MIT.
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ detection_claim_audit/__init__.py
6
+ detection_claim_audit/__main__.py
7
+ detection_claim_audit/audit.py
8
+ detection_claim_audit/phrases.py
9
+ detection_claim_audit.egg-info/PKG-INFO
10
+ detection_claim_audit.egg-info/SOURCES.txt
11
+ detection_claim_audit.egg-info/dependency_links.txt
12
+ detection_claim_audit.egg-info/entry_points.txt
13
+ detection_claim_audit.egg-info/top_level.txt
14
+ tests/__init__.py
15
+ tests/test_audit.py
16
+ tests/fixtures/bad/README.md
17
+ tests/fixtures/bad/app.py
18
+ tests/fixtures/good/README.md
19
+ tests/fixtures/good/app.py
20
+ tests/fixtures/no_claim/README.md
21
+ tests/fixtures/no_claim/app.py
22
+ tests/fixtures/no_detection/README.md
23
+ tests/fixtures/no_detection/app.py
24
+ tests/fixtures/testonly/README.md
25
+ tests/fixtures/testonly/tests/test_model.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ detection-claim-audit = detection_claim_audit.__main__:main
@@ -0,0 +1 @@
1
+ detection_claim_audit
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "detection-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline audit of documented box-level vision assertions"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+
13
+ [project.scripts]
14
+ detection-claim-audit = "detection_claim_audit.__main__:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["detection_claim_audit*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1 @@
1
+ detects objects
@@ -0,0 +1 @@
1
+ import ultralytics
@@ -0,0 +1 @@
1
+ detects objects
@@ -0,0 +1,2 @@
1
+ from ultralytics import YOLO
2
+ model=YOLO("weights")
@@ -0,0 +1 @@
1
+ A simple utility.
@@ -0,0 +1 @@
1
+ import ultralytics
@@ -0,0 +1 @@
1
+ no object detection
@@ -0,0 +1,2 @@
1
+ from ultralytics import YOLO
2
+ model=YOLO("weights")
@@ -0,0 +1 @@
1
+ detects objects
@@ -0,0 +1,2 @@
1
+ from ultralytics import YOLO
2
+ model=YOLO("weights")
@@ -0,0 +1,165 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from detection_claim_audit.audit import audit, claims, evidence, matches
8
+ from detection_claim_audit.phrases import DETECTION, NODETECTION
9
+ from detection_claim_audit.__main__ import main
10
+
11
+ FIXTURES = Path(__file__).parent / 'fixtures'
12
+
13
+
14
+ class ClaimsTests(unittest.TestCase):
15
+ def test_counts_and_sort(self):
16
+ self.assertEqual(len(DETECTION), 48)
17
+ self.assertEqual(len(NODETECTION), 32)
18
+ for values in (DETECTION, NODETECTION):
19
+ self.assertEqual(len(values), len(set(values)))
20
+ self.assertEqual(list(values), sorted(values, key=len, reverse=True))
21
+
22
+ def test_fences(self):
23
+ for fence in ('```', '~~~', ' ````'):
24
+ self.assertEqual(claims(fence+'\ndetects objects\n'+fence), (False, False))
25
+
26
+ def test_inline(self):
27
+ self.assertEqual(claims('`detects objects`'), (True, False))
28
+
29
+ def test_normalization(self):
30
+ self.assertEqual(claims("Doesn't detect objects in images"), (False, True))
31
+ self.assertEqual(claims('REAL-TIME OBJECT\nDETECTION'), (True, False))
32
+ self.assertEqual(claims('detects\n\nobjects'), (False, False))
33
+
34
+ def test_longest_and_boundaries(self):
35
+ self.assertEqual(matches('detects objects in images', reversed(DETECTION))[0], ['detects objects in images'])
36
+ self.assertEqual(claims('predetect objectsx'), (False, False))
37
+
38
+
39
+ POSITIVES = [
40
+ 'import ultralytics\nultralytics.YOLO("x")',
41
+ 'import ultralytics as u\nu.YOLO("x")',
42
+ 'from ultralytics import YOLO as Y\nY("x")',
43
+ 'from ultralytics import YOLO\nwith YOLO("x") as m:\n m.predict(x)',
44
+ 'from ultralytics import YOLO\nself.model=YOLO("x")\nself.model(x)',
45
+ 'from ultralytics import YOLO\nYOLO("x").predict(x)',
46
+ 'from ultralytics import YOLO\nm: object=YOLO("x")\nm.predict(x)',
47
+ 'from ultralytics import YOLO\nm=YOLO("x")\nm(x)',
48
+ 'import mediapipe as mp\nmp.tasks.vision.ObjectDetector.create_from_options(options)',
49
+ 'from mediapipe.tasks.vision import ObjectDetector as O\nO.create_from_options(options)',
50
+ 'from mediapipe.tasks.vision import ObjectDetector\nObjectDetector(options)',
51
+ 'import torchvision as tv\ntv.models.detection.fasterrcnn_resnet50_fpn()',
52
+ 'from torchvision.models.detection import ssd300_vgg16 as model\nmodel()',
53
+ 'from detectron2.engine import DefaultPredictor as D\np=D(cfg)\np(image)',
54
+ 'import detectron2.engine as e\ne.DefaultPredictor(cfg)',
55
+ 'from transformers import pipeline as p\np("object-detection")',
56
+ 'import transformers as t\nt.pipeline(task="object-detection")',
57
+ ]
58
+ for method in ('detect','detect_for_video','detect_async'):
59
+ POSITIVES.append('from mediapipe.tasks.vision import ObjectDetector\nm=ObjectDetector.create_from_options(o)\nm.'+method+'(x)')
60
+ NEGATIVES = [
61
+ 'import ultralytics', 'import cv2\ncv2.imread("x")',
62
+ 'from PIL import Image\nImage.open("x")', 'import cv2\ncv2.VideoCapture(0)',
63
+ 'import cv2\ncv2.rectangle(image, a, b, c)',
64
+ 'from torchvision.models import resnet50\nresnet50()',
65
+ 'import face_recognition\nface_recognition.face_locations(x)',
66
+ 'import mediapipe as mp\nmp.solutions.face_detection.FaceDetection()',
67
+ 'import mediapipe as mp\nmp.solutions.hands.Hands()',
68
+ 'import mediapipe as mp\nmp.solutions.pose.Pose()',
69
+ 'import mediapipe as mp\nmp.tasks.vision.PoseLandmarker.create_from_options(o)',
70
+ 'import mediapipe as mp\nmp.solutions.selfie_segmentation.SelfieSegmentation()',
71
+ 'import mediapipe as mp\nmp.tasks.vision.ImageSegmenter.create_from_options(o)',
72
+ 'model.track(x)', 'from deep_sort import DeepSORT\nDeepSORT()',
73
+ 'import cv2\nn=cv2.dnn.readNet("x")\nn.forward()',
74
+ 'import torch\ntorch.hub.load("ultralytics/yolov5", "yolov5s")',
75
+ 'from ultralytics import YOLO\ndef YOLO(x): return x\nYOLO("x")',
76
+ 'from mediapipe.tasks.vision import ObjectDetector\nclass ObjectDetector: pass\nObjectDetector()',
77
+ 'from detectron2.engine import DefaultPredictor\ndef DefaultPredictor(x): return x\nDefaultPredictor(x)',
78
+ 'from transformers import pipeline\ndef pipeline(x): return x\npipeline("object-detection")',
79
+ 'from transformers import pipeline\npipeline("image-classification")',
80
+ 'predict(x)\ndetect(x)', 'x="object detection"',
81
+ 'import subprocess\nsubprocess.run(["yolo", "detect"])', 'not valid python !',
82
+ 'from other import YOLO\nYOLO(x)',
83
+ 'from ultralytics import YOLO\nYOLO=lambda x:x\nYOLO(x)',
84
+ ]
85
+
86
+
87
+ class EvidenceTests(unittest.TestCase):
88
+ def test_tracking_method_is_not_bound_evidence(self):
89
+ from detection_claim_audit.audit import Evidence
90
+ import ast
91
+ v=Evidence(); v.bound['m']='yolo'
92
+ v.visit(ast.parse('m.track(x)'))
93
+ self.assertFalse(v.found)
94
+
95
+
96
+ class IntegrationTests(unittest.TestCase):
97
+ def cli(self, *args):
98
+ out, err = io.StringIO(), io.StringIO()
99
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
100
+ try:
101
+ status=main(list(map(str,args)))
102
+ except SystemExit as e:
103
+ status=e.code
104
+ return status,out.getvalue(),err.getvalue()
105
+
106
+ def test_fixtures(self):
107
+ for fixture, status, severity, rule in [
108
+ ('good',0,None,None), ('no_claim',0,None,None),
109
+ ('bad',2,'HIGH','documented-detection-claim-false'),
110
+ ('testonly',0,'MEDIUM','documented-detection-claim-false'),
111
+ ('no_detection',2,'HIGH','documented-no-detection-claim-false')]:
112
+ with self.subTest(fixture=fixture):
113
+ code,out,_=self.cli(FIXTURES/fixture,'--json')
114
+ self.assertEqual(code,status)
115
+ result=json.loads(out)
116
+ self.assertEqual(set(result),{'verdict','findings','files_scanned'})
117
+ self.assertEqual(result['verdict'],'FAIL' if status==2 else 'PASS')
118
+ self.assertEqual(len(result['findings']),int(severity is not None))
119
+ if severity:
120
+ self.assertEqual(result['findings'][0]['severity'],severity)
121
+ self.assertEqual(result['findings'][0]['rule'],rule)
122
+ self.assertEqual(set(result['findings'][0]),{'rule','severity','message'})
123
+ self.assertEqual(self.cli(FIXTURES/'testonly','--fail-on','MEDIUM')[0],2)
124
+
125
+ def test_ignore_and_verbose(self):
126
+ code,out,_=self.cli(FIXTURES/'bad','--ignore','README.md','--verbose')
127
+ self.assertEqual(code,0)
128
+ self.assertIn('Files scanned: 1',out)
129
+ self.assertEqual(self.cli(FIXTURES/'good','--ignore','*.py')[0],2)
130
+
131
+ def test_version_errors(self):
132
+ self.assertEqual(self.cli('--version')[:2],(0,'0.1.0\n'))
133
+ for args in [[],['--unknown'],['/nonexistent-root'],[str(FIXTURES/'bad'),'--fail-on','LOW']]:
134
+ self.assertEqual(self.cli(*args)[0],1)
135
+
136
+ def test_exclusions_and_docs(self):
137
+ with tempfile.TemporaryDirectory() as d:
138
+ root=Path(d); (root/'README.md').write_text('detects objects')
139
+ for component in ['docs','examples','fixtures']:
140
+ folder=root/component;folder.mkdir();(folder/'source.py').write_text(POSITIVES[0])
141
+ (root/'linked.py').symlink_to(root/'docs/source.py')
142
+ (root/'linked_dir').symlink_to(root/'docs',target_is_directory=True)
143
+ self.assertEqual(audit(root)['findings'][0]['severity'],'HIGH')
144
+ (root/'README.md').write_text('Nothing promised.')
145
+ (root/'docs/note.md').write_text('detects objects')
146
+ self.assertEqual(audit(root)['verdict'],'FAIL')
147
+
148
+ def test_self_audit(self):
149
+ self.assertEqual(audit(Path(__file__).resolve().parents[1])['verdict'],'PASS')
150
+
151
+
152
+ def add_test(cls, name, function, value, expected):
153
+ def test(self):
154
+ self.assertEqual(function(value), expected)
155
+ setattr(cls, name, test)
156
+
157
+
158
+ for i,phrase in enumerate(DETECTION):
159
+ add_test(ClaimsTests,'test_positive_%02d'%i,claims,phrase,(True,False))
160
+ for i,phrase in enumerate(NODETECTION):
161
+ add_test(ClaimsTests,'test_negative_%02d'%i,claims,phrase,(False,True))
162
+ for i,source in enumerate(POSITIVES):
163
+ add_test(EvidenceTests,'test_provider_%02d'%i,evidence,source,True)
164
+ for i,source in enumerate(NEGATIVES):
165
+ add_test(EvidenceTests,'test_nonprovider_%02d'%i,evidence,source,False)