classification-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,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,10 @@
1
+ classification_claim_audit/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ classification_claim_audit/__main__.py,sha256=nt-sdUHWN8o7oMXToF3-PTvNmvCwN99jTqytoWbwED4,1336
3
+ classification_claim_audit/audit.py,sha256=B9-mL7Nn-rLwVoMmjy7LjJ359Rs3ZmkhYPakKPhTnJ8,9158
4
+ classification_claim_audit/phrases.py,sha256=_y8qnBDVOFWdCM689qkfDdo_1Q5Rxtmd24PlW2JLKsc,2974
5
+ classification_claim_audit-0.1.0.dist-info/licenses/LICENSE,sha256=xMnuyoMuMA-noObdRRtXjo3qyTPZE7gRqDWA2YsqMW8,1096
6
+ classification_claim_audit-0.1.0.dist-info/METADATA,sha256=4xRvVkMs2fbvjvuvUyq8iwWTOm-bnmI8gt5FgE1_5lw,3494
7
+ classification_claim_audit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ classification_claim_audit-0.1.0.dist-info/entry_points.txt,sha256=EXegqhkg4rMDWviM8qtTKuEjlvMtsNrnmOzux1FqOtI,88
9
+ classification_claim_audit-0.1.0.dist-info/top_level.txt,sha256=kmQXl2YnWY8K3wizWGiFsV7XAKqDfAc5nbQ--r86CTY,27
10
+ classification_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
+ classification-claim-audit = classification_claim_audit.__main__:main
@@ -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 @@
1
+ classification_claim_audit