ragnaroq 0.0.4__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 (31) hide show
  1. ragnaroq-0.0.4/LICENSE +202 -0
  2. ragnaroq-0.0.4/PKG-INFO +200 -0
  3. ragnaroq-0.0.4/README.md +177 -0
  4. ragnaroq-0.0.4/pyproject.toml +42 -0
  5. ragnaroq-0.0.4/setup.cfg +4 -0
  6. ragnaroq-0.0.4/src/ragnaroq/__init__.py +10 -0
  7. ragnaroq-0.0.4/src/ragnaroq/cli.py +78 -0
  8. ragnaroq-0.0.4/src/ragnaroq/config.py +47 -0
  9. ragnaroq-0.0.4/src/ragnaroq/crosscheck.py +78 -0
  10. ragnaroq-0.0.4/src/ragnaroq/export/__init__.py +67 -0
  11. ragnaroq-0.0.4/src/ragnaroq/export/chunks.py +87 -0
  12. ragnaroq-0.0.4/src/ragnaroq/export/markdown.py +27 -0
  13. ragnaroq-0.0.4/src/ragnaroq/model.py +121 -0
  14. ragnaroq-0.0.4/src/ragnaroq/native.py +162 -0
  15. ragnaroq-0.0.4/src/ragnaroq/ocr/__init__.py +56 -0
  16. ragnaroq-0.0.4/src/ragnaroq/ocr/easyocr.py +87 -0
  17. ragnaroq-0.0.4/src/ragnaroq/ocr/tesseract.py +70 -0
  18. ragnaroq-0.0.4/src/ragnaroq/pipeline.py +223 -0
  19. ragnaroq-0.0.4/src/ragnaroq/policy.py +89 -0
  20. ragnaroq-0.0.4/src/ragnaroq/structure.py +63 -0
  21. ragnaroq-0.0.4/src/ragnaroq/validators/__init__.py +15 -0
  22. ragnaroq-0.0.4/src/ragnaroq/validators/dates.py +68 -0
  23. ragnaroq-0.0.4/src/ragnaroq/validators/encoding.py +25 -0
  24. ragnaroq-0.0.4/src/ragnaroq.egg-info/PKG-INFO +200 -0
  25. ragnaroq-0.0.4/src/ragnaroq.egg-info/SOURCES.txt +29 -0
  26. ragnaroq-0.0.4/src/ragnaroq.egg-info/dependency_links.txt +1 -0
  27. ragnaroq-0.0.4/src/ragnaroq.egg-info/entry_points.txt +2 -0
  28. ragnaroq-0.0.4/src/ragnaroq.egg-info/requires.txt +13 -0
  29. ragnaroq-0.0.4/src/ragnaroq.egg-info/top_level.txt +1 -0
  30. ragnaroq-0.0.4/tests/test_convert.py +264 -0
  31. ragnaroq-0.0.4/tests/test_rules.py +89 -0
