varga 0.0.1__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.
varga-0.0.1/.gitignore ADDED
@@ -0,0 +1,165 @@
1
+ _docs/
2
+ _proc/
3
+
4
+ *.bak
5
+ .gitattributes
6
+ .last_checked
7
+ .gitconfig
8
+ *.bak
9
+ *.log
10
+ *~
11
+ ~*
12
+ _tmp*
13
+ tmp*
14
+ tags
15
+ *.pkg
16
+
17
+ # Byte-compiled / optimized / DLL files
18
+ __pycache__/
19
+ *.py[cod]
20
+ *$py.class
21
+
22
+ # C extensions
23
+ *.so
24
+
25
+ # Distribution / packaging
26
+ .Python
27
+ env/
28
+ build/
29
+ conda/
30
+ develop-eggs/
31
+ dist/
32
+ downloads/
33
+ eggs/
34
+ .eggs/
35
+ lib/
36
+ lib64/
37
+ parts/
38
+ sdist/
39
+ var/
40
+ wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+
45
+ # PyInstaller
46
+ # Usually these files are written by a python script from a template
47
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
48
+ *.manifest
49
+ *.spec
50
+
51
+ # Installer logs
52
+ pip-log.txt
53
+ pip-delete-this-directory.txt
54
+
55
+ # Unit test / coverage reports
56
+ htmlcov/
57
+ .tox/
58
+ .coverage
59
+ .coverage.*
60
+ .cache
61
+ nosetests.xml
62
+ coverage.xml
63
+ *.cover
64
+ .hypothesis/
65
+
66
+ # Translations
67
+ *.mo
68
+ *.pot
69
+
70
+ # Django stuff:
71
+ *.log
72
+ local_settings.py
73
+
74
+ # Flask stuff:
75
+ instance/
76
+ .webassets-cache
77
+
78
+ # Scrapy stuff:
79
+ .scrapy
80
+
81
+ # Sphinx documentation
82
+ docs/_build/
83
+
84
+ # PyBuilder
85
+ target/
86
+
87
+ # Jupyter Notebook
88
+ .ipynb_checkpoints
89
+
90
+ # pyenv
91
+ .python-version
92
+
93
+ # celery beat schedule file
94
+ celerybeat-schedule
95
+
96
+ # SageMath parsed files
97
+ *.sage.py
98
+
99
+ # dotenv
100
+ .env
101
+
102
+ # virtualenv
103
+ .venv
104
+ venv/
105
+ ENV/
106
+
107
+ # Spyder project settings
108
+ .spyderproject
109
+ .spyproject
110
+
111
+ # Rope project settings
112
+ .ropeproject
113
+
114
+ # mkdocs documentation
115
+ /site
116
+
117
+ # mypy
118
+ .mypy_cache/
119
+
120
+ .vscode
121
+ *.swp
122
+
123
+ # osx generated files
124
+ .DS_Store
125
+ .DS_Store?
126
+ .Trashes
127
+ ehthumbs.db
128
+ Thumbs.db
129
+ .idea
130
+
131
+ # pytest
132
+ .pytest_cache
133
+
134
+ # tools/trust-doc-nbs
135
+ docs_src/.last_checked
136
+
137
+ # symlinks to fastai
138
+ docs_src/fastai
139
+ tools/fastai
140
+
141
+ # link checker
142
+ checklink/cookies.txt
143
+
144
+ # .gitconfig is now autogenerated
145
+ .gitconfig
146
+
147
+ # Quarto installer
148
+ .deb
149
+ .pkg
150
+
151
+ # Quarto
152
+ .quarto
153
+
154
+ # local vault + extracted assets
155
+ *.db
156
+ *.usearch
157
+ # ...except the recorded model replies the notebook tests replay in CI. The sqlite side files are
158
+ # transient, so they stay ignored.
159
+ !nbs/chatcache/cache.db
160
+ nbs/chatcache/*.db-wal
161
+ nbs/chatcache/*.db-shm
162
+ pdfs/
163
+ assets/
164
+ .venv/
165
+ .kosha/
varga-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
varga-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: varga
3
+ Version: 0.0.1
4
+ Summary: what kind of thing a document is, and the fields it holds: cue-scored doctypes and schema-constrained extraction
5
+ Project-URL: Repository, https://github.com/vedicreader/varga
6
+ Project-URL: Documentation, https://vedicreader.github.io/varga/
7
+ Author-email: Karthik <karthik.rajgopal@hotmail.com>
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: doctype,document classification,information extraction,invoice,nbdev,schema,structured output
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Text Processing
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: fastcore>=1.12.31
21
+ Requires-Dist: rahasya>=0.0.1
22
+ Provides-Extra: keyphrase
23
+ Requires-Dist: litesearch>=0.1.25; extra == 'keyphrase'
24
+ Provides-Extra: llm
25
+ Requires-Dist: rishi>=0.1.2; extra == 'llm'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # varga
29
+
30
+
31
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
32
+
33
+ Two questions about one document. [`guess_type`](https://vedicreader.github.io/varga/core.html#guess_type) answers the first from cue phrases and
34
+ countable evidence, with no model unless two kinds tie. [`as_schema`](https://vedicreader.github.io/varga/schema.html#as_schema) and [`structured`](https://vedicreader.github.io/varga/schema.html#structured) answer the
35
+ second against a shape you name or invent.
36
+
37
+ ## Install
38
+
39
+ ``` sh
40
+ uv add varga # doctypes; no model, no network
41
+ uv add 'varga[llm]' # ...and `structured`, which asks one
42
+ ```
43
+
44
+ ## What is it
45
+
46
+ ``` python
47
+ INVOICE = '''# INVOICE
48
+ Invoice No: ACM-2024-0117
49
+ Date: 2024-03-01
50
+ Bill to: Contoso GmbH, Berlin
51
+ From: Acme Supplies Ltd
52
+ Total due: 1,240.00 EUR
53
+ Payment terms: net 30
54
+ '''
55
+ r = guess_type(INVOICE)
56
+ r.doctype, r.decisive, round(r.margin, 2)
57
+ ```
58
+
59
+ ('invoice', True, 0.4)
60
+
61
+ `decisive` is the whole point: it says whether the cues settled it. When two kinds tie,
62
+ `margin` is 0 and a caller knows to spend a model call. Nothing else here costs one.
63
+
64
+ ``` python
65
+ signals(INVOICE).counts
66
+ ```
67
+
68
+ {'money': 1, 'date': 1, 'ref': 1, 'heading': 1, 'org': 2}
69
+
70
+ ## What is in it
71
+
72
+ ``` python
73
+ from dataclasses import fields
74
+ [f.name for f in fields(as_schema('invoice'))]
75
+ ```
76
+
77
+ ['number',
78
+ 'date',
79
+ 'due_date',
80
+ 'vendor',
81
+ 'vendor_tax_id',
82
+ 'bill_to',
83
+ 'ship_to',
84
+ 'currency',
85
+ 'subtotal',
86
+ 'tax',
87
+ 'total',
88
+ 'payment_terms',
89
+ 'items']
90
+
91
+ Ten shapes are built in: `invoice`, `purchase_order`, `quote`, `receipt`, `catalogue`,
92
+ `contract`, `resume`, `paper`, `meeting_notes`, `other`. Or write one on the spot:
93
+
94
+ ``` python
95
+ [(f.name, f.type.__name__) for f in fields(as_schema('vendor:str, total:float, items:list'))]
96
+ ```
97
+
98
+ [('vendor', 'str'), ('total', 'float'), ('items', 'list')]
99
+
100
+ `structured(chat, prompt, schema)` fills it. It prefers the model’s constrained mode and
101
+ falls back to a JSON reply when that raises, so a model without tool calling still answers.
102
+
103
+ ## The doctypes
104
+
105
+ ``` python
106
+ len(DOCTYPES), sorted(DOCTYPES)
107
+ ```
108
+
109
+ Ten of them are work-product labels — `proposal`, `presentation`, `requirements_spec`,
110
+ `technical_design`, `regulatory_guidance`, `procedure`, `qa_artifact`, `roadmap`, `claim`,
111
+ `clinical_record` — and each is decisive on its own text without a model. Prose that merely
112
+ borrows the vocabulary scores under 0.2 against every one of them.
113
+
114
+ ## What it depends on
115
+
116
+ `fastcore` and [rahasya](https://github.com/vedicreader/rahasya), for the honorific-anchored
117
+ name regex the entity leg shares with the privacy gate. One definition of what a name is.
118
+
119
+ `rishi` is needed only by [`structured`](https://vedicreader.github.io/varga/schema.html#structured). `litesearch` adds keyphrases to `signals().ents` and is
120
+ display only: no doctype score reads them, and [`signals`](https://vedicreader.github.io/varga/core.html#signals) works without it.
121
+
122
+ ## Development
123
+
124
+ The notebooks in `nbs/` are the source; the modules are generated.
125
+
126
+ ``` sh
127
+ pip install -e .
128
+ nbdev_prepare
129
+ ```
varga-0.0.1/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # varga
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ Two questions about one document. [`guess_type`](https://vedicreader.github.io/varga/core.html#guess_type) answers the first from cue phrases and
7
+ countable evidence, with no model unless two kinds tie. [`as_schema`](https://vedicreader.github.io/varga/schema.html#as_schema) and [`structured`](https://vedicreader.github.io/varga/schema.html#structured) answer the
8
+ second against a shape you name or invent.
9
+
10
+ ## Install
11
+
12
+ ``` sh
13
+ uv add varga # doctypes; no model, no network
14
+ uv add 'varga[llm]' # ...and `structured`, which asks one
15
+ ```
16
+
17
+ ## What is it
18
+
19
+ ``` python
20
+ INVOICE = '''# INVOICE
21
+ Invoice No: ACM-2024-0117
22
+ Date: 2024-03-01
23
+ Bill to: Contoso GmbH, Berlin
24
+ From: Acme Supplies Ltd
25
+ Total due: 1,240.00 EUR
26
+ Payment terms: net 30
27
+ '''
28
+ r = guess_type(INVOICE)
29
+ r.doctype, r.decisive, round(r.margin, 2)
30
+ ```
31
+
32
+ ('invoice', True, 0.4)
33
+
34
+ `decisive` is the whole point: it says whether the cues settled it. When two kinds tie,
35
+ `margin` is 0 and a caller knows to spend a model call. Nothing else here costs one.
36
+
37
+ ``` python
38
+ signals(INVOICE).counts
39
+ ```
40
+
41
+ {'money': 1, 'date': 1, 'ref': 1, 'heading': 1, 'org': 2}
42
+
43
+ ## What is in it
44
+
45
+ ``` python
46
+ from dataclasses import fields
47
+ [f.name for f in fields(as_schema('invoice'))]
48
+ ```
49
+
50
+ ['number',
51
+ 'date',
52
+ 'due_date',
53
+ 'vendor',
54
+ 'vendor_tax_id',
55
+ 'bill_to',
56
+ 'ship_to',
57
+ 'currency',
58
+ 'subtotal',
59
+ 'tax',
60
+ 'total',
61
+ 'payment_terms',
62
+ 'items']
63
+
64
+ Ten shapes are built in: `invoice`, `purchase_order`, `quote`, `receipt`, `catalogue`,
65
+ `contract`, `resume`, `paper`, `meeting_notes`, `other`. Or write one on the spot:
66
+
67
+ ``` python
68
+ [(f.name, f.type.__name__) for f in fields(as_schema('vendor:str, total:float, items:list'))]
69
+ ```
70
+
71
+ [('vendor', 'str'), ('total', 'float'), ('items', 'list')]
72
+
73
+ `structured(chat, prompt, schema)` fills it. It prefers the model’s constrained mode and
74
+ falls back to a JSON reply when that raises, so a model without tool calling still answers.
75
+
76
+ ## The doctypes
77
+
78
+ ``` python
79
+ len(DOCTYPES), sorted(DOCTYPES)
80
+ ```
81
+
82
+ Ten of them are work-product labels — `proposal`, `presentation`, `requirements_spec`,
83
+ `technical_design`, `regulatory_guidance`, `procedure`, `qa_artifact`, `roadmap`, `claim`,
84
+ `clinical_record` — and each is decisive on its own text without a model. Prose that merely
85
+ borrows the vocabulary scores under 0.2 against every one of them.
86
+
87
+ ## What it depends on
88
+
89
+ `fastcore` and [rahasya](https://github.com/vedicreader/rahasya), for the honorific-anchored
90
+ name regex the entity leg shares with the privacy gate. One definition of what a name is.
91
+
92
+ `rishi` is needed only by [`structured`](https://vedicreader.github.io/varga/schema.html#structured). `litesearch` adds keyphrases to `signals().ents` and is
93
+ display only: no doctype score reads them, and [`signals`](https://vedicreader.github.io/varga/core.html#signals) works without it.
94
+
95
+ ## Development
96
+
97
+ The notebooks in `nbs/` are the source; the modules are generated.
98
+
99
+ ``` sh
100
+ pip install -e .
101
+ nbdev_prepare
102
+ ```
@@ -0,0 +1,55 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "varga"
7
+ dynamic = ["version"]
8
+ description = "what kind of thing a document is, and the fields it holds: cue-scored doctypes and schema-constrained extraction"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "Karthik", email = "karthik.rajgopal@hotmail.com"}]
13
+ keywords = ['nbdev', 'document classification', 'information extraction', 'structured output',
14
+ 'invoice', 'doctype', 'schema']
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Text Processing",
24
+ ]
25
+ dependencies = [
26
+ "fastcore>=1.12.31",
27
+ "rahasya>=0.0.1",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ # `structured` needs a model to ask; `signals` and `guess_type` need neither
32
+ llm = ["rishi>=0.1.2"]
33
+ # keyphrases in `signals().ents`; display only, no doctype depends on them
34
+ keyphrase = ["litesearch>=0.1.25"]
35
+
36
+ [project.urls]
37
+ Repository = "https://github.com/vedicreader/varga"
38
+ Documentation = "https://vedicreader.github.io/varga/"
39
+
40
+ [project.entry-points.nbdev]
41
+ varga = "varga._modidx:d"
42
+
43
+ [tool.nbdev]
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["varga"]
47
+
48
+ [tool.hatch.build.targets.sdist]
49
+ include = ["/varga", "/README.md", "/pyproject.toml"]
50
+
51
+ [tool.hatch.version]
52
+ path = "varga/__init__.py"
53
+
54
+ [dependency-groups]
55
+ dev = ["ipykernel>=7.3.0", "nbdev>=3.3.4", "notebook>=7.6.1", "rishi>=0.1.2", "litesearch>=0.1.25"]
@@ -0,0 +1,3 @@
1
+ __version__ = "0.0.1"
2
+ from .core import *
3
+ from .schema import *
@@ -0,0 +1,27 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/varga',
5
+ 'doc_host': 'https://vedicreader.github.io',
6
+ 'git_url': 'https://github.com/vedicreader/varga',
7
+ 'lib_path': 'varga'},
8
+ 'syms': { 'varga.core': { 'varga.core._keyphrases': ('core.html#_keyphrases', 'varga/core.py'),
9
+ 'varga.core._noun_ents': ('core.html#_noun_ents', 'varga/core.py'),
10
+ 'varga.core.cue_scores': ('core.html#cue_scores', 'varga/core.py'),
11
+ 'varga.core.guess_type': ('core.html#guess_type', 'varga/core.py'),
12
+ 'varga.core.signals': ('core.html#signals', 'varga/core.py')},
13
+ 'varga.schema': { 'varga.schema.Catalogue': ('schema.html#catalogue', 'varga/schema.py'),
14
+ 'varga.schema.Contract': ('schema.html#contract', 'varga/schema.py'),
15
+ 'varga.schema.Invoice': ('schema.html#invoice', 'varga/schema.py'),
16
+ 'varga.schema.MeetingNotes': ('schema.html#meetingnotes', 'varga/schema.py'),
17
+ 'varga.schema.Paper': ('schema.html#paper', 'varga/schema.py'),
18
+ 'varga.schema.Receipt': ('schema.html#receipt', 'varga/schema.py'),
19
+ 'varga.schema.Resume': ('schema.html#resume', 'varga/schema.py'),
20
+ 'varga.schema.Summary': ('schema.html#summary', 'varga/schema.py'),
21
+ 'varga.schema._json_reply': ('schema.html#_json_reply', 'varga/schema.py'),
22
+ 'varga.schema._norm': ('schema.html#_norm', 'varga/schema.py'),
23
+ 'varga.schema._split_reasoning': ('schema.html#_split_reasoning', 'varga/schema.py'),
24
+ 'varga.schema.as_schema': ('schema.html#as_schema', 'varga/schema.py'),
25
+ 'varga.schema.dyn_schema': ('schema.html#dyn_schema', 'varga/schema.py'),
26
+ 'varga.schema.schema_str': ('schema.html#schema_str', 'varga/schema.py'),
27
+ 'varga.schema.structured': ('schema.html#structured', 'varga/schema.py')}}}
@@ -0,0 +1,265 @@
1
+ """what kind of thing a document is, decided by cues before a model is asked
2
+
3
+ Docs: https://vedicreader.github.io/varga/core.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['SIGNALS', 'DOCTYPES', 'KIND_HINT', 'MIN_SCORE', 'MIN_MARGIN', 'KIND_BONUS', 'signals', 'cue_scores', 'guess_type']
9
+
10
+ # %% ../nbs/00_core.ipynb #50d7feae
11
+ import re
12
+ from collections import Counter
13
+ from fastcore.all import AttrDict, L
14
+ from rahasya import NER_CHARS, PERSON_HON
15
+
16
+ # %% ../nbs/00_core.ipynb #15f3fd04
17
+ SIGNALS = dict(
18
+ # what a document *contains*, as cheaply as a regex can tell: the evidence a type is scored on
19
+ money = r'[$€£¥₹]\s?\d[\d,]*(?:\.\d+)?|\b\d[\d,]*\.\d{2}\s?(?:usd|eur|gbp|inr|jpy|cad|aud)\b'
20
+ r'|\b(?:usd|eur|gbp|inr|jpy|cad|aud)\s?\d[\d,]*',
21
+ date = r'\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\b'
22
+ r'|\b\d{1,2} (?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]* \d{2,4}\b'
23
+ r'|\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]* \d{1,2},? \d{4}\b',
24
+ time = r'\b\d{1,2}:\d{2}(?::\d{2})?\s?(?:am|pm)?\b',
25
+ ref = r'\b(?:invoice|inv|order|p\.?o|ref(?:erence)?|receipt|bill|account|sku|part|item)\s*'
26
+ r'(?:no\.?|number|id)?\s*[:#]\s*[a-z0-9][a-z0-9\-/]{2,}\b',
27
+ qty = r'\b(?:qty|quantity|units?|pcs?|nos?)\b\s*[:.]?\s*\d+|\b\d+\s?(?:x|×)\s?\d',
28
+ percent = r'\b\d{1,3}(?:\.\d+)?\s?%',
29
+ tax = r'\b(?:vat|gst|hsn|sac|tin|ein|abn|sales tax|tax id|withholding)\b',
30
+ email = r'\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b',
31
+ url = r'https?://\S+',
32
+ citation = r'\[\d+\]|\bet al\.|\bdoi:|\barxiv:',
33
+ code = r'^\s*(?:def|class|function|const|let|var|import|from|package|#include)\s+\w',
34
+ table = r'^\s*\|.+\|\s*$',
35
+ heading = r'^#{1,6} \S',
36
+ blank = r'_{4,}|\[ ?\]',
37
+ )
38
+ _SIG = {k: re.compile(v, re.I|re.M) for k, v in SIGNALS.items()}
39
+ # entity extraction runs on the head of a document (`NER_CHARS`, from rahasya): that is where
40
+ # its type is decided
41
+
42
+ # handrolled entity extraction: ORG by legal suffix, PERSON by honorific, LAW by instrument type
43
+ _ORG_SUFF = re.compile(
44
+ r'(?<![a-z,\.])([A-Z][A-Za-z0-9\'\-& ]{1,50}?)\s+'
45
+ r'(?:Ltd\.?|Limited|Corp\.?|Corporation|Inc\.?|LLC|LLP|GmbH|AG|SA|NV|BV|Pty\.?|PLC'
46
+ r'|Group\b|Holdings?\b|Associates?\b|Partners?\b|Ventures?\b'
47
+ r'|University\b|College\b|Institute\b|Hospital\b|Foundation\b'
48
+ r'|Bank\b|Fund\b|Trust\b|Council\b|Authority\b|Commission\b'
49
+ r'|Ministry\b|Department\b|Agency\b|Bureau\b)\b'
50
+ )
51
+ # the PERSON arm is rahasya's, so a name means the same thing to the doctype scorer and to the
52
+ # privacy gate. One regex, measured once.
53
+ _PERSON_HON = PERSON_HON
54
+ _LAW_INST = re.compile(
55
+ r'\b([A-Z][A-Za-z ]{2,50}?)\s+'
56
+ r'(?:Act(?:\s+\d{4})?|Regulations?\b|Directive\b|Ordinance\b|Statute\b|Treaty\b|Convention\b|Amendment\b)'
57
+ )
58
+
59
+ # %% ../nbs/00_core.ipynb #b9d6a10c
60
+ def _noun_ents(text:str, limit:int=40) -> L:
61
+ 'ORG, PERSON and LAW entities via regex; no model weight.'
62
+ seen, out = set(), L()
63
+ def _add(t, label):
64
+ n = re.sub(r'\s+', ' ', t.strip())[:60]
65
+ k = n.lower()
66
+ if n and k not in seen: seen.add(k); out.append((n, label))
67
+ persons = list(_PERSON_HON.finditer(text))
68
+ for m in _ORG_SUFF.finditer(text):
69
+ start = max((p.end() for p in persons if p.start() < m.end() and p.end() > m.start()), default=m.start())
70
+ org = re.sub(r'^\s*(?:of|at|from)\s+', '', text[start:m.end()])
71
+ _add(org, 'ORG')
72
+ for m in persons: _add(m.group(1), 'PERSON')
73
+ for m in _LAW_INST.finditer(text): _add(m.group(1).strip(), 'LAW')
74
+ return out[:limit]
75
+
76
+ # %% ../nbs/00_core.ipynb #24e79db7
77
+ def _keyphrases(text:str) -> tuple:
78
+ 'litesearch keyphrases when it is installed, nothing when it is not. Display only: `cue_scores` reads the ORG/PERSON/LAW labels, never these.'
79
+ try: from litesearch import text_entities
80
+ except ImportError: return ()
81
+ return text_entities(text)
82
+
83
+ # %% ../nbs/00_core.ipynb #ef3ce3c0
84
+ def signals(text:str, # the document text
85
+ ner:bool=True, # run entity extraction (noun entities + keyphrases)
86
+ limit:int=20, # entities kept
87
+ ) -> AttrDict:
88
+ 'Countable evidence in one document: `counts` per signal, plus the entities it names.'
89
+ counts = {k: len(p.findall(text or '')) for k, p in _SIG.items()}
90
+ noun = L(_noun_ents((text or '')[:NER_CHARS]) if ner else ()).map(
91
+ lambda t: AttrDict(label=t[1], text=t[0]))
92
+ kws = L(_keyphrases((text or '')[:NER_CHARS]) if ner else ()).map(
93
+ lambda t: AttrDict(label=(t[1] or 'KEYPHRASE').upper(), text=re.sub(r'\s+', ' ', t[0].strip())[:60])
94
+ ).filter(lambda e: e.text and e.label not in {'ORG', 'PERSON', 'LAW', 'PRODUCT', 'GPE'})
95
+ found = noun + kws
96
+ labels = dict(Counter(e.label.lower() for e in found))
97
+ # labels count everything found; limit caps display only (cue_scores reads labels)
98
+ if noun:
99
+ counts = {k: counts.get(k, 0) + (labels.get(k, 0) if k not in counts else 0)
100
+ for k in (*counts, *(l for l in labels if l not in ('keyphrase', 'term')))}
101
+ return AttrDict(counts={k: v for k, v in counts.items() if v}, labels=labels,
102
+ ents=found.sorted(key=lambda e: e.label in ('KEYPHRASE', 'TERM'))[:limit],
103
+ method=('ner+regex' if noun else 'keyphrase+regex' if kws else 'regex'))
104
+
105
+ # %% ../nbs/00_core.ipynb #e77bc6be
106
+ DOCTYPES = {
107
+ # label: the cue phrases that are evidence for it, the regex signals it needs, and the
108
+ # entity labels it expects
109
+ 'invoice': dict(needs=('money',), ents=('ORG',), cues=(
110
+ r'\b(?:tax )?invoice\b', r'\b(?:amount|balance|total) due\b', r'\bbill(?:ed)? to\b|\bremit\b',
111
+ r'\bpayment terms?\b|\bnet \d{1,3}\b', r'\bsub-?total\b', r'\b(?:vat|gst|sales tax)\b')),
112
+ 'receipt': dict(needs=('money',), ents=('ORG',), cues=(
113
+ r'\breceipt\b', r'\bthank you for your (?:order|purchase|payment)\b',
114
+ r'\bcard\b[^\n]{0,16}\bending\b|\bcash tendered\b|\bchange due\b',
115
+ r'\btransaction (?:id|no)\b|\bauth(?:orisation|orization) code\b',
116
+ r'\bpaid\b|\bpayment received\b', r'\bmerchant\b|\bstore #\s?\d+\b')),
117
+ 'purchase_order': dict(needs=('ref',), ents=('ORG',), cues=(
118
+ r'\bpurchase order\b|\bp\.?o\.?\s*(?:no|number|#)', r'\bship(?:[ -]?to)?\b',
119
+ r'\bdelivery date\b|\brequested delivery\b', r'\bvendor\b|\bsupplier\b',
120
+ r'\brequisition\b', r'\bunit price\b')),
121
+ 'quote': dict(needs=('money',), ents=('ORG',), cues=(
122
+ r'\bquotation\b|\bquote\s*(?:no|number|#)|\bestimate\b', r'\bvalid (?:until|for|through)\b',
123
+ r'\bunit price\b', r'\bterms and conditions\b',
124
+ r'\bwe are pleased to (?:quote|offer)\b|\bno obligation\b')),
125
+ 'catalogue': dict(needs=('money',), ents=(), cues=(
126
+ r'\bcatalog(?:ue)?\b|\bprice list\b|\bproduct list\b',
127
+ r'\bsku\b|\bmodel\s*(?:no|number)\b|\bpart\s*(?:no|number)\b',
128
+ r'\b(?:in|out of) stock\b|\bavailability\b', r'\bper (?:unit|pack|case|kg|litre|liter)\b',
129
+ r'\bspecifications?\b|\bdimensions\b', r'\badd to (?:cart|basket)\b')),
130
+ 'contract': dict(needs=(), ents=('ORG', 'LAW'), cues=(
131
+ r'\bagreement\b|\bcontract\b', r'\bparties\b|\bby and between\b',
132
+ r'\bhereby\b|\bwhereas\b|\bhereinafter\b', r'\bshall\b',
133
+ r'\bgoverning law\b|\bjurisdiction\b|\btermination\b',
134
+ r'\bconfidential(?:ity)?\b|\bindemnif|\bliability\b')),
135
+ 'resume': dict(needs=('email',), ents=('PERSON', 'ORG'), cues=(
136
+ r'\b(?:curriculum vitae|resum[eé])\b',
137
+ r'\bwork experience\b|\bemployment history\b|\bprofessional experience\b',
138
+ r'\beducation\b', r'\bskills\b', r'\bcertification',
139
+ r'\breferences available\b|linkedin\.com/in/')),
140
+ 'paper': dict(needs=('citation',), ents=('ORG', 'PERSON'), cues=(
141
+ r'\babstract\b', r'\bintroduction\b', r'\brelated work\b|\bmethodology\b|\bexperiments?\b',
142
+ r'\breferences\b|\bbibliography\b', r'\bwe (?:propose|present|show|evaluate)\b',
143
+ r'\bdoi:|\barxiv:')),
144
+ 'report': dict(needs=(), ents=('ORG',), cues=(
145
+ r'\bexecutive summary\b', r'\bfindings\b|\bconclusions?\b|\brecommendations?\b',
146
+ r'\bq[1-4] \d{4}\b|\bfiscal year\b|\bfy\d{2}\b|\bquarter\b',
147
+ r'\btable \d+\b|\bfigure \d+\b|\bappendix\b',
148
+ r'\byear[- ]on[- ]year\b|\brevenue\b|\bmargin\b')),
149
+ # --- work-product labels ---
150
+ 'proposal': dict(needs=(), ents=('ORG',), cues=(
151
+ r'\bproposal\b|\brfp response\b|\brequest for proposal\b', r'\bproposed approach\b|\bour approach\b',
152
+ r'\bscope of work\b|\bwork ?plan\b', r'\bdeliverables?\b', r'\bfees?\b|\binvestment\b',
153
+ r'\bproject team\b|\bteam structure\b')),
154
+ 'presentation': dict(needs=(), ents=(), cues=(
155
+ r'\bslide deck\b|\bthis (?:deck|presentation)\b|\bslide \d+\b',
156
+ r'\bkey takeaways?\b|\bkey messages?\b', r'\bfor discussion\b|\bquestions? for discussion\b',
157
+ r'\bexecutive update\b|\bsteering committee\b|\bboard update\b',
158
+ r'\bappendix slides?\b|\bback-?up slides?\b',
159
+ r'\bagenda for (?:today|this session)\b|\bwalk(?:ing)? through\b')),
160
+ 'requirements_spec': dict(needs=(), ents=(), cues=(
161
+ r'\brequirements? specification\b|\bproduct requirements?\b', r'\bacceptance criteria\b',
162
+ r'\bfunctional requirements?\b|\bnon[- ]functional requirements?\b', r'\buser stor(?:y|ies)\b',
163
+ r'\brequirement id\b|\btraceability matrix\b', r'\bthe system shall\b|\bmust be able to\b')),
164
+ 'technical_design': dict(needs=(), ents=(), cues=(
165
+ r'\bsolution design\b|\btechnical design\b|\bdesign document\b',
166
+ r'\bdata architecture\b|\bsystem architecture\b|\barchitecture (?:diagram|overview)\b',
167
+ r'\bdata flow\b|\bsequence diagram\b|\bcomponent (?:diagram|view)\b',
168
+ r'\bapplication hosting\b|\bnon[- ]functional\b|\bscalability\b',
169
+ r'\bintegration (?:points?|patterns?|layer)\b|\binterface (?:contract|spec)\b',
170
+ r'\bsubnet\b|\bapi gateway\b|\bdeployment (?:topology|diagram)\b')),
171
+ 'regulatory_guidance': dict(needs=(), ents=('LAW', 'ORG'), cues=(
172
+ r'\bregulation \(?(?:eu|ec)\b|\bmedical device regulation\b', r'\bcompetent authority\b',
173
+ r'\bnotified bod(?:y|ies)\b|\bconformity assessment\b', r'\bauthori[sz]ed representative\b',
174
+ r'\btechnical documentation\b|\btechnical file\b', r'\barticle \d+\b|\bannex [ivx]+\b')),
175
+ 'procedure': dict(needs=(), ents=('ORG',), cues=(
176
+ r'\bstandard operating procedure\b|\bs\.?o\.?p\.?\b|\bwork instruction\b',
177
+ r'\bprocess owner\b|\bresponsibilit(?:y|ies)\b', r'\bapproval workflow\b|\bapproval authority\b',
178
+ r'\bescalation\b|\bexception handling\b', r'\brevision history\b|\bchange control\b',
179
+ r'\bthis procedure (?:applies|describes|covers)\b|\bscope and purpose\b')),
180
+ 'qa_artifact': dict(needs=(), ents=(), cues=(
181
+ r'\btest (?:case|plan|script|protocol)\b', r'\bexpected results?\b|\bactual results?\b',
182
+ r'\bsteps to reproduce\b|\bdefects?\b|\bbug report\b',
183
+ r'\bdeviation log\b|\bdiscrepanc(?:y|ies)\b',
184
+ r'\btemplate fidelity\b|\bvalidation report\b|\bqa audit\b',
185
+ r'\bpass/fail\b|\btest (?:results?|status|evidence)\b')),
186
+ 'roadmap': dict(needs=(), ents=('ORG',), cues=(
187
+ r'\broadmap\b', r'\bmilestones?\b', r'\bphase [0-9a-z]+\b|\bnow[,/ ]+next[,/ ]+later\b',
188
+ r'\bnext (?:30|60|90) days\b|\bquarterly plan\b', r'\btarget date\b|\bplanned date\b',
189
+ r'\bproduct backlog\b|\bdelivery plan\b|\bthemes?\b')),
190
+ # claim vs clinical_record share a dated-person shape; cues must separate them
191
+ 'claim': dict(needs=('date',), ents=('PERSON', 'ORG'), cues=(
192
+ r'\bclaim (?:number|no\.?|form|reference)\b|\bclaim id\b',
193
+ r'\bincident date\b|\bdate of loss\b', r'\bclaimant\b|\binsured\b|\bpolicyholder\b',
194
+ r'\bpolicy (?:number|no\.?|#)\b|\bcoverage\b', r'\b(?:loss )?adjuster\b|\bassessor\b',
195
+ r'\bsettlement\b|\bdeductible\b|\bexcess\b|\bliability accepted\b')),
196
+ 'clinical_record': dict(needs=('date',), ents=('PERSON', 'ORG'), cues=(
197
+ r'\bpatient\b|\bencounter\b', r'\bdiagnos(?:is|es|ed)\b|\bicd-?10\b',
198
+ r'\bpresenting complaint\b|\bclinical (?:history|notes?)\b',
199
+ r'\bprescri(?:bed|ption)\b|\bmedication\b|\bdosage\b',
200
+ r'\bdischarge summary\b|\breferral letter\b|\bclinician\b|\bphysician\b',
201
+ r'\badverse events?\b|\bdevice malfunction\b|\bside effects?\b')),
202
+ 'documentation': dict(needs=('heading',), ents=(), cues=(
203
+ r'\binstallation\b|\bgetting started\b|\bquick ?start\b',
204
+ r'\busage\b|\bexamples?\b|\bapi reference\b', r'\bparameters?\b|\breturns\b|\barguments?\b',
205
+ r'\bpip install\b|\bnpm install\b|\bdocker run\b', r'\bconfiguration\b|\bsee also\b',
206
+ r'^```')),
207
+ 'code': dict(needs=('code',), ents=(), cues=(
208
+ r'^\s*(?:def|class)\s+\w+|^\s*(?:function|const|let|var)\s+\w+',
209
+ r'^\s*(?:import|from|#include|package|use)\s+\w', r'\breturn\b',
210
+ r'^\s*(?://|#|/\*)', r'\b(?:if|for|while)\s*\(', r'\b(?:public|private|static|async)\b')),
211
+ 'email': dict(needs=('email',), ents=('PERSON',), cues=(
212
+ r'^(?:from|to|cc|bcc|subject|sent):', r'^\s*(?:dear|hi|hello)\b',
213
+ r'\b(?:best|kind) regards\b|\bsincerely\b|\bthanks,\b',
214
+ r'\bforwarded message\b|\bwrote:\s*$', r'\bunsubscribe\b')),
215
+ 'meeting_notes': dict(needs=(), ents=('PERSON',), cues=(
216
+ r'\b(?:meeting|call) notes\b|\bminutes\b', r'\battendees\b|\bparticipants\b|\bpresent\b',
217
+ r'\bagenda\b', r'\baction items?\b|\bnext steps\b|\bfollow[- ]ups?\b',
218
+ r'\bdecided\b|\bdecisions?\b|\bowner\b|\bdue by\b')),
219
+ 'form': dict(needs=('blank',), ents=(), cues=(
220
+ r'\bplease (?:complete|fill|print|sign)\b', r'\bfor office use only\b',
221
+ r'\bapplicant\b|\bapplication (?:form|for)\b', r'\bsignature\b|\bdate signed\b',
222
+ r'\b(?:full name|surname|given names?|date of birth|dob)\b', r'_{4,}')),
223
+ 'transcript': dict(needs=('time',), ents=('PERSON',), cues=(
224
+ r'\btranscript\b', r'^\s*\[?\d{1,2}:\d{2}', r'^\s*(?:speaker \d|[A-Z][a-z]+\s?[A-Z]?[a-z]*):',
225
+ r'\b(?:um|uh|you know|i mean)\b', r'\bwelcome (?:back|to)\b|\bthanks for (?:watching|listening)\b')),
226
+ 'article': dict(needs=(), ents=('PERSON', 'ORG'), cues=(
227
+ r'\bpublished\b|\bposted (?:on|by)\b', r'\bread more\b|\bshare this\b|\bcomments?\b',
228
+ r'\bsubscribe\b|\bnewsletter\b', r'\baccording to\b', r'\btags?:|\bcategor(?:y|ies):')),
229
+ }
230
+ _CUES = {l: [re.compile(c, re.I|re.M) for c in d['cues']] for l, d in DOCTYPES.items()}
231
+
232
+ # arrival kind is strong evidence (youtube -> transcript)
233
+ KIND_HINT = dict(youtube='transcript', arxiv='paper', code='code')
234
+ MIN_SCORE, MIN_MARGIN, KIND_BONUS = 0.4, 0.12, 0.2
235
+
236
+ def cue_scores(text:str, sig=None) -> dict:
237
+ 'Every doctype scored against `text`, best first: the categorisation no model is needed for.'
238
+ sig = sig if sig is not None else signals(text)
239
+ ner, out = sig.method.startswith('ner'), {}
240
+ for lbl, d in DOCTYPES.items():
241
+ cues = [p for p in _CUES[lbl] if p.search(text or '')]
242
+ need = [s for s in d['needs'] if sig.counts.get(s)]
243
+ ents = [e for e in d['ents'] if sig.labels.get(e.lower())] if ner else []
244
+ legs = [(0.6, len(cues)/len(_CUES[lbl]))]
245
+ if d['needs']: legs.append((0.25, len(need)/len(d['needs'])))
246
+ if ner and d['ents']: legs.append((0.15, len(ents)/len(d['ents'])))
247
+ w = sum(x for x, _ in legs)
248
+ out[lbl] = round(sum(x*f for x, f in legs)/w, 3)
249
+ return dict(sorted(out.items(), key=lambda kv: -kv[1]))
250
+
251
+ def guess_type(text:str, # the document text
252
+ sig=None, # a signals() result, computed if not given
253
+ kind:str=None, # the vault kind that acquired it, if known
254
+ min_score:float=MIN_SCORE, # below this the cues have not decided
255
+ min_margin:float=MIN_MARGIN, # runner-up this close means they have not either
256
+ ) -> AttrDict:
257
+ 'The best doctype for `text` from cues alone, and whether that guess is worth trusting.'
258
+ sig = sig if sig is not None else signals(text)
259
+ sc = cue_scores(text, sig)
260
+ if kind in KIND_HINT: sc[KIND_HINT[kind]] = round(min(1.0, sc[KIND_HINT[kind]] + KIND_BONUS), 3)
261
+ ranked = sorted(sc.items(), key=lambda kv: -kv[1])
262
+ (top, best), (_, second) = ranked[0], (ranked[1] if len(ranked) > 1 else ('', 0.0))
263
+ return AttrDict(doctype=top if best else 'other', score=best, margin=round(best-second, 3),
264
+ decisive=best >= min_score and best-second >= min_margin,
265
+ scores=dict(ranked[:5]), method=sig.method)
@@ -0,0 +1,226 @@
1
+ """the shape an extraction fills, and the call that fills it
2
+
3
+ Docs: https://vedicreader.github.io/varga/schema.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_schema.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['SCHEMAS', 'FIELD_TYPES', 'Invoice', 'Receipt', 'Catalogue', 'Contract', 'Resume', 'Paper', 'MeetingNotes', 'Summary',
9
+ 'dyn_schema', 'as_schema', 'schema_str', 'structured']
10
+
11
+ # %% ../nbs/01_schema.ipynb #e423da84
12
+ import json, re, warnings
13
+ from dataclasses import dataclass, fields, is_dataclass, make_dataclass, asdict
14
+ from typing import get_origin
15
+ from fastcore.all import AttrDict, L
16
+
17
+ # %% ../nbs/01_schema.ipynb #a125d2cb
18
+ @dataclass
19
+ class Invoice:
20
+ """An invoice, purchase order or quotation.
21
+
22
+ items: one entry per line, each {description, qty, unit_price, amount}.
23
+ Amounts are bare numbers with the currency in `currency`; dates are ISO (2024-03-01).
24
+ """
25
+ number:str = ''
26
+ date:str = ''
27
+ due_date:str = ''
28
+ vendor:str = ''
29
+ vendor_tax_id:str = ''
30
+ bill_to:str = ''
31
+ ship_to:str = ''
32
+ currency:str = ''
33
+ subtotal:float = 0
34
+ tax:float = 0
35
+ total:float = 0
36
+ payment_terms:str = ''
37
+ items:list[dict] = None
38
+
39
+ # %% ../nbs/01_schema.ipynb #0bb49294
40
+ @dataclass
41
+ class Receipt:
42
+ """A receipt for a completed payment.
43
+
44
+ items: one entry per line, each {description, qty, amount}. `paid_with` is the tender or the
45
+ last digits of the card. Dates are ISO (2024-03-01)."""
46
+ merchant:str = ''
47
+ date:str = ''
48
+ transaction_id:str = ''
49
+ currency:str = ''
50
+ subtotal:float = 0
51
+ tax:float = 0
52
+ total:float = 0
53
+ paid_with:str = ''
54
+ items:list[dict] = None
55
+
56
+ # %% ../nbs/01_schema.ipynb #5bb4dff8
57
+ @dataclass
58
+ class Catalogue:
59
+ """A product catalogue, price list or listing page.
60
+
61
+ products: one entry per product, each {sku, name, category, price, currency, availability, url}.
62
+ Prices are bare numbers."""
63
+ name:str = ''
64
+ vendor:str = ''
65
+ currency:str = ''
66
+ updated:str = ''
67
+ n_products:int = 0
68
+ products:list[dict] = None
69
+
70
+ # %% ../nbs/01_schema.ipynb #57fbc6cd
71
+ @dataclass
72
+ class Contract:
73
+ """An agreement between parties.
74
+
75
+ parties: the legal names. obligations: what each side must do. Dates are ISO (2024-03-01)."""
76
+ title:str = ''
77
+ parties:list[str] = None
78
+ effective_date:str = ''
79
+ end_date:str = ''
80
+ term:str = ''
81
+ value:str = ''
82
+ governing_law:str = ''
83
+ termination:str = ''
84
+ obligations:list[str] = None
85
+
86
+ # %% ../nbs/01_schema.ipynb #24e91acd
87
+ @dataclass
88
+ class Resume:
89
+ """One person's CV.
90
+
91
+ experience: one entry per role, each {employer, title, start, end, summary}.
92
+ education: one entry per qualification, each {institution, qualification, year}."""
93
+ name:str = ''
94
+ email:str = ''
95
+ phone:str = ''
96
+ location:str = ''
97
+ headline:str = ''
98
+ years_experience:float = 0
99
+ skills:list[str] = None
100
+ experience:list[dict] = None
101
+ education:list[dict] = None
102
+
103
+ # %% ../nbs/01_schema.ipynb #e81c81f6
104
+ @dataclass
105
+ class Paper:
106
+ """An academic paper. authors: names in order. findings: the claims the paper actually makes."""
107
+ title:str = ''
108
+ authors:list[str] = None
109
+ venue:str = ''
110
+ year:str = ''
111
+ doi:str = ''
112
+ abstract:str = ''
113
+ method:str = ''
114
+ findings:list[str] = None
115
+ limitations:list[str] = None
116
+
117
+ # %% ../nbs/01_schema.ipynb #17cbf009
118
+ @dataclass
119
+ class MeetingNotes:
120
+ """Notes from one meeting. actions: one entry per commitment, each {what, owner, due}."""
121
+ title:str = ''
122
+ date:str = ''
123
+ attendees:list[str] = None
124
+ topics:list[str] = None
125
+ decisions:list[str] = None
126
+ actions:list[dict] = None
127
+
128
+ # %% ../nbs/01_schema.ipynb #70ed9b52
129
+ @dataclass
130
+ class Summary:
131
+ """What one document says, when no more specific shape fits.
132
+
133
+ entities: the organisations, people and places it names. dates: ISO where the document allows."""
134
+ title:str = ''
135
+ doctype:str = ''
136
+ about:str = ''
137
+ key_points:list[str] = None
138
+ entities:list[str] = None
139
+ dates:list[str] = None
140
+ numbers:list[str] = None
141
+ open_questions:list[str] = None
142
+
143
+ # %% ../nbs/01_schema.ipynb #36192e1e
144
+ # PO and quotation share the Invoice schema
145
+ SCHEMAS = dict(invoice=Invoice, purchase_order=Invoice, quote=Invoice, receipt=Receipt,
146
+ catalogue=Catalogue, contract=Contract, resume=Resume, paper=Paper,
147
+ meeting_notes=MeetingNotes, other=Summary)
148
+
149
+ FIELD_TYPES = {'str':str, 'text':str, 'int':int, 'float':float, 'number':float, 'num':float, 'bool':bool,
150
+ 'list':list, 'dict':dict, 'strs':list[str], 'dicts':list[dict],
151
+ 'list[str]':list[str], 'list[dict]':list[dict]}
152
+ _DFLT = {str: '', int: 0, float: 0.0, bool: False}
153
+
154
+ # %% ../nbs/01_schema.ipynb #7ab433ab
155
+ def dyn_schema(spec, # 'vendor:str, total:float, items:dicts', or {'vendor':'str'}, or ['vendor']
156
+ name:str='Extracted', # class name, which the model sees
157
+ doc:str=None, # class docstring, which the model also sees
158
+ ) -> type:
159
+ 'A dataclass built at runtime from a field spec: the shape of an answer, named in one string.'
160
+ if isinstance(spec, str): spec = [p for p in re.split(r'[,\n]', spec) if p.strip()]
161
+ if isinstance(spec, dict): spec = [f'{k}:{v}' for k, v in spec.items()]
162
+ flds = []
163
+ for p in spec:
164
+ nm, _, ty = (p if isinstance(p, str) else ':'.join(p)).partition(':')
165
+ t = FIELD_TYPES.get(ty.strip().lower() or 'str', str)
166
+ flds.append((re.sub(r'\W', '_', nm.strip()), t, _DFLT.get(t, None)))
167
+ if not flds: raise ValueError(f'no fields in schema spec {spec!r}')
168
+ return make_dataclass(re.sub(r'\W', '', name) or 'Extracted', flds,
169
+ namespace=dict(__doc__=doc or 'The fields to pull out of the document.'))
170
+
171
+ # %% ../nbs/01_schema.ipynb #86058550
172
+ def as_schema(spec, name:str='Extracted', doc:str=None) -> type:
173
+ 'Whatever names a shape, as a dataclass: a `SCHEMAS` key, a dataclass, or a `dyn_schema` spec.'
174
+ if is_dataclass(spec): return spec
175
+ if isinstance(spec, str) and spec.strip() in SCHEMAS: return SCHEMAS[spec.strip()]
176
+ return dyn_schema(spec, name=name, doc=doc)
177
+
178
+ # %% ../nbs/01_schema.ipynb #393a81bb
179
+ def _norm(obj, schema) -> dict:
180
+ "A structured reply as a plain dict, with the `None` a list field defaults to turned back into `[]`."
181
+ d = asdict(obj) if is_dataclass(obj) and not isinstance(obj, type) else dict(obj or {})
182
+ lists = {f.name for f in fields(schema) if f.type is list or get_origin(f.type) is list}
183
+ return {k: ([] if v is None and k in lists else v) for k, v in d.items()}
184
+
185
+ # %% ../nbs/01_schema.ipynb #d62421fb
186
+ def schema_str(schema) -> str:
187
+ "A schema written out for a model to read: its docstring, then `name: type` per field."
188
+ def ty(t):
189
+ if isinstance(t, str): return t
190
+ # `list[dict].__name__` is just 'list'; the parameter is the half the model needs
191
+ return str(t).replace('typing.', '') if get_origin(t) else getattr(t, '__name__', str(t))
192
+ return ((schema.__doc__ or '').strip() + '\n\n{\n'
193
+ + ',\n'.join(f' "{f.name}": {ty(f.type)}' for f in fields(schema)) + '\n}')
194
+
195
+ # %% ../nbs/01_schema.ipynb #3dae58c8
196
+ def _split_reasoning(text:str) -> str:
197
+ "The answer with any reasoning stripped: rishi's `split_think`, plus the *closing*-only tag an MLX prefill leaves."
198
+ from rishi.core import split_think
199
+ text, _ = split_think(text)
200
+ if '</think>' in text: text = text.partition('</think>')[2]
201
+ return text.strip()
202
+
203
+ # %% ../nbs/01_schema.ipynb #bf7b950f
204
+ def _json_reply(ch, prompt:str, schema, sp:str='') -> object:
205
+ 'Ask for the shape as a JSON object in prose and rebuild it, with the model left unconstrained.'
206
+ ch.hist = []
207
+ from rishi.core import resp_text
208
+ txt = resp_text(ch(f'{sp}\n\n{prompt}\n\nReply with only a JSON object in a ```json fence, with '
209
+ f'exactly these keys and types:\n\n{schema_str(schema)}'))
210
+ from rishi.core import extract_fence
211
+ d = json.loads(extract_fence(_split_reasoning(txt), 'json'))
212
+ nms = {f.name for f in fields(schema)}
213
+ return schema(**{k: v for k, v in d.items() if k in nms})
214
+
215
+ # %% ../nbs/01_schema.ipynb #875af6df
216
+ def structured(ch, # a `rishi.Chat`, e.g. from `new_chat`
217
+ prompt:str, # the document and the instruction
218
+ schema, # the dataclass the reply must fill
219
+ sp:str='', # system prompt for the extraction
220
+ ) -> dict:
221
+ 'A structured reply as a dict, retried as a plain JSON reply when the constrained call fails.'
222
+ try: return _norm(ch.structured(prompt, schema, sp=sp), schema)
223
+ except Exception as e:
224
+ warnings.warn(f'{type(e).__name__} on a constrained call for {schema.__name__} '
225
+ f'({str(e)[:150]}); retrying as a JSON reply.')
226
+ return _norm(_json_reply(ch, prompt, schema, sp), schema)