drawbook-lp 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,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ out/
8
+ sources/
@@ -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,12 @@
1
+ Drawbook
2
+ Copyright 2026 Stargira Advisors Ltd
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ The ledger layout, section names and transaction types follow the ILPA Capital Call &
7
+ Distribution Template (v. 2.0, September 2025), published by the Institutional Limited
8
+ Partners Association (ilpa.org). ILPA's files are not included in this repository;
9
+ tools/fetch_ilpa.py downloads them from ilpa.org for the tests that need them.
10
+ Drawbook is not affiliated with or endorsed by ILPA.
11
+
12
+ All notices, funds, investors and bank details in testset/ and sample/ are made up.
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: drawbook-lp
3
+ Version: 0.1.0
4
+ Summary: Capital call and distribution PDFs to an ILPA-format ledger, every figure linked to its page.
5
+ Project-URL: Homepage, https://github.com/kyasuda-stargira/drawbook
6
+ Project-URL: Source, https://github.com/kyasuda-stargira/drawbook
7
+ Author: Stargira
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: openpyxl>=3.1
15
+ Requires-Dist: pdfplumber>=0.11
16
+ Requires-Dist: pydantic>=2.6
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Drawbook
20
+
21
+ Capital call and distribution PDFs → an ILPA-format ledger.
22
+
23
+ Drawbook is a free, open-source tool for LPs (limited partners: the investors in a private fund). Point it at a folder of fund documents: capital call notices, distribution notices and capital account statements. It returns one spreadsheet of cash flows, laid out in the structure of ILPA's 2025 Capital Call & Distribution Template. Every figure links back to the file and page it came from.
24
+
25
+ ## What you get
26
+
27
+ `drawbook-out/lp-ledger.xlsx`, with four sheets:
28
+
29
+ - **Fund**: fund name, GP, currency, fund size, commitment and ownership share.
30
+ - **Transactions**: one row per cash flow: dates, ILPA transaction type, amount, whether it changes your unfunded commitment (the part of your commitment not yet called), inside or outside commitment, recallable or not, source file and page.
31
+ - **Balances**: paid-in, unfunded, distributions and recallable capital as each notice states them.
32
+ - **Warnings**: balances that don't tie to the notice before, **payment details that changed between notices**, and figures Drawbook could not find on the page it read them from.
33
+
34
+ Plus `lp-ledger.csv` (the transactions) and `notices.json` (everything read).
35
+
36
+ Filled ILPA 2025 template workbooks (`.xlsx`) in the same folder are read directly, without AI.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install drawbook-lp
42
+ ```
43
+
44
+ Scanned PDFs also need Tesseract and Poppler (`brew install tesseract poppler`, or your system's package manager).
45
+
46
+ ## Run
47
+
48
+ Drawbook reads with an AI model running on your own machine. Start any OpenAI-compatible local server, for example:
49
+
50
+ ```bash
51
+ mlx_lm.server --model mlx-community/Qwen3-8B-4bit --port 8080 # Apple silicon
52
+ ollama serve # then --local-url http://127.0.0.1:11434/v1
53
+ ```
54
+
55
+ Then:
56
+
57
+ ```bash
58
+ drawbook ./my-fund-notices --local-model mlx-community/Qwen3-8B-4bit
59
+ ```
60
+
61
+ Your documents never leave the machine in this mode. Drawbook refuses a "local" address that is not on this computer.
62
+
63
+ ## Using your own AI provider (opt-in)
64
+
65
+ Some documents read better with a larger model. You can send chosen documents to your own provider:
66
+
67
+ ```bash
68
+ export DRAWBOOK_OUTSIDE_KEY=... # your key; you pay your provider directly
69
+ drawbook ./notices --outside anthropic --outside-model <model> --outside-for "*capital-call*.pdf"
70
+ ```
71
+
72
+ Before each document is sent, Drawbook shows a warning and asks you to confirm. Side letters and LPAs often limit sharing fund documents with outside processors, so check yours first. Drawbook first reads the document locally to find the LP's name and ID, and removes them from the text it sends. Add `--redact-figures` to remove figures too. Every send is logged in `drawbook-out/outside-send-log.jsonl`.
73
+
74
+ ## How it reads
75
+
76
+ 1. Text from the PDF's text layer; pages with no text go through OCR.
77
+ 2. The model fills a fixed schema mapped from the ILPA template (see `docs/field-map.md`).
78
+ 3. Code then checks every figure appears on the page the model cited. A figure found on no page is dropped and listed in Warnings. Drawbook never fills a figure the document does not print.
79
+ 4. Balances are tied from one notice to the next, and payment details are compared across notices.
80
+
81
+ **Always confirm changed payment details with the GP by phone before you pay.**
82
+
83
+ ## Accuracy
84
+
85
+ Drawbook is tested on made-up notices in varied GP layouts, because real notices are confidential. With Qwen3 8B (4-bit) running locally, it read 98.0% of fields exactly (348 of 355) on 10 notices in three layouts it had never seen. Scanned copies scored within 5 points of their text versions.
86
+
87
+ Scores on made-up documents may flatter it on real ones. Always check the Warnings sheet. See `docs/test-results.md` for how the test set was built and scored.
88
+
89
+ ## Licence
90
+
91
+ Apache 2.0. Not investment, tax or accounting advice. It reorganises your own documents; check the output against them.
@@ -0,0 +1,73 @@
1
+ # Drawbook
2
+
3
+ Capital call and distribution PDFs → an ILPA-format ledger.
4
+
5
+ Drawbook is a free, open-source tool for LPs (limited partners: the investors in a private fund). Point it at a folder of fund documents: capital call notices, distribution notices and capital account statements. It returns one spreadsheet of cash flows, laid out in the structure of ILPA's 2025 Capital Call & Distribution Template. Every figure links back to the file and page it came from.
6
+
7
+ ## What you get
8
+
9
+ `drawbook-out/lp-ledger.xlsx`, with four sheets:
10
+
11
+ - **Fund**: fund name, GP, currency, fund size, commitment and ownership share.
12
+ - **Transactions**: one row per cash flow: dates, ILPA transaction type, amount, whether it changes your unfunded commitment (the part of your commitment not yet called), inside or outside commitment, recallable or not, source file and page.
13
+ - **Balances**: paid-in, unfunded, distributions and recallable capital as each notice states them.
14
+ - **Warnings**: balances that don't tie to the notice before, **payment details that changed between notices**, and figures Drawbook could not find on the page it read them from.
15
+
16
+ Plus `lp-ledger.csv` (the transactions) and `notices.json` (everything read).
17
+
18
+ Filled ILPA 2025 template workbooks (`.xlsx`) in the same folder are read directly, without AI.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install drawbook-lp
24
+ ```
25
+
26
+ Scanned PDFs also need Tesseract and Poppler (`brew install tesseract poppler`, or your system's package manager).
27
+
28
+ ## Run
29
+
30
+ Drawbook reads with an AI model running on your own machine. Start any OpenAI-compatible local server, for example:
31
+
32
+ ```bash
33
+ mlx_lm.server --model mlx-community/Qwen3-8B-4bit --port 8080 # Apple silicon
34
+ ollama serve # then --local-url http://127.0.0.1:11434/v1
35
+ ```
36
+
37
+ Then:
38
+
39
+ ```bash
40
+ drawbook ./my-fund-notices --local-model mlx-community/Qwen3-8B-4bit
41
+ ```
42
+
43
+ Your documents never leave the machine in this mode. Drawbook refuses a "local" address that is not on this computer.
44
+
45
+ ## Using your own AI provider (opt-in)
46
+
47
+ Some documents read better with a larger model. You can send chosen documents to your own provider:
48
+
49
+ ```bash
50
+ export DRAWBOOK_OUTSIDE_KEY=... # your key; you pay your provider directly
51
+ drawbook ./notices --outside anthropic --outside-model <model> --outside-for "*capital-call*.pdf"
52
+ ```
53
+
54
+ Before each document is sent, Drawbook shows a warning and asks you to confirm. Side letters and LPAs often limit sharing fund documents with outside processors, so check yours first. Drawbook first reads the document locally to find the LP's name and ID, and removes them from the text it sends. Add `--redact-figures` to remove figures too. Every send is logged in `drawbook-out/outside-send-log.jsonl`.
55
+
56
+ ## How it reads
57
+
58
+ 1. Text from the PDF's text layer; pages with no text go through OCR.
59
+ 2. The model fills a fixed schema mapped from the ILPA template (see `docs/field-map.md`).
60
+ 3. Code then checks every figure appears on the page the model cited. A figure found on no page is dropped and listed in Warnings. Drawbook never fills a figure the document does not print.
61
+ 4. Balances are tied from one notice to the next, and payment details are compared across notices.
62
+
63
+ **Always confirm changed payment details with the GP by phone before you pay.**
64
+
65
+ ## Accuracy
66
+
67
+ Drawbook is tested on made-up notices in varied GP layouts, because real notices are confidential. With Qwen3 8B (4-bit) running locally, it read 98.0% of fields exactly (348 of 355) on 10 notices in three layouts it had never seen. Scanned copies scored within 5 points of their text versions.
68
+
69
+ Scores on made-up documents may flatter it on real ones. Always check the Warnings sheet. See `docs/test-results.md` for how the test set was built and scored.
70
+
71
+ ## Licence
72
+
73
+ Apache 2.0. Not investment, tax or accounting advice. It reorganises your own documents; check the output against them.
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.27.0"] # writes metadata 2.4, which twine and PyPI accept
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "drawbook-lp"
7
+ version = "0.1.0"
8
+ description = "Capital call and distribution PDFs to an ILPA-format ledger, every figure linked to its page."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Stargira" }]
13
+ dependencies = ["pdfplumber>=0.11", "pydantic>=2.6", "openpyxl>=3.1"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Topic :: Office/Business :: Financial :: Accounting"]
15
+
16
+ [project.scripts]
17
+ drawbook = "drawbook.cli:main"
18
+
19
+ [tool.hatch.build.targets.wheel]
20
+ packages = ["src/drawbook"]
21
+
22
+ [tool.hatch.build.targets.sdist]
23
+ include = ["src/drawbook", "README.md", "LICENSE", "NOTICE", "pyproject.toml"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/kyasuda-stargira/drawbook"
27
+ Source = "https://github.com/kyasuda-stargira/drawbook"
File without changes
@@ -0,0 +1,72 @@
1
+ """Tie-out and bank-change checks across a fund's notices."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from collections import defaultdict
6
+ from datetime import date
7
+ from decimal import Decimal
8
+
9
+ from .schema import InsideOutside, Notice
10
+
11
+ TOL = Decimal("1.00") # allow rounding to whole units on printed notices
12
+
13
+
14
+ def _ne(a, b) -> bool:
15
+ return a is not None and b is not None and abs(a - b) > TOL
16
+
17
+
18
+ def fund_key(n: Notice) -> tuple:
19
+ return (" ".join(n.fund_name.lower().split()), (n.lp_id or n.lp_name or "").lower())
20
+
21
+
22
+ def _norm_bank(v: str | None) -> str:
23
+ return re.sub(r"[^0-9a-z]", "", (v or "").lower())
24
+
25
+
26
+ def within(n: Notice) -> list[str]:
27
+ out = []
28
+ parts = [n.lp_unfunded_prior, n.lp_unfunded_impact_current, n.lp_expired_released, n.lp_other_unfunded_adjustment]
29
+ if n.lp_unfunded_prior is not None and n.lp_unfunded_impact_current is not None and n.lp_unfunded_incl is not None:
30
+ s = sum((p for p in parts if p is not None), Decimal(0))
31
+ if _ne(s, n.lp_unfunded_incl):
32
+ out.append(f"unfunded does not tie: {n.lp_unfunded_prior} + changes = {s}, notice says {n.lp_unfunded_incl}")
33
+ for label, prior, cur, incl in [
34
+ ("contributions", n.lp_cum_contributions_prior, n.lp_contributions_current, n.lp_cum_contributions_incl),
35
+ ("distributions", n.lp_cum_distributions_prior, n.lp_distributions_current, n.lp_cum_distributions_incl)]:
36
+ if prior is not None and incl is not None:
37
+ if _ne(prior + (cur or 0), incl):
38
+ out.append(f"cumulative {label} do not tie: {prior} + {cur or 0} != {incl}")
39
+ if n.transactions and n.lp_contributions_current is not None:
40
+ inside = sum((t.lp_amount for t in n.transactions if t.transaction_type.value.startswith("Capital Call")
41
+ and t.inside_outside == InsideOutside.INSIDE), Decimal(0))
42
+ if _ne(inside, n.lp_contributions_current):
43
+ out.append(f"line items ({inside}) do not add up to the amount called ({n.lp_contributions_current})")
44
+ return out
45
+
46
+
47
+ def run(notices: list[Notice]) -> list[dict]:
48
+ """Return warnings: [{file, field, warning}]."""
49
+ warns = []
50
+ for n in notices:
51
+ for msg in within(n):
52
+ warns.append({"file": n.source_file, "field": "balances", "warning": msg})
53
+ groups: dict[tuple, list[Notice]] = defaultdict(list)
54
+ for n in notices:
55
+ groups[fund_key(n)].append(n)
56
+ for seq in groups.values():
57
+ seq.sort(key=lambda n: (n.notice_date or date.min, n.source_file))
58
+ for a, b in zip(seq, seq[1:]):
59
+ for label, x, y in [("unfunded commitment", a.lp_unfunded_incl, b.lp_unfunded_prior),
60
+ ("contributions to date", a.lp_cum_contributions_incl, b.lp_cum_contributions_prior),
61
+ ("distributions to date", a.lp_cum_distributions_incl, b.lp_cum_distributions_prior)]:
62
+ if _ne(x, y):
63
+ warns.append({"file": b.source_file, "field": "balances",
64
+ "warning": f"{label} before this notice ({y}) does not match {a.source_file} after it ({x})"})
65
+ if a.bank and b.bank:
66
+ for f in ("account_number", "sort_code", "swift_bic", "bank_name"):
67
+ va, vb = getattr(a.bank, f), getattr(b.bank, f)
68
+ if va and vb and _norm_bank(va) != _norm_bank(vb):
69
+ warns.append({"file": b.source_file, "field": f"bank.{f}",
70
+ "warning": f"PAYMENT DETAILS CHANGED: {f} was {va!r} in {a.source_file}, "
71
+ f"now {vb!r}. Confirm with the GP by phone before paying."})
72
+ return warns
@@ -0,0 +1,91 @@
1
+ """drawbook <folder>: read every PDF (and ILPA template .xlsx) in a folder into lp-ledger.xlsx + lp-ledger.csv."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import fnmatch
6
+ import json
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import checks, ledger, xlsx_import
12
+ from .extract import extract
13
+ from .providers import LocalProvider, OutsideProvider
14
+
15
+
16
+ def _confirm_factory(assume_yes: bool):
17
+ def confirm(msg: str) -> bool:
18
+ print(f"\nWARNING: {msg}", file=sys.stderr)
19
+ if assume_yes:
20
+ print("(--yes given: sending)", file=sys.stderr)
21
+ return True
22
+ return input("Send? [y/N] ").strip().lower() == "y"
23
+ return confirm
24
+
25
+
26
+ def main(argv: list[str] | None = None) -> int:
27
+ ap = argparse.ArgumentParser(prog="drawbook", description=__doc__)
28
+ ap.add_argument("folder", type=Path)
29
+ ap.add_argument("--out", type=Path, default=None, help="output folder (default: <folder>/drawbook-out)")
30
+ ap.add_argument("--local-url", default=None, help="OpenAI-compatible server on this machine (default http://127.0.0.1:8080/v1)")
31
+ ap.add_argument("--local-model", default=None)
32
+ ap.add_argument("--no-ocr", action="store_true", help="skip OCR for scanned pages")
33
+ g = ap.add_argument_group("outside AI (opt-in; documents leave this machine)")
34
+ g.add_argument("--outside", choices=["anthropic", "openai-compatible"], help="use your own AI provider")
35
+ g.add_argument("--outside-model", help="model name at that provider")
36
+ g.add_argument("--outside-url", help="base URL (openai-compatible only)")
37
+ g.add_argument("--outside-for", action="append", default=[],
38
+ help="file name pattern to send outside (repeatable). Without it, the whole folder is sent.")
39
+ g.add_argument("--redact-figures", action="store_true", help="also replace figures with [FIGURE] before sending")
40
+ g.add_argument("--yes", action="store_true", help="skip the per-document confirmation")
41
+ a = ap.parse_args(argv)
42
+
43
+ folder = a.folder
44
+ out = a.out or folder / "drawbook-out"
45
+ local = LocalProvider(a.local_url, a.local_model)
46
+ outside = None
47
+ if a.outside:
48
+ key = os.environ.get("DRAWBOOK_OUTSIDE_KEY", "")
49
+ if not key or not a.outside_model:
50
+ ap.error("--outside needs --outside-model and the DRAWBOOK_OUTSIDE_KEY environment variable")
51
+ outside = OutsideProvider(a.outside, key, a.outside_model, base_url=a.outside_url,
52
+ log_path=out / "outside-send-log.jsonl", confirm=_confirm_factory(a.yes),
53
+ redact_names=[], redact_figures=a.redact_figures)
54
+
55
+ notices, warns = [], []
56
+ files = sorted(p for p in folder.iterdir() if p.suffix.lower() in (".pdf", ".xlsx"))
57
+ for p in files:
58
+ if p.suffix.lower() == ".xlsx":
59
+ if xlsx_import.is_ilpa_template(p):
60
+ notices.append(xlsx_import.read(p))
61
+ continue
62
+ use_outside = outside and (not a.outside_for or any(fnmatch.fnmatch(p.name, pat) for pat in a.outside_for))
63
+ prov = outside if use_outside else local
64
+ print(f"reading {p.name} with {prov.name}", file=sys.stderr)
65
+ try:
66
+ from .pdftext import read_pages
67
+ pages = read_pages(p, ocr=not a.no_ocr)
68
+ if use_outside:
69
+ # local pass first finds the LP's name so it can be redacted before anything is sent
70
+ first = extract(p, local, pages)
71
+ outside.redact_names = [x for x in (first.notice.lp_name, first.notice.lp_id) if first.notice and x] \
72
+ if first.notice else []
73
+ r = extract(p, prov, pages)
74
+ except PermissionError:
75
+ warns.append({"file": p.name, "field": "*", "warning": "not sent outside (declined); not read"})
76
+ continue
77
+ except Exception as e: # noqa: BLE001
78
+ warns.append({"file": p.name, "field": "*", "warning": f"could not read: {e}"})
79
+ continue
80
+ warns += r.warnings
81
+ if r.notice:
82
+ notices.append(r.notice)
83
+ warns = checks.run(notices) + warns
84
+ xlsx, csv_path = ledger.write(notices, warns, out)
85
+ (out / "notices.json").write_text(json.dumps([json.loads(n.model_dump_json()) for n in notices], indent=1))
86
+ print(f"{len(notices)} documents read, {len(warns)} warnings -> {xlsx}", file=sys.stderr)
87
+ return 0
88
+
89
+
90
+ if __name__ == "__main__":
91
+ sys.exit(main())