ragnaroq-0.0.4/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: ragnaroq
3
+ Version: 0.0.4
4
+ Summary: Turn any PDF into LLM-readable, RAG-ready text with every line anchored to its source and a rule-based trust verdict.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/pTidke/ragnaroq
7
+ Project-URL: Roadmap, https://github.com/pTidke/ragnaroq/blob/main/docs/roadmap.md
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: pdfplumber<0.12,>=0.11
12
+ Requires-Dist: pypdf<7,>=6
13
+ Requires-Dist: pydantic<3,>=2.9
14
+ Requires-Dist: Pillow>=11
15
+ Provides-Extra: easyocr
16
+ Requires-Dist: easyocr<2,>=1.7; extra == "easyocr"
17
+ Requires-Dist: numpy; extra == "easyocr"
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=8; extra == "test"
20
+ Requires-Dist: reportlab>=4; extra == "test"
21
+ Requires-Dist: ruff>=0.6; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # RAGnaroq
25
+
26
+ **The end of bad RAG.** Point it at your files and get text a language model can trust: every line anchored to its place in the source, and judged before it is used.
27
+
28
+ Today it reads PDFs. The plan is any folder of files, ready for retrieval and served to any model over MCP ([roadmap](docs/roadmap.md)).
29
+
30
+ ```bash
31
+ pip install ragnaroq # with a Q. Not released yet: until then, install from this repository
32
+ ragnaroq convert notification.pdf --out out/
33
+ ```
34
+
35
+ ## RAG 'n' AROQ
36
+
37
+ In Old Norse, *ragna rök* is "the fate of the gods", and *rök* means fate, or judgement. Passing judgement on every line is what this tool is for. So: **RAG 'n' AROQ**, like rock 'n' roll. RAG, and the four jobs that make it trustworthy. That is why the name ends in Q: it is Ragnarök, spelt the way the fourth job reads.
38
+
39
+ | | Job | Norse name | Why the name fits |
40
+ | --- | --- | --- | --- |
41
+ | **A** | **Assess**: every line gets a verdict, *accepted*, *flagged* or *blocked*, by rules. | **The Norns** | Three Norns weave every fate at the roots of Yggdrasil. Three verdicts. |
42
+ | **R** | **Read**: the text layer, and later Word, Excel, PowerPoint, JSON, XML and more. | **Runes** | Odin hung nine nights on the world tree to learn to read the runes. |
43
+ | **O** | **OCR**: read what is only an image, with independent readers checking each other. | **Heimdall** | The watchman of the gods sees a hundred leagues, by night as well as by day. |
44
+ | **Q** | **Questions**: ask your folder and get answers that cite their lines. | **The Völva** | In the *Völuspá*, Odin questions a seeress, and her answer foretells Ragnarök itself. |
45
+
46
+ And around them:
47
+
48
+ | Name | Part | Why |
49
+ | --- | --- | --- |
50
+ | **Mímir** | `metadata.json`, the master file of what every document is and says | The keeper of the well of wisdom. Odin gave an eye for one drink. |
51
+ | **Huginn** | A local language model's second opinion (metadata, chunking plan) | Odin's raven of *thought*. |
52
+ | **Muninn** | The search index | Odin's raven of *memory*. |
53
+ | **Forseti** | The review screen, where a person settles what the readers disagree on | The god who settles every dispute. |
54
+ | **Bifröst** | The MCP server: the bridge from your folder to any model, local or on your server | The rainbow bridge between the worlds. |
55
+ | **Yggdrasil** | The `.ragnaroq/` folder that ties a processed folder together | The world tree that connects the nine worlds. |
56
+
57
+ Norse names are for the big parts; the plumbing has plain names (`ragnaroq.ocr`, `ragnaroq.policy`). Wherever a Norse name appears, its plain meaning appears with it.
58
+
59
+ ## How it reads a PDF
60
+
61
+ It is an extraction engine, not only OCR. Character recognition is one stage, used when a page has no usable text layer and as an independent check when it does.
62
+
63
+ ```
64
+ PDF ─▶ preflight ─▶ text layer + geometry ─▶ OCR (scan, or cross-check)
65
+ ─▶ rule validators ─▶ decision policy ─▶ structure
66
+ ─▶ document.json everything, with boxes, readings and flags
67
+ document.md for a language model to read
68
+ chunks.jsonl for a vector index, with citations
69
+ ```
70
+
71
+ The core uses no language model and makes no network call. Model stages planned on the roadmap are optional and local by default.
72
+
73
+ ## Status
74
+
75
+ This is a working skeleton: small, tested, and end to end. It was called `pdfanchor` until version 0.0.4. It grew out of a private extraction lab built for Indian tax documents, which still holds far more experience than this code does. `docs/porting-from-the-lab.md` lists what moves across and in what order.
76
+
77
+ The goal is wider than PDFs: point ragnaroq at a folder of any files and get a checked, described and indexed knowledge layer, served to any model through MCP. [docs/roadmap.md](docs/roadmap.md) sets out the stages, the principles and the milestones. [docs/chunking.md](docs/chunking.md) explains how the chunking strategy for each document is chosen from its metadata.
78
+
79
+ | Area | State |
80
+ | --- | --- |
81
+ | Output contract and JSON schema | Working, versioned `0.1.0` |
82
+ | Text-layer reading with line and table-cell boxes | Working |
83
+ | Scanned pages through Tesseract (command-line program) | Working, tested with the real program |
84
+ | Cross-check of the text layer against an OCR reading | Working |
85
+ | Validators: unmapped characters, malformed dates | Working |
86
+ | Decision policy: accepted / flagged / blocked, with rule ids | Working; **thresholds are not calibrated** |
87
+ | Markdown and chunk exporters | Working |
88
+ | EasyOCR as a second reader on scanned pages | Working, tested with the real models in CI; English only |
89
+ | Process isolation and resource limits per page | Not ported (lab: `runner.py`, `worker.py`) |
90
+ | Pinned, hash-checked OCR weights | Partly: EasyOCR checks its own MD5 sums; versions are not pinned yet |
91
+ | Scan recovery, rotation, show-through | Not ported |
92
+ | Table structure for scans; merged cells and header paths | Not ported |
93
+ | Large documents in page groups | Not built |
94
+ | Accuracy measured on reference pages | Not done; needed before trusting "accepted" |
95
+
96
+ ## Install and run
97
+
98
+ Python 3.12 or newer. For scanned pages, install the Tesseract program and the language data you need (`eng`, `hin`, …).
99
+
100
+ ```bash
101
+ pip install -e ".[test]"
102
+ ```
103
+
104
+ ```bash
105
+ ragnaroq convert notification.pdf --out out/
106
+ ```
107
+
108
+ ```bash
109
+ ragnaroq convert gazette.pdf --out out/ --lang eng+hin --exclude-script Deva
110
+ ```
111
+
112
+ A second reader for scanned pages, so lines that both readers agree on need no person:
113
+
114
+ ```bash
115
+ pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
116
+ pip install -e ".[easyocr]"
117
+ ragnaroq convert scan.pdf --out out/ --easyocr-models ~/easyocr-models --easyocr-download
118
+ ```
119
+
120
+ The models are fetched once into `--easyocr-models`; leave out `--easyocr-download` afterwards to stay offline. If they are missing, EasyOCR is left out at the start and Tesseract reads alone. EasyOCR confirms scanned pages only: a page with a text layer is cross-checked by the first engine (`Config.native_crosscheck_engines`). A confirming reader that fails on a page flags the page (`ocr.reader-failed`) and the first reader's lines stand.
121
+
122
+ Exit code `0` means every line was accepted by rule, `2` means the files were written and something needs a person, `1` means the file could not be processed.
123
+
124
+ ```python
125
+ from ragnaroq import Config, convert, write
126
+
127
+ document = convert("notification.pdf", config=Config(languages=("eng",)))
128
+ print(document.summary) # {'lines': 120, 'accepted': 112, 'flagged': 8, ...}
129
+ write(document, "out/")
130
+ ```
131
+
132
+ ## What comes out
133
+
134
+ **`document.json`** is the full record. For each page: its kind (`native`, `scanned`, `blank`, `failed`), and every line with its box in PDF points, the exact text the reader returned (`raw`), the NFC-normalised `text`, where it came from (`native` or `ocr:<engine>`), every other engine's reading of the same place, its `status`, and the `flags` that explain any status other than `accepted`. Tables keep every cell with its box; an empty reading is `null`, never a guessed blank.
135
+
136
+ **`document.md`** is Markdown in reading order. Headings become `##`, the lines of a paragraph are joined, tables become Markdown tables. Page breaks and review flags are HTML comments (`<!-- page 3 -->`, `<!-- flagged: date.ordinal-suffix -->`), so a model sees them without mistaking them for content.
137
+
138
+ **`chunks.jsonl`** has one JSON object per line:
139
+
140
+ | Field | Use |
141
+ | --- | --- |
142
+ | `embedding_text` | What to embed: the title and heading, then the text |
143
+ | `text` | What to show |
144
+ | `context` | Title and current heading |
145
+ | `pages`, `anchors` | Where it came from: page, bounding box and line ids, one anchor per page the chunk touches |
146
+ | `status`, `rules` | `accepted`, `flagged` or `blocked`, and the rules that fired. Filter on this |
147
+ | `sources` | `native`, `ocr:tesseract`, … |
148
+ | `id` | Stable for the same source file and lines |
149
+
150
+ A chunk never splits a paragraph and may run across a page break. A table is always its own chunk.
151
+
152
+ ## How it decides
153
+
154
+ Rules, in `policy.py`. Nothing is decided by engine confidence, because confidence is high on exactly the errors that matter (`31st` read as `31*`, `01st` read as `015`).
155
+
156
+ - A text-layer line is **accepted** when no validator objects and an independent OCR reading of the rendered page agrees with it: similar overall, and identical on every critical token (anything containing a digit, and negations).
157
+ - A scanned line is **accepted** when two engines agree by the same test.
158
+ - Anything else is **flagged** with the rule that caused it. Tables are always flagged.
159
+ - A page with ink and no way to read it is **blocked**. It is never silently empty.
160
+ - Text is never repaired. A flag says what looks wrong; the text stays as read.
161
+
162
+ Two switches loosen this when you have no second reader: `Policy.accept_native_without_crosscheck` and `Policy.accept_single_ocr_reading`. Both are off by default.
163
+
164
+ The thresholds are starting values. Until they are measured against human-verified pages, read "accepted" as "passed every rule", not as an accuracy figure.
165
+
166
+ ## Layout
167
+
168
+ ```
169
+ src/ragnaroq/
170
+ model.py output contract (pydantic) config.py settings and policy thresholds
171
+ native.py text layer, tables, rendering ocr/ engine interface and adapters
172
+ crosscheck.py compare two readings validators/ rule checks that raise flags
173
+ policy.py accepted / flagged / blocked structure.py scripts, headings, paragraphs
174
+ export/ markdown and chunks pipeline.py convert() and write()
175
+ cli.py
176
+ schemas/document.schema.json generated; a test keeps it in sync
177
+ tests/ synthetic PDFs only
178
+ ```
179
+
180
+ Adding an OCR engine means one class with `name`, `version()` and `read(image, languages)`. Adding a rule means one function from text to flags, listed in `validators/__init__.py`.
181
+
182
+ ## Development
183
+
184
+ ```bash
185
+ python -m pytest
186
+ ```
187
+
188
+ ```bash
189
+ ruff check .
190
+ ```
191
+
192
+ After changing `model.py`, regenerate the schema:
193
+
194
+ ```bash
195
+ ragnaroq schema > schemas/document.schema.json
196
+ ```
197
+
198
+ ## Licence
199
+
200
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,177 @@
1
+ # RAGnaroq
2
+
3
+ **The end of bad RAG.** Point it at your files and get text a language model can trust: every line anchored to its place in the source, and judged before it is used.
4
+
5
+ Today it reads PDFs. The plan is any folder of files, ready for retrieval and served to any model over MCP ([roadmap](docs/roadmap.md)).
6
+
7
+ ```bash
8
+ pip install ragnaroq # with a Q. Not released yet: until then, install from this repository
9
+ ragnaroq convert notification.pdf --out out/
10
+ ```
11
+
12
+ ## RAG 'n' AROQ
13
+
14
+ In Old Norse, *ragna rök* is "the fate of the gods", and *rök* means fate, or judgement. Passing judgement on every line is what this tool is for. So: **RAG 'n' AROQ**, like rock 'n' roll. RAG, and the four jobs that make it trustworthy. That is why the name ends in Q: it is Ragnarök, spelt the way the fourth job reads.
15
+
16
+ | | Job | Norse name | Why the name fits |
17
+ | --- | --- | --- | --- |
18
+ | **A** | **Assess**: every line gets a verdict, *accepted*, *flagged* or *blocked*, by rules. | **The Norns** | Three Norns weave every fate at the roots of Yggdrasil. Three verdicts. |
19
+ | **R** | **Read**: the text layer, and later Word, Excel, PowerPoint, JSON, XML and more. | **Runes** | Odin hung nine nights on the world tree to learn to read the runes. |
20
+ | **O** | **OCR**: read what is only an image, with independent readers checking each other. | **Heimdall** | The watchman of the gods sees a hundred leagues, by night as well as by day. |
21
+ | **Q** | **Questions**: ask your folder and get answers that cite their lines. | **The Völva** | In the *Völuspá*, Odin questions a seeress, and her answer foretells Ragnarök itself. |
22
+
23
+ And around them:
24
+
25
+ | Name | Part | Why |
26
+ | --- | --- | --- |
27
+ | **Mímir** | `metadata.json`, the master file of what every document is and says | The keeper of the well of wisdom. Odin gave an eye for one drink. |
28
+ | **Huginn** | A local language model's second opinion (metadata, chunking plan) | Odin's raven of *thought*. |
29
+ | **Muninn** | The search index | Odin's raven of *memory*. |
30
+ | **Forseti** | The review screen, where a person settles what the readers disagree on | The god who settles every dispute. |
31
+ | **Bifröst** | The MCP server: the bridge from your folder to any model, local or on your server | The rainbow bridge between the worlds. |
32
+ | **Yggdrasil** | The `.ragnaroq/` folder that ties a processed folder together | The world tree that connects the nine worlds. |
33
+
34
+ Norse names are for the big parts; the plumbing has plain names (`ragnaroq.ocr`, `ragnaroq.policy`). Wherever a Norse name appears, its plain meaning appears with it.
35
+
36
+ ## How it reads a PDF
37
+
38
+ It is an extraction engine, not only OCR. Character recognition is one stage, used when a page has no usable text layer and as an independent check when it does.
39
+
40
+ ```
41
+ PDF ─▶ preflight ─▶ text layer + geometry ─▶ OCR (scan, or cross-check)
42
+ ─▶ rule validators ─▶ decision policy ─▶ structure
43
+ ─▶ document.json everything, with boxes, readings and flags
44
+ document.md for a language model to read
45
+ chunks.jsonl for a vector index, with citations
46
+ ```
47
+
48
+ The core uses no language model and makes no network call. Model stages planned on the roadmap are optional and local by default.
49
+
50
+ ## Status
51
+
52
+ This is a working skeleton: small, tested, and end to end. It was called `pdfanchor` until version 0.0.4. It grew out of a private extraction lab built for Indian tax documents, which still holds far more experience than this code does. `docs/porting-from-the-lab.md` lists what moves across and in what order.
53
+
54
+ The goal is wider than PDFs: point ragnaroq at a folder of any files and get a checked, described and indexed knowledge layer, served to any model through MCP. [docs/roadmap.md](docs/roadmap.md) sets out the stages, the principles and the milestones. [docs/chunking.md](docs/chunking.md) explains how the chunking strategy for each document is chosen from its metadata.
55
+
56
+ | Area | State |
57
+ | --- | --- |
58
+ | Output contract and JSON schema | Working, versioned `0.1.0` |
59
+ | Text-layer reading with line and table-cell boxes | Working |
60
+ | Scanned pages through Tesseract (command-line program) | Working, tested with the real program |
61
+ | Cross-check of the text layer against an OCR reading | Working |
62
+ | Validators: unmapped characters, malformed dates | Working |
63
+ | Decision policy: accepted / flagged / blocked, with rule ids | Working; **thresholds are not calibrated** |
64
+ | Markdown and chunk exporters | Working |
65
+ | EasyOCR as a second reader on scanned pages | Working, tested with the real models in CI; English only |
66
+ | Process isolation and resource limits per page | Not ported (lab: `runner.py`, `worker.py`) |
67
+ | Pinned, hash-checked OCR weights | Partly: EasyOCR checks its own MD5 sums; versions are not pinned yet |
68
+ | Scan recovery, rotation, show-through | Not ported |
69
+ | Table structure for scans; merged cells and header paths | Not ported |
70
+ | Large documents in page groups | Not built |
71
+ | Accuracy measured on reference pages | Not done; needed before trusting "accepted" |
72
+
73
+ ## Install and run
74
+
75
+ Python 3.12 or newer. For scanned pages, install the Tesseract program and the language data you need (`eng`, `hin`, …).
76
+
77
+ ```bash
78
+ pip install -e ".[test]"
79
+ ```
80
+
81
+ ```bash
82
+ ragnaroq convert notification.pdf --out out/
83
+ ```
84
+
85
+ ```bash
86
+ ragnaroq convert gazette.pdf --out out/ --lang eng+hin --exclude-script Deva
87
+ ```
88
+
89
+ A second reader for scanned pages, so lines that both readers agree on need no person:
90
+
91
+ ```bash
92
+ pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
93
+ pip install -e ".[easyocr]"
94
+ ragnaroq convert scan.pdf --out out/ --easyocr-models ~/easyocr-models --easyocr-download
95
+ ```
96
+
97
+ The models are fetched once into `--easyocr-models`; leave out `--easyocr-download` afterwards to stay offline. If they are missing, EasyOCR is left out at the start and Tesseract reads alone. EasyOCR confirms scanned pages only: a page with a text layer is cross-checked by the first engine (`Config.native_crosscheck_engines`). A confirming reader that fails on a page flags the page (`ocr.reader-failed`) and the first reader's lines stand.
98
+
99
+ Exit code `0` means every line was accepted by rule, `2` means the files were written and something needs a person, `1` means the file could not be processed.
100
+
101
+ ```python
102
+ from ragnaroq import Config, convert, write
103
+
104
+ document = convert("notification.pdf", config=Config(languages=("eng",)))
105
+ print(document.summary) # {'lines': 120, 'accepted': 112, 'flagged': 8, ...}
106
+ write(document, "out/")
107
+ ```
108
+
109
+ ## What comes out
110
+
111
+ **`document.json`** is the full record. For each page: its kind (`native`, `scanned`, `blank`, `failed`), and every line with its box in PDF points, the exact text the reader returned (`raw`), the NFC-normalised `text`, where it came from (`native` or `ocr:<engine>`), every other engine's reading of the same place, its `status`, and the `flags` that explain any status other than `accepted`. Tables keep every cell with its box; an empty reading is `null`, never a guessed blank.
112
+
113
+ **`document.md`** is Markdown in reading order. Headings become `##`, the lines of a paragraph are joined, tables become Markdown tables. Page breaks and review flags are HTML comments (`<!-- page 3 -->`, `<!-- flagged: date.ordinal-suffix -->`), so a model sees them without mistaking them for content.
114
+
115
+ **`chunks.jsonl`** has one JSON object per line:
116
+
117
+ | Field | Use |
118
+ | --- | --- |
119
+ | `embedding_text` | What to embed: the title and heading, then the text |
120
+ | `text` | What to show |
121
+ | `context` | Title and current heading |
122
+ | `pages`, `anchors` | Where it came from: page, bounding box and line ids, one anchor per page the chunk touches |
123
+ | `status`, `rules` | `accepted`, `flagged` or `blocked`, and the rules that fired. Filter on this |
124
+ | `sources` | `native`, `ocr:tesseract`, … |
125
+ | `id` | Stable for the same source file and lines |
126
+
127
+ A chunk never splits a paragraph and may run across a page break. A table is always its own chunk.
128
+
129
+ ## How it decides
130
+
131
+ Rules, in `policy.py`. Nothing is decided by engine confidence, because confidence is high on exactly the errors that matter (`31st` read as `31*`, `01st` read as `015`).
132
+
133
+ - A text-layer line is **accepted** when no validator objects and an independent OCR reading of the rendered page agrees with it: similar overall, and identical on every critical token (anything containing a digit, and negations).
134
+ - A scanned line is **accepted** when two engines agree by the same test.
135
+ - Anything else is **flagged** with the rule that caused it. Tables are always flagged.
136
+ - A page with ink and no way to read it is **blocked**. It is never silently empty.
137
+ - Text is never repaired. A flag says what looks wrong; the text stays as read.
138
+
139
+ Two switches loosen this when you have no second reader: `Policy.accept_native_without_crosscheck` and `Policy.accept_single_ocr_reading`. Both are off by default.
140
+
141
+ The thresholds are starting values. Until they are measured against human-verified pages, read "accepted" as "passed every rule", not as an accuracy figure.
142
+
143
+ ## Layout
144
+
145
+ ```
146
+ src/ragnaroq/
147
+ model.py output contract (pydantic) config.py settings and policy thresholds
148
+ native.py text layer, tables, rendering ocr/ engine interface and adapters
149
+ crosscheck.py compare two readings validators/ rule checks that raise flags
150
+ policy.py accepted / flagged / blocked structure.py scripts, headings, paragraphs
151
+ export/ markdown and chunks pipeline.py convert() and write()
152
+ cli.py
153
+ schemas/document.schema.json generated; a test keeps it in sync
154
+ tests/ synthetic PDFs only
155
+ ```
156
+
157
+ Adding an OCR engine means one class with `name`, `version()` and `read(image, languages)`. Adding a rule means one function from text to flags, listed in `validators/__init__.py`.
158
+
159
+ ## Development
160
+
161
+ ```bash
162
+ python -m pytest
163
+ ```
164
+
165
+ ```bash
166
+ ruff check .
167
+ ```
168
+
169
+ After changing `model.py`, regenerate the schema:
170
+
171
+ ```bash
172
+ ragnaroq schema > schemas/document.schema.json
173
+ ```
174
+
175
+ ## Licence
176
+
177
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=80"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ragnaroq"
7
+ version = "0.0.4"
8
+ description = "Turn any PDF into LLM-readable, RAG-ready text with every line anchored to its source and a rule-based trust verdict."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ dependencies = [
14
+ "pdfplumber>=0.11,<0.12",
15
+ "pypdf>=6,<7",
16
+ "pydantic>=2.9,<3",
17
+ "Pillow>=11",
18
+ ]
19
+
20
+ [project.urls]
21
+ Repository = "https://github.com/pTidke/ragnaroq"
22
+ Roadmap = "https://github.com/pTidke/ragnaroq/blob/main/docs/roadmap.md"
23
+
24
+ [project.optional-dependencies]
25
+ easyocr = ["easyocr>=1.7,<2", "numpy"]
26
+ test = ["pytest>=8", "reportlab>=4", "ruff>=0.6"]
27
+
28
+ [project.scripts]
29
+ ragnaroq = "ragnaroq.cli:main"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
36
+
37
+ [tool.ruff]
38
+ target-version = "py312"
39
+ line-length = 110
40
+
41
+ [tool.ruff.lint]
42
+ select = ["E4", "E7", "E9", "F", "I", "B", "UP"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,10 @@
1
+ """ragnaroq: turn any PDF into text a language model or a vector index can use, with every
2
+ line anchored to its place on the page and a rule-based verdict on whether to trust it."""
3
+
4
+ __version__ = "0.0.4"
5
+
6
+ from .config import Config, Policy # noqa: E402
7
+ from .model import Document # noqa: E402
8
+ from .pipeline import ConversionError, convert, write # noqa: E402
9
+
10
+ __all__ = ["Config", "ConversionError", "Document", "Policy", "convert", "write", "__version__"]