classification-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. classification_claim_audit-0.1.0/LICENSE +21 -0
  2. classification_claim_audit-0.1.0/MANIFEST.in +2 -0
  3. classification_claim_audit-0.1.0/PKG-INFO +65 -0
  4. classification_claim_audit-0.1.0/README.md +55 -0
  5. classification_claim_audit-0.1.0/classification_claim_audit/__init__.py +1 -0
  6. classification_claim_audit-0.1.0/classification_claim_audit/__main__.py +41 -0
  7. classification_claim_audit-0.1.0/classification_claim_audit/audit.py +210 -0
  8. classification_claim_audit-0.1.0/classification_claim_audit/phrases.py +95 -0
  9. classification_claim_audit-0.1.0/classification_claim_audit.egg-info/PKG-INFO +65 -0
  10. classification_claim_audit-0.1.0/classification_claim_audit.egg-info/SOURCES.txt +25 -0
  11. classification_claim_audit-0.1.0/classification_claim_audit.egg-info/dependency_links.txt +1 -0
  12. classification_claim_audit-0.1.0/classification_claim_audit.egg-info/entry_points.txt +2 -0
  13. classification_claim_audit-0.1.0/classification_claim_audit.egg-info/top_level.txt +1 -0
  14. classification_claim_audit-0.1.0/pyproject.toml +17 -0
  15. classification_claim_audit-0.1.0/setup.cfg +4 -0
  16. classification_claim_audit-0.1.0/tests/__init__.py +0 -0
  17. classification_claim_audit-0.1.0/tests/fixtures/bad/README.md +1 -0
  18. classification_claim_audit-0.1.0/tests/fixtures/bad/app.py +1 -0
  19. classification_claim_audit-0.1.0/tests/fixtures/good/README.md +1 -0
  20. classification_claim_audit-0.1.0/tests/fixtures/good/app.py +2 -0
  21. classification_claim_audit-0.1.0/tests/fixtures/no_claim/README.md +1 -0
  22. classification_claim_audit-0.1.0/tests/fixtures/no_claim/app.py +2 -0
  23. classification_claim_audit-0.1.0/tests/fixtures/no_classification/README.md +1 -0
  24. classification_claim_audit-0.1.0/tests/fixtures/no_classification/app.py +2 -0
  25. classification_claim_audit-0.1.0/tests/fixtures/testonly/README.md +1 -0
  26. classification_claim_audit-0.1.0/tests/fixtures/testonly/test_model.py +2 -0
  27. classification_claim_audit-0.1.0/tests/test_audit.py +127 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 classification-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,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: classification-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline audit of documented whole-picture labelling 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
