ocr-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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ocr-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 README.md LICENSE
2
+ recursive-include tests *.py *.md .env
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: ocr-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented picture-word claims
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # ocr-claim-audit 0.1.0
12
+
13
+ Offline static checking of documented picture-word claims against Python source.
14
+ No provider installation is needed; audited code is never executed.
15
+ Requires Python 3.9 or newer. MIT licensed.
16
+
17
+ ## Usage
18
+
19
+ ```sh
20
+ python3 -m pip install .
21
+ ocr-claim-audit /path/to/project --json
22
+ python3 -m ocr_claim_audit /path/to/project --verbose
23
+ python3 -m ocr_claim_audit /path/to/project --ignore 'docs/generated/*' --fail-on MEDIUM
24
+ python3 -m unittest discover
25
+ python3 -m build
26
+ ```
27
+
28
+ The default threshold is HIGH. MEDIUM findings remain visible but exit zero;
29
+ `--fail-on MEDIUM` makes them fail. Exit codes are 0 for PASS, 2 for FAIL,
30
+ and 1 for usage or filesystem errors. `--version` prints 0.1.0.
31
+ JSON includes verdict, findings (rule, severity, message), and a source count.
32
+ At most one finding appears per family. Rule identifiers:
33
+
34
+ ```text
35
+ documented-ocr-claim-false
36
+ documented-no-ocr-claim-false
37
+ ```
38
+
39
+ ## Scope
40
+
41
+ Root README.md and Markdown beneath any docs path component supply claims.
42
+ Fenced blocks are excluded; inline code counts. Paragraph lines are joined,
43
+ case folded, contractions expanded, hyphens replaced with spaces, and whitespace
44
+ collapsed. Matching uses word boundaries and exact templates. Negative spans
45
+ are removed first, longest first.
46
+
47
+ Production evidence comes from AST calls resolved through provider imports and
48
+ aliases: pytesseract image_to_string, image_to_data, image_to_boxes, image_to_osd;
49
+ easyocr Reader; paddleocr PaddleOCR; and RapidOCR from rapidocr_onnxruntime,
50
+ rapidocr_openvino, or rapidocr_torch. Reader construction alone counts, so
51
+ bound and chained calls also qualify. Local function/class names shadow imports.
52
+ Source under tests or with test file names supplies only MEDIUM evidence.
53
+ Source under fixtures, docs, and examples, and symlinked files, is excluded.
54
+ Environment files are never opened.
55
+
56
+ ## Limitations
57
+
58
+ Only the exact templates below count. A bare acronym or settings heading is
59
+ insufficient. Opposite-direction image generation, camera capture, image
60
+ opening, preprocessing, file export, and instructions for the user to inspect
61
+ words themselves are outside claim scope. Imports, strings, decorators,
62
+ unbound reader methods, pixel processing, and image loading are insufficient.
63
+ A subprocess invoking a system reader helper is excluded: command strings do
64
+ not establish a provider call. Other recognition stacks, including phone-camera
65
+ SDKs, cloud picture-word APIs, and handwriting-specific engines, are out of
66
+ scope. Only the Python routes listed above count. Static analysis cannot prove
67
+ runtime success, dependency availability, or image quality. Invalid syntax
68
+ provides no evidence. Files must be UTF-8. With no source, a positive claim
69
+ fails at HIGH while a negative claim passes. No claims always passes.
70
+
71
+ ## Exact vocabulary
72
+
73
+ ```text
74
+ extracts text from scanned documents
75
+ extract text from scanned documents
76
+ supports optical character recognition
77
+ support optical character recognition
78
+ extracts text from screenshots
79
+ extract text from screenshots
80
+ recognizes text from images
81
+ recognize text from images
82
+ recognises text from images
83
+ recognise text from images
84
+ recognizes text in images
85
+ recognize text in images
86
+ recognises text in images
87
+ recognise text in images
88
+ extracts text from images
89
+ extract text from images
90
+ extracts text from photos
91
+ extract text from photos
92
+ reads text from images
93
+ read text from images
94
+ reads text from photos
95
+ read text from photos
96
+ reads text in images
97
+ read text in images
98
+ converts images to text
99
+ convert images to text
100
+ converts photos to text
101
+ convert photos to text
102
+ performs ocr on images
103
+ perform ocr on images
104
+ performs ocr on photos
105
+ perform ocr on photos
106
+ optical character recognition support
107
+ does ocr on images
108
+ do ocr on images
109
+ recognizes text
110
+ recognize text
111
+ recognises text
112
+ recognise text
113
+ extracts text
114
+ extract text
115
+ reads text
116
+ read text
117
+ ocr support
118
+ supports ocr
119
+ support ocr
120
+ text recognition
121
+ optical character recognition
122
+ does not support optical character recognition
123
+ does not recognize text in images
124
+ does not recognise text in images
125
+ does not recognize text from images
126
+ does not recognise text from images
127
+ does not extract text from images
128
+ does not extract text from photos
129
+ does not read text from images
130
+ does not read text from photos
131
+ does not convert images to text
132
+ does not convert photos to text
133
+ does not perform ocr on images
134
+ does not perform ocr
135
+ does not support ocr
136
+ optical character recognition not supported
137
+ text recognition not supported
138
+ ocr not supported
139
+ no optical character recognition
140
+ without optical character recognition
141
+ no text recognition
142
+ without text recognition
143
+ no ocr support
144
+ without ocr support
145
+ no ocr
146
+ without ocr
147
+ ```
@@ -0,0 +1,137 @@
1
+ # ocr-claim-audit 0.1.0
2
+
3
+ Offline static checking of documented picture-word claims against Python source.
4
+ No provider installation is needed; audited code is never executed.
5
+ Requires Python 3.9 or newer. MIT licensed.
6
+
7
+ ## Usage
8
+
9
+ ```sh
10
+ python3 -m pip install .
11
+ ocr-claim-audit /path/to/project --json
12
+ python3 -m ocr_claim_audit /path/to/project --verbose
13
+ python3 -m ocr_claim_audit /path/to/project --ignore 'docs/generated/*' --fail-on MEDIUM
14
+ python3 -m unittest discover
15
+ python3 -m build
16
+ ```
17
+
18
+ The default threshold is HIGH. MEDIUM findings remain visible but exit zero;
19
+ `--fail-on MEDIUM` makes them fail. Exit codes are 0 for PASS, 2 for FAIL,
20
+ and 1 for usage or filesystem errors. `--version` prints 0.1.0.
21
+ JSON includes verdict, findings (rule, severity, message), and a source count.
22
+ At most one finding appears per family. Rule identifiers:
23
+
24
+ ```text
25
+ documented-ocr-claim-false
26
+ documented-no-ocr-claim-false
27
+ ```
28
+
29
+ ## Scope
30
+
31
+ Root README.md and Markdown beneath any docs path component supply claims.
32
+ Fenced blocks are excluded; inline code counts. Paragraph lines are joined,
33
+ case folded, contractions expanded, hyphens replaced with spaces, and whitespace
34
+ collapsed. Matching uses word boundaries and exact templates. Negative spans
35
+ are removed first, longest first.
36
+
37
+ Production evidence comes from AST calls resolved through provider imports and
38
+ aliases: pytesseract image_to_string, image_to_data, image_to_boxes, image_to_osd;
39
+ easyocr Reader; paddleocr PaddleOCR; and RapidOCR from rapidocr_onnxruntime,
40
+ rapidocr_openvino, or rapidocr_torch. Reader construction alone counts, so
41
+ bound and chained calls also qualify. Local function/class names shadow imports.
42
+ Source under tests or with test file names supplies only MEDIUM evidence.
43
+ Source under fixtures, docs, and examples, and symlinked files, is excluded.
44
+ Environment files are never opened.
45
+
46
+ ## Limitations
47
+
48
+ Only the exact templates below count. A bare acronym or settings heading is
49
+ insufficient. Opposite-direction image generation, camera capture, image
50
+ opening, preprocessing, file export, and instructions for the user to inspect
51
+ words themselves are outside claim scope. Imports, strings, decorators,
52
+ unbound reader methods, pixel processing, and image loading are insufficient.
53
+ A subprocess invoking a system reader helper is excluded: command strings do
54
+ not establish a provider call. Other recognition stacks, including phone-camera
55
+ SDKs, cloud picture-word APIs, and handwriting-specific engines, are out of
56
+ scope. Only the Python routes listed above count. Static analysis cannot prove
57
+ runtime success, dependency availability, or image quality. Invalid syntax
58
+ provides no evidence. Files must be UTF-8. With no source, a positive claim
59
+ fails at HIGH while a negative claim passes. No claims always passes.
60
+
61
+ ## Exact vocabulary
62
+
63
+ ```text
64
+ extracts text from scanned documents
65
+ extract text from scanned documents
66
+ supports optical character recognition
67
+ support optical character recognition
68
+ extracts text from screenshots
69
+ extract text from screenshots
70
+ recognizes text from images
71
+ recognize text from images
72
+ recognises text from images
73
+ recognise text from images
74
+ recognizes text in images
75
+ recognize text in images
76
+ recognises text in images
77
+ recognise text in images
78
+ extracts text from images
79
+ extract text from images
80
+ extracts text from photos
81
+ extract text from photos
82
+ reads text from images
83
+ read text from images
84
+ reads text from photos
85
+ read text from photos
86
+ reads text in images
87
+ read text in images
88
+ converts images to text
89
+ convert images to text
90
+ converts photos to text
91
+ convert photos to text
92
+ performs ocr on images
93
+ perform ocr on images
94
+ performs ocr on photos
95
+ perform ocr on photos
96
+ optical character recognition support
97
+ does ocr on images
98
+ do ocr on images
99
+ recognizes text
100
+ recognize text
101
+ recognises text
102
+ recognise text
103
+ extracts text
104
+ extract text
105
+ reads text
106
+ read text
107
+ ocr support
108
+ supports ocr
109
+ support ocr
110
+ text recognition
111
+ optical character recognition
112
+ does not support optical character recognition
113
+ does not recognize text in images
114
+ does not recognise text in images
115
+ does not recognize text from images
116
+ does not recognise text from images
117
+ does not extract text from images
118
+ does not extract text from photos
119
+ does not read text from images
120
+ does not read text from photos
121
+ does not convert images to text
122
+ does not convert photos to text
123
+ does not perform ocr on images
124
+ does not perform ocr
125
+ does not support ocr
126
+ optical character recognition not supported
127
+ text recognition not supported
128
+ ocr not supported
129
+ no optical character recognition
130
+ without optical character recognition
131
+ no text recognition
132
+ without text recognition
133
+ no ocr support
134
+ without ocr support
135
+ no ocr
136
+ without ocr
137
+ ```
@@ -0,0 +1,2 @@
1
+ """Static picture-word claim auditing."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,36 @@
1
+ """Command line entry point."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ from . import __version__
6
+ from .audit import audit
7
+
8
+ def main(argv=None):
9
+ parser = argparse.ArgumentParser(description="Check documented picture-word claims against Python code.")
10
+ parser.add_argument("root", nargs="?", default=".")
11
+ parser.add_argument("--json", action="store_true")
12
+ parser.add_argument("--verbose", action="store_true")
13
+ parser.add_argument("--ignore", action="append", default=[])
14
+ parser.add_argument("--fail-on", choices=["HIGH", "MEDIUM"], default="HIGH")
15
+ parser.add_argument("--version", action="version", version=__version__)
16
+ try:
17
+ args = parser.parse_args(argv)
18
+ except SystemExit as exc:
19
+ return 0 if exc.code == 0 else 1
20
+ try:
21
+ result = audit(args.root, args.ignore, args.fail_on)
22
+ except (ValueError, OSError, UnicodeError) as exc:
23
+ print(str(exc), file=sys.stderr)
24
+ return 1
25
+ if args.json:
26
+ print(json.dumps(result))
27
+ else:
28
+ print(result["verdict"])
29
+ for finding in result["findings"]:
30
+ print("{severity} {rule}: {message}".format(**finding))
31
+ if args.verbose:
32
+ print("Scanned {} Python files".format(result["scanned_python_files"]))
33
+ return 2 if result["verdict"] == "FAIL" else 0
34
+
35
+ if __name__ == "__main__":
36
+ sys.exit(main())
@@ -0,0 +1,100 @@
1
+ """Offline documentation and AST analysis; audited code is never executed."""
2
+ import ast
3
+ import fnmatch
4
+ import re
5
+ from pathlib import Path
6
+ from .phrases import OCR, NOOCR
7
+
8
+ MODULES = {"pytesseract", "easyocr", "paddleocr", "rapidocr_onnxruntime", "rapidocr_openvino", "rapidocr_torch"}
9
+ FUNCTIONS = {"pytesseract": {"image_to_string", "image_to_data", "image_to_boxes", "image_to_osd"}, "easyocr": {"Reader"}, "paddleocr": {"PaddleOCR"}, **{m: {"RapidOCR"} for m in MODULES if m.startswith("rapidocr_")}}
10
+
11
+ def normalize(text):
12
+ return re.sub(r"\s+", " ", text.lower().replace("n't", " not").replace("-", " ")).strip()
13
+
14
+ def prose(text):
15
+ lines = []
16
+ fence = None
17
+ for line in text.splitlines():
18
+ match = re.match(r"^\s*(`{3,}|~{3,})", line)
19
+ if match:
20
+ mark = match.group(1)
21
+ if fence is None:
22
+ fence = mark
23
+ elif mark[0] == fence[0] and len(mark) >= len(fence) and not line.strip()[len(mark):].strip():
24
+ fence = None
25
+ lines.append("")
26
+ elif fence is None:
27
+ lines.append(line)
28
+ return "\n".join(lines)
29
+
30
+ def claims(text):
31
+ positive = negative = False
32
+ for paragraph in re.split(r"\n\s*\n", prose(text)):
33
+ paragraph = normalize(paragraph)
34
+ for phrase in sorted(NOOCR, key=len, reverse=True):
35
+ paragraph, count = re.subn(r"\b" + re.escape(phrase) + r"\b", " ", paragraph)
36
+ negative |= bool(count)
37
+ positive |= any(re.search(r"\b" + re.escape(p) + r"\b", paragraph) for p in OCR)
38
+ return bool(positive), bool(negative)
39
+
40
+ def evidence(source):
41
+ try:
42
+ tree = ast.parse(source)
43
+ except SyntaxError:
44
+ return False
45
+ aliases = {}
46
+ shadows = {n.name for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))}
47
+ for node in ast.walk(tree):
48
+ if isinstance(node, ast.Import):
49
+ for item in node.names:
50
+ if item.name in MODULES:
51
+ aliases[item.asname or item.name] = item.name
52
+ elif isinstance(node, ast.ImportFrom) and node.module in MODULES:
53
+ for item in node.names:
54
+ if item.name in FUNCTIONS[node.module]:
55
+ aliases[item.asname or item.name] = node.module + "." + item.name
56
+ def resolve(node):
57
+ if isinstance(node, ast.Name):
58
+ return "" if node.id in shadows else aliases.get(node.id, "")
59
+ if isinstance(node, ast.Attribute):
60
+ base = resolve(node.value)
61
+ return base + "." + node.attr if base else ""
62
+ return ""
63
+ # Every bound/chained reader route necessarily contains its constructor
64
+ # Call in this module, which already satisfies Route B.
65
+ return any(resolve(n.func) in {m + "." + f for m, fs in FUNCTIONS.items() for f in fs}
66
+ for n in ast.walk(tree) if isinstance(n, ast.Call))
67
+
68
+ def audit(root, ignore=(), fail_on="HIGH"):
69
+ root = Path(root)
70
+ if not root.is_dir():
71
+ raise ValueError("root must be a readable directory")
72
+ pos = neg = prod = test = False
73
+ scanned = 0
74
+ for path in sorted(root.rglob("*")):
75
+ rel = path.relative_to(root)
76
+ if path.is_symlink() or any((root / Path(*rel.parts[:i])).is_symlink() for i in range(1, len(rel.parts))):
77
+ continue
78
+ if not path.is_file() or any(fnmatch.fnmatch(rel.as_posix(), g) for g in ignore):
79
+ continue
80
+ if path.suffix.lower() == ".md" and (rel.as_posix() == "README.md" or "docs" in rel.parts[:-1]):
81
+ p, n = claims(path.read_text(encoding="utf-8"))
82
+ pos |= p
83
+ neg |= n
84
+ elif path.suffix == ".py":
85
+ if any(p in {"fixtures", "docs", "examples"} for p in rel.parts[:-1]):
86
+ continue
87
+ is_test = "tests" in rel.parts[:-1] or path.name.startswith("test_") or path.name.endswith("_test.py")
88
+ scanned += 1
89
+ found = evidence(path.read_text(encoding="utf-8"))
90
+ if is_test:
91
+ test |= found
92
+ else:
93
+ prod |= found
94
+ findings = []
95
+ if pos and not prod:
96
+ findings.append(dict(rule="documented-ocr-claim-false", severity="MEDIUM" if test else "HIGH", message="Documented picture-word capability lacks production evidence."))
97
+ if neg and prod:
98
+ findings.append(dict(rule="documented-no-ocr-claim-false", severity="HIGH", message="Documented absence conflicts with production evidence."))
99
+ failed = any(f["severity"] == "HIGH" or fail_on == "MEDIUM" for f in findings)
100
+ return dict(verdict="FAIL" if failed else "PASS", findings=findings, scanned_python_files=scanned)
@@ -0,0 +1,3 @@
1
+ """Exact documented claim vocabulary."""
2
+ OCR = ('extracts text from scanned documents', 'extract text from scanned documents', 'supports optical character recognition', 'support optical character recognition', 'extracts text from screenshots', 'extract text from screenshots', 'recognizes text from images', 'recognize text from images', 'recognises text from images', 'recognise text from images', 'recognizes text in images', 'recognize text in images', 'recognises text in images', 'recognise text in images', 'extracts text from images', 'extract text from images', 'extracts text from photos', 'extract text from photos', 'reads text from images', 'read text from images', 'reads text from photos', 'read text from photos', 'reads text in images', 'read text in images', 'converts images to text', 'convert images to text', 'converts photos to text', 'convert photos to text', 'performs ocr on images', 'perform ocr on images', 'performs ocr on photos', 'perform ocr on photos', 'optical character recognition support', 'does ocr on images', 'do ocr on images', 'recognizes text', 'recognize text', 'recognises text', 'recognise text', 'extracts text', 'extract text', 'reads text', 'read text', 'ocr support', 'supports ocr', 'support ocr', 'text recognition', 'optical character recognition')
3
+ NOOCR = ('does not support optical character recognition', 'does not recognize text in images', 'does not recognise text in images', 'does not recognize text from images', 'does not recognise text from images', 'does not extract text from images', 'does not extract text from photos', 'does not read text from images', 'does not read text from photos', 'does not convert images to text', 'does not convert photos to text', 'does not perform ocr on images', 'does not perform ocr', 'does not support ocr', 'optical character recognition not supported', 'text recognition not supported', 'ocr not supported', 'no optical character recognition', 'without optical character recognition', 'no text recognition', 'without text recognition', 'no ocr support', 'without ocr support', 'no ocr', 'without ocr')
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: ocr-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented picture-word claims
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # ocr-claim-audit 0.1.0
12
+
13
+ Offline static checking of documented picture-word claims against Python source.
14
+ No provider installation is needed; audited code is never executed.
15
+ Requires Python 3.9 or newer. MIT licensed.
16
+
17
+ ## Usage
18
+
19
+ ```sh
20
+ python3 -m pip install .
21
+ ocr-claim-audit /path/to/project --json
22
+ python3 -m ocr_claim_audit /path/to/project --verbose
23
+ python3 -m ocr_claim_audit /path/to/project --ignore 'docs/generated/*' --fail-on MEDIUM
24
+ python3 -m unittest discover
25
+ python3 -m build
26
+ ```
27
+
28
+ The default threshold is HIGH. MEDIUM findings remain visible but exit zero;
29
+ `--fail-on MEDIUM` makes them fail. Exit codes are 0 for PASS, 2 for FAIL,
30
+ and 1 for usage or filesystem errors. `--version` prints 0.1.0.
31
+ JSON includes verdict, findings (rule, severity, message), and a source count.
32
+ At most one finding appears per family. Rule identifiers:
33
+
34
+ ```text
35
+ documented-ocr-claim-false
36
+ documented-no-ocr-claim-false
37
+ ```
38
+
39
+ ## Scope
40
+
41
+ Root README.md and Markdown beneath any docs path component supply claims.
42
+ Fenced blocks are excluded; inline code counts. Paragraph lines are joined,
43
+ case folded, contractions expanded, hyphens replaced with spaces, and whitespace
44
+ collapsed. Matching uses word boundaries and exact templates. Negative spans
45
+ are removed first, longest first.
46
+
47
+ Production evidence comes from AST calls resolved through provider imports and
48
+ aliases: pytesseract image_to_string, image_to_data, image_to_boxes, image_to_osd;
49
+ easyocr Reader; paddleocr PaddleOCR; and RapidOCR from rapidocr_onnxruntime,
50
+ rapidocr_openvino, or rapidocr_torch. Reader construction alone counts, so
51
+ bound and chained calls also qualify. Local function/class names shadow imports.
52
+ Source under tests or with test file names supplies only MEDIUM evidence.
53
+ Source under fixtures, docs, and examples, and symlinked files, is excluded.
54
+ Environment files are never opened.
55
+
56
+ ## Limitations
57
+
58
+ Only the exact templates below count. A bare acronym or settings heading is
59
+ insufficient. Opposite-direction image generation, camera capture, image
60
+ opening, preprocessing, file export, and instructions for the user to inspect
61
+ words themselves are outside claim scope. Imports, strings, decorators,
62
+ unbound reader methods, pixel processing, and image loading are insufficient.
63
+ A subprocess invoking a system reader helper is excluded: command strings do
64
+ not establish a provider call. Other recognition stacks, including phone-camera
65
+ SDKs, cloud picture-word APIs, and handwriting-specific engines, are out of
66
+ scope. Only the Python routes listed above count. Static analysis cannot prove
67
+ runtime success, dependency availability, or image quality. Invalid syntax
68
+ provides no evidence. Files must be UTF-8. With no source, a positive claim
69
+ fails at HIGH while a negative claim passes. No claims always passes.
70
+
71
+ ## Exact vocabulary
72
+
73
+ ```text
74
+ extracts text from scanned documents
75
+ extract text from scanned documents
76
+ supports optical character recognition
77
+ support optical character recognition
78
+ extracts text from screenshots
79
+ extract text from screenshots
80
+ recognizes text from images
81
+ recognize text from images
82
+ recognises text from images
83
+ recognise text from images
84
+ recognizes text in images
85
+ recognize text in images
86
+ recognises text in images
87
+ recognise text in images
88
+ extracts text from images
89
+ extract text from images
90
+ extracts text from photos
91
+ extract text from photos
92
+ reads text from images
93
+ read text from images
94
+ reads text from photos
95
+ read text from photos
96
+ reads text in images
97
+ read text in images
98
+ converts images to text
99
+ convert images to text
100
+ converts photos to text
101
+ convert photos to text
102
+ performs ocr on images
103
+ perform ocr on images
104
+ performs ocr on photos
105
+ perform ocr on photos
106
+ optical character recognition support
107
+ does ocr on images
108
+ do ocr on images
109
+ recognizes text
110
+ recognize text
111
+ recognises text
112
+ recognise text
113
+ extracts text
114
+ extract text
115
+ reads text
116
+ read text
117
+ ocr support
118
+ supports ocr
119
+ support ocr
120
+ text recognition
121
+ optical character recognition
122
+ does not support optical character recognition
123
+ does not recognize text in images
124
+ does not recognise text in images
125
+ does not recognize text from images
126
+ does not recognise text from images
127
+ does not extract text from images
128
+ does not extract text from photos
129
+ does not read text from images
130
+ does not read text from photos
131
+ does not convert images to text
132
+ does not convert photos to text
133
+ does not perform ocr on images
134
+ does not perform ocr
135
+ does not support ocr
136
+ optical character recognition not supported
137
+ text recognition not supported
138
+ ocr not supported
139
+ no optical character recognition
140
+ without optical character recognition
141
+ no text recognition
142
+ without text recognition
143
+ no ocr support
144
+ without ocr support
145
+ no ocr
146
+ without ocr
147
+ ```
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ ocr_claim_audit/__init__.py
6
+ ocr_claim_audit/__main__.py
7
+ ocr_claim_audit/audit.py
8
+ ocr_claim_audit/phrases.py
9
+ ocr_claim_audit.egg-info/PKG-INFO
10
+ ocr_claim_audit.egg-info/SOURCES.txt
11
+ ocr_claim_audit.egg-info/dependency_links.txt
12
+ ocr_claim_audit.egg-info/entry_points.txt
13
+ ocr_claim_audit.egg-info/top_level.txt
14
+ tests/__init__.py
15
+ tests/cases.py
16
+ tests/test_audit.py
17
+ tests/fixtures/.env
18
+ tests/fixtures/bad/README.md
19
+ tests/fixtures/bad/app.py
20
+ tests/fixtures/good/README.md
21
+ tests/fixtures/good/app.py
22
+ tests/fixtures/no-ocr/README.md
23
+ tests/fixtures/no-ocr/app.py
24
+ tests/fixtures/testonly/README.md
25
+ tests/fixtures/testonly/tests/test_reader.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ocr-claim-audit = ocr_claim_audit.__main__:main
@@ -0,0 +1 @@
1
+ ocr_claim_audit
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ocr-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline static audit of documented picture-word claims"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+
13
+ [project.scripts]
14
+ ocr-claim-audit = "ocr_claim_audit.__main__:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["ocr_claim_audit*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,20 @@
1
+ GOOD = [
2
+ 'from pytesseract import image_to_string\nimage_to_string(img)',
3
+ 'import pytesseract\npytesseract.image_to_string(img)',
4
+ 'from pytesseract import image_to_data\nimage_to_data(img)',
5
+ 'import easyocr\neasyocr.Reader([])',
6
+ 'import easyocr\nr = easyocr.Reader([])\nr.readtext(img)',
7
+ 'import easyocr\neasyocr.Reader([]).readtext(img)',
8
+ 'import paddleocr\npaddleocr.PaddleOCR()',
9
+ 'import paddleocr\nr = paddleocr.PaddleOCR()\nr.ocr(img)',
10
+ 'from rapidocr_onnxruntime import RapidOCR\nRapidOCR()',
11
+ 'from rapidocr_onnxruntime import RapidOCR\nengine = RapidOCR()\nengine(img)',
12
+ ]
13
+ BAD = [
14
+ 'x = 1', 'import pytesseract', 'from PIL import Image\nImage.open(path)',
15
+ 'import cv2\ncv2.VideoCapture(0)', 'import cv2\ncv2.threshold(img,0,255,0)',
16
+ 'reader.readtext(img)', 'reader.ocr(img)', 'text = "hello world"',
17
+ 'import subprocess\nsubprocess.run(["tesseract", "photo.png"])',
18
+ 'def image_to_string(img): return "hello"\nimage_to_string(img)',
19
+ 'class Reader: pass\nReader()',
20
+ ]
@@ -0,0 +1 @@
1
+ MARKER_ONLY
@@ -0,0 +1 @@
1
+ Extracts text from images
@@ -0,0 +1 @@
1
+ value = 1
@@ -0,0 +1 @@
1
+ Extracts text from images
@@ -0,0 +1,2 @@
1
+ from pytesseract import image_to_string
2
+ image_to_string(img)
@@ -0,0 +1,2 @@
1
+ import pytesseract
2
+ pytesseract.image_to_string(img)
@@ -0,0 +1 @@
1
+ Extracts text from images
@@ -0,0 +1,2 @@
1
+ import easyocr
2
+ easyocr.Reader([])
@@ -0,0 +1,164 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+ from unittest.mock import patch
11
+ from ocr_claim_audit.audit import audit, claims, evidence
12
+ from ocr_claim_audit.__main__ import main
13
+ from ocr_claim_audit.phrases import OCR, NOOCR
14
+ from tests.cases import GOOD, BAD
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+
18
+ class AuditTests(unittest.TestCase):
19
+ def project(self, doc='Extracts text from images', code=None, name='app.py'):
20
+ temp = tempfile.TemporaryDirectory()
21
+ self.addCleanup(temp.cleanup)
22
+ root = Path(temp.name)
23
+ (root/'README.md').write_text(doc)
24
+ if code is not None:
25
+ path = root/name
26
+ path.parent.mkdir(parents=True, exist_ok=True)
27
+ path.write_text(code)
28
+ return root
29
+
30
+ def high(self, root, rule='documented-ocr-claim-false'):
31
+ result = audit(root)
32
+ self.assertEqual(result['verdict'], 'FAIL')
33
+ self.assertEqual(len(result['findings']), 1)
34
+ self.assertEqual(result['findings'][0]['severity'], 'HIGH')
35
+ self.assertEqual(result['findings'][0]['rule'], rule)
36
+
37
+ def test_22_testonly(self):
38
+ for name in ['tests/reader.py', 'test_reader.py', 'reader_test.py']:
39
+ with self.subTest(name=name):
40
+ root = self.project(code=GOOD[0], name=name)
41
+ result = audit(root)
42
+ self.assertEqual(result['verdict'], 'PASS')
43
+ self.assertEqual([f['severity'] for f in result['findings']], ['MEDIUM'])
44
+ self.assertEqual(audit(root, fail_on='MEDIUM')['verdict'], 'FAIL')
45
+
46
+ def test_23_negative(self):
47
+ self.high(self.project('No OCR', GOOD[0]), 'documented-no-ocr-claim-false')
48
+
49
+ def test_24_no_claim(self):
50
+ self.assertEqual(audit(self.project('Useful tool', GOOD[0]))['findings'], [])
51
+
52
+ def test_25_generation(self):
53
+ for doc in ['generates images from text', 'renders text as an image']:
54
+ self.assertEqual(audit(self.project(doc))['findings'], [])
55
+
56
+ def test_26_user(self):
57
+ self.assertEqual(audit(self.project('read the text yourself first'))['findings'], [])
58
+
59
+ def test_27_bare(self):
60
+ for doc in ['ocr', 'ocr settings', 'Camera capture', 'Image opening and resizing, thresholding, deskewing and file export']:
61
+ self.assertEqual(audit(self.project(doc))['findings'], [])
62
+
63
+ def test_28_fences(self):
64
+ for fence in ['```', '~~~~']:
65
+ self.assertEqual(claims(fence+'text\nExtracts text from images\n'+fence), (False, False))
66
+
67
+ def test_29_inline(self):
68
+ self.high(self.project('We `extract text from images`.'))
69
+
70
+ def test_30_negation(self):
71
+ self.assertEqual(claims("doesn't support ocr"), (False, True))
72
+ self.assertEqual(audit(self.project('does not support ocr'))['findings'], [])
73
+
74
+ def test_31_no_source(self):
75
+ self.high(self.project())
76
+ self.assertEqual(audit(self.project('No OCR'))['findings'], [])
77
+
78
+ def test_32_self(self):
79
+ self.assertEqual(claims((ROOT/'README.md').read_text()), (False, False))
80
+ self.assertEqual(audit(ROOT)['findings'], [])
81
+
82
+ def invoke(self, args):
83
+ out = io.StringIO()
84
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
85
+ code = main(args)
86
+ return code, out.getvalue()
87
+
88
+ def test_33_cli(self):
89
+ self.assertEqual(self.invoke(['--version']), (0, '0.1.0\n'))
90
+ root = self.project(code='x=1')
91
+ code, out = self.invoke([str(root), '--json'])
92
+ self.assertEqual(code, 2)
93
+ self.assertEqual(json.loads(out)['verdict'], 'FAIL')
94
+ self.assertEqual(self.invoke([str(root), '--ignore', 'README.md', '--verbose'])[0], 0)
95
+ self.assertEqual(self.invoke([str(root/'missing')])[0], 1)
96
+ self.assertEqual(self.invoke(['--invalid'])[0], 1)
97
+ proc = subprocess.run([sys.executable, '-m', 'ocr_claim_audit', '--version'], capture_output=True, text=True)
98
+ self.assertEqual((proc.returncode, proc.stdout.strip()), (0, '0.1.0'))
99
+
100
+ def test_34_packaging_and_env(self):
101
+ for file in ['pyproject.toml','MANIFEST.in','README.md','LICENSE','tests/fixtures/.env']:
102
+ self.assertTrue((ROOT/file).is_file())
103
+ self.assertIn('ocr-claim-audit = "ocr_claim_audit.__main__:main"', (ROOT/'pyproject.toml').read_text())
104
+ self.assertIn('MIT License', (ROOT/'LICENSE').read_text())
105
+ self.assertIn('recursive-include tests', (ROOT/'MANIFEST.in').read_text())
106
+ original = Path.read_text
107
+ def guarded(path, *args, **kwargs):
108
+ self.assertNotEqual(path.name, '.env')
109
+ return original(path, *args, **kwargs)
110
+ with patch.object(Path, 'read_text', guarded):
111
+ audit(ROOT)
112
+ for folder in ['ocr_claim_audit', 'tests']:
113
+ for path in (ROOT/folder).rglob('*.py'):
114
+ text = path.read_text()
115
+ self.assertIsNone(re.search(r'(?m)^\s*(?:\$\s*)?python\s', text))
116
+ self.assertIsNone(re.search(r'(?:AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{36})', text))
117
+
118
+ def test_additional_aliases_and_shadowing(self):
119
+ for module, function in [('pytesseract', 'image_to_boxes'), ('pytesseract', 'image_to_osd'), ('easyocr', 'Reader'), ('paddleocr', 'PaddleOCR'), ('rapidocr_openvino', 'RapidOCR'), ('rapidocr_torch', 'RapidOCR')]:
120
+ for code in [f'import {module} as provider\nprovider.{function}(img)', f'from {module} import {function} as run\nrun(img)']:
121
+ self.assertTrue(evidence(code), code)
122
+ self.assertFalse(evidence(f'from {module} import {function}\ndef {function}(*args): pass\n{function}(img)'))
123
+ for code in ['image_to_string(img)', 'readtext(img)', 'ocr(img)', 'engine(img)', 'import cv2\ncv2.imread(path)', 'import cv2\ncv2.resize(img,size)', 'import cv2\ncv2.cvtColor(img,0)', '@app.get("/")\ndef route(): pass', 'class PaddleOCR: pass\nPaddleOCR()', 'class RapidOCR: pass\nRapidOCR()', '# pytesseract.image_to_string(img)\n"easyocr.Reader()"']:
124
+ self.assertFalse(evidence(code), code)
125
+
126
+ def test_additional_scope(self):
127
+ for name in ['docs/a.py', 'examples/a.py', 'fixtures/a.py']:
128
+ self.high(self.project(code=GOOD[0], name=name))
129
+ root = self.project(code=GOOD[0], name='excluded.py')
130
+ self.assertEqual(audit(root)['verdict'], 'PASS')
131
+ self.assertEqual(audit(root, ['excluded.py'])['verdict'], 'FAIL')
132
+ (root/'excluded.py').unlink()
133
+ (root/'linked.py').symlink_to(ROOT/'tests/fixtures/good/app.py')
134
+ self.high(root)
135
+ root = self.project('Neutral', GOOD[0])
136
+ (root/'nested/docs').mkdir(parents=True)
137
+ (root/'nested/docs/guide.md').write_text('No OCR')
138
+ self.high(root, 'documented-no-ocr-claim-false')
139
+
140
+ def test_additional_normalization(self):
141
+ self.assertEqual(claims('EXTRACTS-TEXT\nFROM IMAGES'), (True, False))
142
+ self.assertEqual(claims('preextracts textually'), (False, False))
143
+ self.assertEqual(claims('No OCR. Also extracts text from images.'), (True, True))
144
+ self.assertEqual(len(audit(self.project('No OCR. Extracts text from images.', GOOD[0]))['findings']), 1)
145
+
146
+ for index, code in enumerate(GOOD, 1):
147
+ def test(self, code=code):
148
+ self.assertEqual(audit(self.project(code=code))['findings'], [])
149
+ setattr(AuditTests, 'test_%02d_good' % index, test)
150
+ for index, code in enumerate(BAD, 11):
151
+ def test(self, code=code):
152
+ self.high(self.project(code=code))
153
+ setattr(AuditTests, 'test_%02d_bad' % index, test)
154
+ for index, phrase in enumerate(OCR):
155
+ def test(self, phrase=phrase):
156
+ self.assertEqual(claims(phrase), (True, False))
157
+ self.high(self.project(phrase))
158
+ setattr(AuditTests, 'test_35_positive_%02d' % index, test)
159
+ for index, phrase in enumerate(NOOCR):
160
+ def test(self, phrase=phrase):
161
+ self.assertEqual(claims(phrase), (False, True))
162
+ self.assertEqual(audit(self.project(phrase))['findings'], [])
163
+ self.high(self.project(phrase, GOOD[0]), 'documented-no-ocr-claim-false')
164
+ setattr(AuditTests, 'test_35_negative_%02d' % index, test)