+ # Whole-picture labelling audit
12
+
13
+ Offline static checking of documented whole-picture labelling promises against Python provider evidence. Python 3.9 or newer; MIT licensed; no runtime dependencies. Source is parsed and never executed.
14
+
15
+ ```sh
16
+ pip install classification-claim-audit
17
+ classification-claim-audit ./project --json
18
+ python3 -m classification_claim_audit ./project --verbose
19
+ classification-claim-audit ./project --ignore 'vendor/*' --fail-on MEDIUM
20
+ classification-claim-audit --version
21
+ ```
22
+
23
+ Reads root README.md and Markdown files beneath any docs path component. Backtick and tilde fenced blocks with up to three leading spaces are excluded; inline code counts. Blank lines separate paragraphs, wrapped lines join, case is folded, contractions expand, hyphens become spaces, and whitespace collapses. Exact templates match word boundaries, longest first. Negative spans are removed before positive matching.
24
+
25
+ Evidence requires an alias-resolved call in a single module. Local definitions shadow imports. Construction alone counts for the first three providers; the fourth requires the literal task shown:
26
+
27
+ ```text
28
+ torchvision.models: listed constructors, including resnet18, vgg16, efficientnet_b0
29
+ timm.create_model
30
+ keras.applications / tensorflow.keras.applications: listed constructors, including ResNet50, MobileNetV2
31
+ transformers.pipeline("image-classification")
32
+ transformers.pipeline(task="image-classification")
33
+ ```
34
+
35
+ Complete constructor sets and wording templates are in the package modules. Bare imports, picture opening, camera capture, drawing supplied boxes, object finding, pixel segmentation, face/hand/pose detection, OCR, barcode decoding, tracking, generic tabular estimators, and bare neural heads do not count. Neither do strings, unbound calls, subprocess helpers, unrelated providers, or syntax-invalid files.
36
+
37
+ Symlinked files and directories are excluded. Python files under fixtures, docs, and examples are excluded. Files under tests or named test_*.py or *_test.py provide only test evidence. Repeatable ignore globs use fnmatch on relative POSIX paths.
38
+
39
+ At most one finding appears per family:
40
+
41
+ ```text
42
+ documented-classification-claim-false
43
+ HIGH: positive promise lacks production evidence
44
+ MEDIUM: evidence exists only in tests
45
+ documented-no-classification-claim-false
46
+ HIGH: negative promise conflicts with production evidence
47
+ ```
48
+
49
+ No matching promise means PASS regardless of source. The default threshold is HIGH; MEDIUM also fails on test-only evidence. Exits are 0 for PASS, 2 for FAIL, and 1 for invalid or unreadable roots and usage errors. Human output includes verdict and findings; verbose output adds the scanned count. JSON includes verdict, findings (rule, severity, message), and files_scanned.
50
+
51
+ Static construction evidence cannot establish runtime success, prediction quality, weights, or actual use. Dynamic imports, cross-module flow, custom implementations, text-to-picture similarity, and runtime model names are outside scope. These operations do not count:
52
+
53
+ ```text
54
+ CLIP / open_clip zero-shot matching
55
+ cv2.dnn.readNet / forward
56
+ torch.hub.load
57
+ torchvision.models.get_model("resnet18")
58
+ ```
59
+
60
+ Develop and build with:
61
+
62
+ ```sh
63
+ python3 -m unittest discover
64
+ python3 -m build
65
+ ```
@@ -0,0 +1,55 @@
1
+ # Whole-picture labelling audit
2
+
3
+ Offline static checking of documented whole-picture labelling promises against Python provider evidence. Python 3.9 or newer; MIT licensed; no runtime dependencies. Source is parsed and never executed.
4
+
5
+ ```sh
6
+ pip install classification-claim-audit
7
+ classification-claim-audit ./project --json
8
+ python3 -m classification_claim_audit ./project --verbose
9
+ classification-claim-audit ./project --ignore 'vendor/*' --fail-on MEDIUM
10
+ classification-claim-audit --version
11
+ ```
12
+
13
+ Reads root README.md and Markdown files beneath any docs path component. Backtick and tilde fenced blocks with up to three leading spaces are excluded; inline code counts. Blank lines separate paragraphs, wrapped lines join, case is folded, contractions expand, hyphens become spaces, and whitespace collapses. Exact templates match word boundaries, longest first. Negative spans are removed before positive matching.
14
+
15
+ Evidence requires an alias-resolved call in a single module. Local definitions shadow imports. Construction alone counts for the first three providers; the fourth requires the literal task shown:
16
+
17
+ ```text
18
+ torchvision.models: listed constructors, including resnet18, vgg16, efficientnet_b0
19
+ timm.create_model
20
+ keras.applications / tensorflow.keras.applications: listed constructors, including ResNet50, MobileNetV2
21
+ transformers.pipeline("image-classification")
22
+ transformers.pipeline(task="image-classification")
23
+ ```
24
+
25
+ Complete constructor sets and wording templates are in the package modules. Bare imports, picture opening, camera capture, drawing supplied boxes, object finding, pixel segmentation, face/hand/pose detection, OCR, barcode decoding, tracking, generic tabular estimators, and bare neural heads do not count. Neither do strings, unbound calls, subprocess helpers, unrelated providers, or syntax-invalid files.
26
+
27
+ Symlinked files and directories are excluded. Python files under fixtures, docs, and examples are excluded. Files under tests or named test_*.py or *_test.py provide only test evidence. Repeatable ignore globs use fnmatch on relative POSIX paths.
28
+
29
+ At most one finding appears per family:
30
+
31
+ ```text
32
+ documented-classification-claim-false
33
+ HIGH: positive promise lacks production evidence
34
+ MEDIUM: evidence exists only in tests
35
+ documented-no-classification-claim-false
36
+ HIGH: negative promise conflicts with production evidence
37
+ ```
38
+
39
+ No matching promise means PASS regardless of source. The default threshold is HIGH; MEDIUM also fails on test-only evidence. Exits are 0 for PASS, 2 for FAIL, and 1 for invalid or unreadable roots and usage errors. Human output includes verdict and findings; verbose output adds the scanned count. JSON includes verdict, findings (rule, severity, message), and files_scanned.
40
+
41
+ Static construction evidence cannot establish runtime success, prediction quality, weights, or actual use. Dynamic imports, cross-module flow, custom implementations, text-to-picture similarity, and runtime model names are outside scope. These operations do not count:
42
+
43
+ ```text
44
+ CLIP / open_clip zero-shot matching
45
+ cv2.dnn.readNet / forward
46
+ torch.hub.load
47
+ torchvision.models.get_model("resnet18")
48
+ ```
49
+
50
+ Develop and build with:
51
+
52
+ ```sh
53
+ python3 -m unittest discover
54
+ python3 -m build
55
+ ```
@@ -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='classification-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,210 @@
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 CLASSIFICATION, NOCLASSIFICATION
8
+
9
+ MODELS = {'densenet161', 'efficientnet_v2_m', 'wide_resnet101_2', 'alexnet', 'efficientnet_b5', 'resnet34', 'vit_l_32', 'vgg19', 'swin_v2_s', 'vgg11', 'googlenet', 'densenet121', 'efficientnet_b3', 'wide_resnet50_2', 'efficientnet_b6', 'resnext50_32x4d', 'resnet152', 'vgg13', 'swin_b', 'vgg13_bn', 'vit_h_14', 'densenet201', 'efficientnet_v2_l', 'efficientnet_b4', 'resnet18', 'resnext101_32x8d', 'swin_s', 'convnext_tiny', 'convnext_base', 'vgg16', 'swin_v2_t', 'efficientnet_b7', 'efficientnet_v2_s', 'resnet101', 'convnext_small', 'swin_t', 'swin_v2_b', 'inception_v3', 'efficientnet_b0', 'mobilenet_v3_large', 'efficientnet_b1', 'vgg19_bn', 'mobilenet_v3_small', 'efficientnet_b2', 'mobilenet_v2', 'resnext101_64x4d', 'convnext_large', 'vit_b_32', 'vgg11_bn', 'resnet50', 'densenet169', 'vit_b_16', 'vit_l_16', 'vgg16_bn'}
10
+ KERAS_MODELS = {'DenseNet169', 'ResNet50V2', 'EfficientNetB5', 'EfficientNetB0', 'DenseNet201', 'InceptionResNetV2', 'DenseNet121', 'ResNet101', 'MobileNet', 'EfficientNetB3', 'Xception', 'EfficientNetB6', 'InceptionV3', 'EfficientNetB1', 'VGG16', 'ResNet152V2', 'EfficientNetB7', 'MobileNetV3Small', 'VGG19', 'ResNet101V2', 'NASNetLarge', 'MobileNetV3Large', 'MobileNetV2', 'NASNetMobile', 'EfficientNetB4', 'EfficientNetB2', 'ResNet50', 'ResNet152'}
11
+
12
+ def normalize(text):
13
+ return ' '.join(text.lower().replace("n't", ' not').replace('-', ' ').split())
14
+
15
+
16
+ def prose(text):
17
+ lines = []
18
+ fence = None
19
+ for line in text.splitlines():
20
+ if fence:
21
+ if re.match(r'^ {0,3}' + re.escape(fence[0]) + '{' + str(fence[1]) + r',}\s*$', line):
22
+ fence = None
23
+ continue
24
+ match = re.match(r'^ {0,3}(`{3,}|~{3,})', line)
25
+ if match:
26
+ fence = (match[1][0], len(match[1]))
27
+ lines.append('')
28
+ else:
29
+ lines.append(line)
30
+ return '\n'.join(lines)
31
+
32
+
33
+ def matches(text, phrases):
34
+ found = []
35
+ for phrase in sorted(phrases, key=len, reverse=True):
36
+ pattern = r'\b' + re.escape(phrase) + r'\b'
37
+ if re.search(pattern, text):
38
+ found.append(phrase)
39
+ text = re.sub(pattern, ' ', text)
40
+ return found, text
41
+
42
+
43
+ def claims(text):
44
+ positive = negative = False
45
+ for paragraph in re.split(r'\n\s*\n', prose(text)):
46
+ negatives, remainder = matches(normalize(paragraph), NOCLASSIFICATION)
47
+ positives, _ = matches(remainder, CLASSIFICATION)
48
+ positive |= bool(positives)
49
+ negative |= bool(negatives)
50
+ return positive, negative
51
+
52
+
53
+ class Evidence(ast.NodeVisitor):
54
+ def __init__(self):
55
+ self.aliases = {}
56
+ self.bound = {}
57
+ self.found = False
58
+
59
+ def path(self, node):
60
+ if isinstance(node, ast.Name):
61
+ return self.aliases.get(node.id, '')
62
+ if isinstance(node, ast.Attribute):
63
+ base = self.path(node.value)
64
+ return base + '.' + node.attr if base else ''
65
+ return ''
66
+
67
+ def key(self, node):
68
+ if isinstance(node, ast.Name):
69
+ return node.id
70
+ if isinstance(node, ast.Attribute):
71
+ base = self.key(node.value)
72
+ return base + '.' + node.attr if base else ''
73
+ return ''
74
+
75
+ def kind(self, node):
76
+ if not isinstance(node, ast.Call):
77
+ return None
78
+ path = self.path(node.func)
79
+ parts = path.split('.')
80
+ if path.startswith('torchvision.models.') and parts[-1] in MODELS:
81
+ return 'classifier'
82
+ if path == 'timm.create_model':
83
+ return 'classifier'
84
+ if (path.startswith('keras.') or path.startswith('tensorflow.keras.')) and 'applications' in parts and parts[-1] in KERAS_MODELS:
85
+ return 'classifier'
86
+ if path == 'transformers.pipeline':
87
+ args = list(node.args[:1]) + [kw.value for kw in node.keywords if kw.arg == 'task']
88
+ if any(isinstance(a, ast.Constant) and a.value == 'image-classification' for a in args):
89
+ return 'classifier'
90
+ return None
91
+
92
+ def visit_Import(self, node):
93
+ for item in node.names:
94
+ name = item.asname or item.name.split('.')[0]
95
+ self.aliases[name] = item.name if item.asname else name
96
+ self.bound.pop(name, None)
97
+
98
+ def visit_ImportFrom(self, node):
99
+ for item in node.names:
100
+ name = item.asname or item.name
101
+ self.aliases[name] = (node.module + '.' + item.name) if node.module and not node.level else ''
102
+ self.bound.pop(name, None)
103
+
104
+ def bind(self, target, value):
105
+ key = self.key(target)
106
+ if key:
107
+ kind = self.kind(value)
108
+ self.bound.pop(key, None)
109
+ self.aliases.pop(key, None)
110
+ if kind:
111
+ self.bound[key] = kind
112
+ elif isinstance(target, (ast.Tuple, ast.List)):
113
+ for child in target.elts:
114
+ self.bind(child, None)
115
+
116
+ def visit_Assign(self, node):
117
+ self.visit(node.value)
118
+ for target in node.targets:
119
+ self.bind(target, node.value)
120
+
121
+ def visit_AnnAssign(self, node):
122
+ if node.value:
123
+ self.visit(node.value)
124
+ self.bind(node.target, node.value)
125
+
126
+ def visit_With(self, node):
127
+ for item in node.items:
128
+ self.visit(item.context_expr)
129
+ if item.optional_vars:
130
+ self.bind(item.optional_vars, item.context_expr)
131
+ for statement in node.body:
132
+ self.visit(statement)
133
+
134
+ visit_AsyncWith = visit_With
135
+
136
+ def visit_Call(self, node):
137
+ if self.kind(node):
138
+ self.found = True
139
+ self.generic_visit(node)
140
+
141
+ def definition(self, node):
142
+ self.aliases.pop(node.name, None)
143
+ self.bound.pop(node.name, None)
144
+ # Definitions shadow imported providers throughout this module. Function
145
+ # bodies share import resolution but their local bindings do not leak.
146
+ aliases, bound = self.aliases.copy(), self.bound.copy()
147
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
148
+ for arg in (node.args.posonlyargs + node.args.args + node.args.kwonlyargs
149
+ + ([node.args.vararg] if node.args.vararg else [])
150
+ + ([node.args.kwarg] if node.args.kwarg else [])):
151
+ self.aliases.pop(arg.arg, None)
152
+ self.bound.pop(arg.arg, None)
153
+ for statement in node.body:
154
+ self.visit(statement)
155
+ self.aliases, self.bound = aliases, bound
156
+
157
+ visit_FunctionDef = definition
158
+ visit_AsyncFunctionDef = definition
159
+ visit_ClassDef = definition
160
+
161
+
162
+ def evidence(source):
163
+ try:
164
+ tree = ast.parse(source)
165
+ except (SyntaxError, ValueError):
166
+ return False
167
+ visitor = Evidence()
168
+ visitor.visit(tree)
169
+ return visitor.found
170
+
171
+
172
+ def audit(root, ignore=(), fail_on='HIGH'):
173
+ root = Path(root)
174
+ if not root.is_dir() or not os.access(root, os.R_OK | os.X_OK):
175
+ raise ValueError('Root must be a readable directory')
176
+ positive = negative = production = test = False
177
+ count = 0
178
+ def walk_error(error):
179
+ raise ValueError(str(error))
180
+ for directory, dirs, files in os.walk(root, followlinks=False, onerror=walk_error):
181
+ dirs[:] = sorted(d for d in dirs if not Path(directory, d).is_symlink())
182
+ for filename in sorted(files):
183
+ path = Path(directory, filename)
184
+ rel = path.relative_to(root)
185
+ if path.is_symlink() or any(fnmatch.fnmatchcase(rel.as_posix(), pattern) for pattern in ignore):
186
+ continue
187
+ doc = rel.as_posix() == 'README.md' or (path.suffix == '.md' and 'docs' in rel.parts[:-1])
188
+ source = path.suffix == '.py' and not set(rel.parts[:-1]) & {'fixtures', 'docs', 'examples'}
189
+ if not (doc or source):
190
+ continue
191
+ try:
192
+ content = path.read_text(encoding='utf-8')
193
+ except (OSError, UnicodeError) as error:
194
+ raise ValueError(str(error)) from error
195
+ count += 1
196
+ if doc:
197
+ pos, neg = claims(content)
198
+ positive |= pos
199
+ negative |= neg
200
+ if source and evidence(content):
201
+ is_test = 'tests' in rel.parts[:-1] or filename.startswith('test_') or filename.endswith('_test.py')
202
+ test |= is_test
203
+ production |= not is_test
204
+ findings = []
205
+ if positive and not production:
206
+ findings.append(dict(rule='documented-classification-claim-false', severity='MEDIUM' if test else 'HIGH', message='Positive assertion lacks production provider evidence.'))
207
+ if negative and production:
208
+ findings.append(dict(rule='documented-no-classification-claim-false', severity='HIGH', message='Negative assertion conflicts with production provider evidence.'))
209
+ failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
210
+ return dict(verdict='FAIL' if failed else 'PASS', findings=findings, files_scanned=count)
@@ -0,0 +1,95 @@
1
+ """Exact normalized documentation templates, longest first."""
2
+
3
+ CLASSIFICATION = (
4
+ 'supports real time image classification',
5
+ 'classifies images into categories',
6
+ 'classifies photos into categories',
7
+ 'automatic image classification',
8
+ 'real time image classification',
9
+ 'classifies images in real time',
10
+ 'performs image classification',
11
+ 'supports image classification',
12
+ 'sorts images into categories',
13
+ 'sorts photos into categories',
14
+ 'image classification support',
15
+ 'recognizes objects in images',
16
+ 'identifies image categories',
17
+ 'labels images automatically',
18
+ 'image classification models',
19
+ 'recognize objects in images',
20
+ 'predicts labels for images',
21
+ 'image classification model',
22
+ 'tags images automatically',
23
+ 'identify image categories',
24
+ 'groups images by category',
25
+ 'assigns labels to images',
26
+ 'recognizes image content',
27
+ 'sorts images by category',
28
+ 'assign labels to images',
29
+ 'picture classification',
30
+ 'predicts photo labels',
31
+ 'predicts image labels',
32
+ 'object classification',
33
+ 'visual classification',
34
+ 'image classification',
35
+ 'photo classification',
36
+ 'classifies pictures',
37
+ 'categorizes images',
38
+ 'classifies objects',
39
+ 'classifies images',
40
+ 'classifies photos',
41
+ 'classify pictures',
42
+ 'image recognition',
43
+ 'image classifiers',
44
+ 'recognizes images',
45
+ 'categorize images',
46
+ 'image classifier',
47
+ 'classifies image',
48
+ 'recognize images',
49
+ 'classify objects',
50
+ 'classify images',
51
+ 'classify photos',
52
+ 'predicts labels',
53
+ 'classify image',
54
+ 'labels images',
55
+ 'label images',
56
+ )
57
+
58
+ NOCLASSIFICATION = (
59
+ 'does not support real time image classification',
60
+ 'does not classify images into categories',
61
+ 'does not perform image classification',
62
+ 'does not support image classification',
63
+ 'does not classify images in real time',
64
+ 'does not sort images into categories',
65
+ 'does not recognize objects in images',
66
+ 'does not label images automatically',
67
+ 'image classification not available',
68
+ 'image classification not supported',
69
+ 'does not predict labels for images',
70
+ 'does not identify image categories',
71
+ 'does not tag images automatically',
72
+ 'does not assign labels to images',
73
+ 'does not recognize image content',
74
+ 'without image classification',
75
+ 'classification not supported',
76
+ 'does not classify pictures',
77
+ 'does not categorize images',
78
+ 'without image recognition',
79
+ 'does not recognize images',
80
+ 'does not classify images',
81
+ 'does not classify photos',
82
+ 'no image classification',
83
+ 'never classifies images',
84
+ 'does not classify image',
85
+ 'never classifies image',
86
+ 'without classification',
87
+ 'does not label images',
88
+ 'no image recognition',
89
+ 'no image classifier',
90
+ 'does not recognize',
91
+ 'does not classify',
92
+ 'no classification',
93
+ 'never classifies',
94
+ 'no classifier',
95
+ )
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: classification-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline audit of documented whole-picture labelling 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
+ # Whole-picture labelling audit
12
+
13
+ Offline static checking of documented whole-picture labelling promises against Python provider evidence. Python 3.9 or newer; MIT licensed; no runtime dependencies. Source is parsed and never executed.
14
+
15
+ ```sh
16
+ pip install classification-claim-audit
17
+ classification-claim-audit ./project --json
18
+ python3 -m classification_claim_audit ./project --verbose
19
+ classification-claim-audit ./project --ignore 'vendor/*' --fail-on MEDIUM
20
+ classification-claim-audit --version
21
+ ```
22
+
23
+ Reads root README.md and Markdown files beneath any docs path component. Backtick and tilde fenced blocks with up to three leading spaces are excluded; inline code counts. Blank lines separate paragraphs, wrapped lines join, case is folded, contractions expand, hyphens become spaces, and whitespace collapses. Exact templates match word boundaries, longest first. Negative spans are removed before positive matching.
24
+
25
+ Evidence requires an alias-resolved call in a single module. Local definitions shadow imports. Construction alone counts for the first three providers; the fourth requires the literal task shown:
26
+
27
+ ```text
28
+ torchvision.models: listed constructors, including resnet18, vgg16, efficientnet_b0
29
+ timm.create_model
30
+ keras.applications / tensorflow.keras.applications: listed constructors, including ResNet50, MobileNetV2
31
+ transformers.pipeline("image-classification")
32
+ transformers.pipeline(task="image-classification")
33
+ ```
34
+
35
+ Complete constructor sets and wording templates are in the package modules. Bare imports, picture opening, camera capture, drawing supplied boxes, object finding, pixel segmentation, face/hand/pose detection, OCR, barcode decoding, tracking, generic tabular estimators, and bare neural heads do not count. Neither do strings, unbound calls, subprocess helpers, unrelated providers, or syntax-invalid files.
36
+
37
+ Symlinked files and directories are excluded. Python files under fixtures, docs, and examples are excluded. Files under tests or named test_*.py or *_test.py provide only test evidence. Repeatable ignore globs use fnmatch on relative POSIX paths.
38
+
39
+ At most one finding appears per family:
40
+
41
+ ```text
42
+ documented-classification-claim-false
43
+ HIGH: positive promise lacks production evidence
44
+ MEDIUM: evidence exists only in tests
45
+ documented-no-classification-claim-false
46
+ HIGH: negative promise conflicts with production evidence
47
+ ```
48
+
49
+ No matching promise means PASS regardless of source. The default threshold is HIGH; MEDIUM also fails on test-only evidence. Exits are 0 for PASS, 2 for FAIL, and 1 for invalid or unreadable roots and usage errors. Human output includes verdict and findings; verbose output adds the scanned count. JSON includes verdict, findings (rule, severity, message), and files_scanned.
50
+
51
+ Static construction evidence cannot establish runtime success, prediction quality, weights, or actual use. Dynamic imports, cross-module flow, custom implementations, text-to-picture similarity, and runtime model names are outside scope. These operations do not count:
52
+
53
+ ```text
54
+ CLIP / open_clip zero-shot matching
55
+ cv2.dnn.readNet / forward
56
+ torch.hub.load
57
+ torchvision.models.get_model("resnet18")
58
+ ```
59
+
60
+ Develop and build with:
61
+
62
+ ```sh
63
+ python3 -m unittest discover
64
+ python3 -m build
65
+ ```
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ classification_claim_audit/__init__.py
6
+ classification_claim_audit/__main__.py
7
+ classification_claim_audit/audit.py
8
+ classification_claim_audit/phrases.py
9
+ classification_claim_audit.egg-info/PKG-INFO
10
+ classification_claim_audit.egg-info/SOURCES.txt
11
+ classification_claim_audit.egg-info/dependency_links.txt
12
+ classification_claim_audit.egg-info/entry_points.txt
13
+ classification_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_classification/README.md
23
+ tests/fixtures/no_classification/app.py
24
+ tests/fixtures/testonly/README.md
25
+ tests/fixtures/testonly/test_model.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ classification-claim-audit = classification_claim_audit.__main__:main
@@ -0,0 +1 @@
1
+ classification_claim_audit
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "classification-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline audit of documented whole-picture labelling assertions"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+
13
+ [project.scripts]
14
+ classification-claim-audit = "classification_claim_audit.__main__:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["classification_claim_audit*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1 @@
1
+ classifies images
@@ -0,0 +1 @@
1
+ import torchvision
@@ -0,0 +1 @@
1
+ classifies images
@@ -0,0 +1,2 @@
1
+ import torchvision
2
+ torchvision.models.resnet18()
@@ -0,0 +1 @@
1
+ A small utility.
@@ -0,0 +1,2 @@
1
+ import torchvision
2
+ torchvision.models.resnet18()
@@ -0,0 +1 @@
1
+ does not classify images
@@ -0,0 +1,2 @@
1
+ import torchvision
2
+ torchvision.models.resnet18()
@@ -0,0 +1 @@
1
+ classifies images
@@ -0,0 +1,2 @@
1
+ import torchvision
2
+ torchvision.models.resnet18()
@@ -0,0 +1,127 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from classification_claim_audit.audit import audit, claims, evidence, matches
8
+ from classification_claim_audit.phrases import CLASSIFICATION, NOCLASSIFICATION
9
+ from classification_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(CLASSIFICATION), 52)
17
+ self.assertEqual(len(NOCLASSIFICATION), 36)
18
+ for values in (CLASSIFICATION, NOCLASSIFICATION):
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+'\nclassifies images\n'+fence), (False, False))
25
+
26
+ def test_inline(self):
27
+ self.assertEqual(claims('`classifies images`'), (True, False))
28
+
29
+ def test_normalization(self):
30
+ self.assertEqual(claims("Doesn't classify images into categories"), (False, True))
31
+ self.assertEqual(claims('REAL-TIME IMAGE\nCLASSIFICATION'), (True, False))
32
+ self.assertEqual(claims('classifies\n\nimages'), (False, False))
33
+
34
+ def test_longest_and_boundaries(self):
35
+ self.assertEqual(matches('classifies images into categories', reversed(CLASSIFICATION))[0], ['classifies images into categories'])
36
+ self.assertEqual(claims('preclassify imagesx'), (False, False))
37
+
38
+
39
+ POSITIVES = ['import torchvision\ntorchvision.models.resnet18()', 'import torchvision as tv\ntv.models.vgg16()', 'from torchvision.models import efficientnet_b0 as model\nmodel()', 'import timm\ntimm.create_model("x")', 'from timm import create_model as m\nm("x")', 'import keras\nkeras.applications.ResNet50()', 'import tensorflow as tf\ntf.keras.applications.MobileNetV2()', 'from keras.applications import Xception as X\nX()', 'from transformers import pipeline as p\np("image-classification")', 'import transformers as t\nt.pipeline(task="image-classification")']
40
+ NEGATIVES = ['import torchvision', 'import cv2\ncv2.imread("x")', 'from PIL import Image\nImage.open("x")', 'import cv2\ncv2.VideoCapture(0)', 'import cv2\ncv2.rectangle(x,a,b,c)', 'from torchvision.models.detection import fasterrcnn_resnet50_fpn\nfasterrcnn_resnet50_fpn()', 'from ultralytics import YOLO\nYOLO("x")', 'import mediapipe as mp\nmp.solutions.selfie_segmentation.SelfieSegmentation()', 'import mediapipe as mp\nmp.tasks.vision.ImageSegmenter.create_from_options(o)', 'import face_recognition\nface_recognition.face_locations(x)', 'import mediapipe as mp\nmp.solutions.hands.Hands()', 'import mediapipe as mp\nmp.solutions.pose.Pose()', 'import pytesseract\npytesseract.image_to_string(x)', 'from pyzbar.pyzbar import decode\ndecode(x)', 'model.track(x)', 'from sklearn.linear_model import LogisticRegression\nLogisticRegression().fit(x,y)', 'import torch\ntorch.nn.Linear(2,3)', 'import cv2\nn=cv2.dnn.readNet("x")\nn.forward()', 'import torch\ntorch.hub.load("x","resnet18")', 'from torchvision.models import get_model\nget_model("resnet18")', 'from timm import create_model\ndef create_model(x): return x\ncreate_model("x")', 'from transformers import pipeline\nclass pipeline: pass\npipeline("image-classification")', 'from torchvision.models import resnet18\nresnet18=lambda:None\nresnet18()', 'resnet18()\ncreate_model("x")\npipeline("image-classification")', 'x="classification"', 'import subprocess\nsubprocess.run(["classify"])', 'not valid python !', 'from transformers import pipeline\npipeline("object-detection")', 'import open_clip\nopen_clip.create_model("x")', 'from other import create_model\ncreate_model("x")']
41
+
42
+ class EvidenceTests(unittest.TestCase):
43
+ def test_all_listed_constructors(self):
44
+ from classification_claim_audit.audit import MODELS, KERAS_MODELS
45
+ for name in MODELS:
46
+ with self.subTest(model=name):
47
+ self.assertTrue(evidence('from torchvision.models import '+name+' as m\nm()'))
48
+ for name in KERAS_MODELS:
49
+ with self.subTest(model=name):
50
+ self.assertTrue(evidence('from tensorflow.keras.applications import '+name+' as m\nm()'))
51
+
52
+ def test_parameter_shadows(self):
53
+ for parameter in ('pipeline', '*pipeline', '**pipeline'):
54
+ self.assertFalse(evidence('from transformers import pipeline\ndef f('+parameter+'):\n pipeline("image-classification")'))
55
+
56
+
57
+
58
+ class IntegrationTests(unittest.TestCase):
59
+ def cli(self, *args):
60
+ out, err = io.StringIO(), io.StringIO()
61
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
62
+ try:
63
+ status=main(list(map(str,args)))
64
+ except SystemExit as e:
65
+ status=e.code
66
+ return status,out.getvalue(),err.getvalue()
67
+
68
+ def test_fixtures(self):
69
+ for fixture, status, severity, rule in [
70
+ ('good',0,None,None), ('no_claim',0,None,None),
71
+ ('bad',2,'HIGH','documented-classification-claim-false'),
72
+ ('testonly',0,'MEDIUM','documented-classification-claim-false'),
73
+ ('no_classification',2,'HIGH','documented-no-classification-claim-false')]:
74
+ with self.subTest(fixture=fixture):
75
+ code,out,_=self.cli(FIXTURES/fixture,'--json')
76
+ self.assertEqual(code,status)
77
+ result=json.loads(out)
78
+ self.assertEqual(set(result),{'verdict','findings','files_scanned'})
79
+ self.assertEqual(result['verdict'],'FAIL' if status==2 else 'PASS')
80
+ self.assertEqual(len(result['findings']),int(severity is not None))
81
+ if severity:
82
+ self.assertEqual(result['findings'][0]['severity'],severity)
83
+ self.assertEqual(result['findings'][0]['rule'],rule)
84
+ self.assertEqual(set(result['findings'][0]),{'rule','severity','message'})
85
+ self.assertEqual(self.cli(FIXTURES/'testonly','--fail-on','MEDIUM')[0],2)
86
+
87
+ def test_ignore_and_verbose(self):
88
+ code,out,_=self.cli(FIXTURES/'bad','--ignore','README.md','--verbose')
89
+ self.assertEqual(code,0)
90
+ self.assertIn('Files scanned: 1',out)
91
+ self.assertEqual(self.cli(FIXTURES/'good','--ignore','*.py')[0],2)
92
+
93
+ def test_version_errors(self):
94
+ self.assertEqual(self.cli('--version')[:2],(0,'0.1.0\n'))
95
+ for args in [[],['--unknown'],['/nonexistent-root'],[str(FIXTURES/'bad'),'--fail-on','LOW']]:
96
+ self.assertEqual(self.cli(*args)[0],1)
97
+
98
+ def test_exclusions_and_docs(self):
99
+ with tempfile.TemporaryDirectory() as d:
100
+ root=Path(d); (root/'README.md').write_text('classifies images')
101
+ for component in ['docs','examples','fixtures']:
102
+ folder=root/component;folder.mkdir();(folder/'source.py').write_text(POSITIVES[0])
103
+ (root/'linked.py').symlink_to(root/'docs/source.py')
104
+ (root/'linked_dir').symlink_to(root/'docs',target_is_directory=True)
105
+ self.assertEqual(audit(root)['findings'][0]['severity'],'HIGH')
106
+ (root/'README.md').write_text('Nothing promised.')
107
+ (root/'docs/note.md').write_text('classifies images')
108
+ self.assertEqual(audit(root)['verdict'],'FAIL')
109
+
110
+ def test_self_audit(self):
111
+ self.assertEqual(audit(Path(__file__).resolve().parents[1])['verdict'],'PASS')
112
+
113
+
114
+ def add_test(cls, name, function, value, expected):
115
+ def test(self):
116
+ self.assertEqual(function(value), expected)
117
+ setattr(cls, name, test)
118
+
119
+
120
+ for i,phrase in enumerate(CLASSIFICATION):
121
+ add_test(ClaimsTests,'test_positive_%02d'%i,claims,phrase,(True,False))
122
+ for i,phrase in enumerate(NOCLASSIFICATION):
123
+ add_test(ClaimsTests,'test_negative_%02d'%i,claims,phrase,(False,True))
124
+ for i,source in enumerate(POSITIVES):
125
+ add_test(EvidenceTests,'test_provider_%02d'%i,evidence,source,True)
126
+ for i,source in enumerate(NEGATIVES):
127
+ add_test(EvidenceTests,'test_nonprovider_%02d'%i,evidence,source,False)