margin-fine-print 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fine_print/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ """Fine Print."""
2
+
3
+ from fine_print.agent import FinePrintAgent
4
+ from fine_print.models import (
5
+ ACCEPTED,
6
+ Clause,
7
+ DocumentMeta,
8
+ FinePrintInput,
9
+ FinePrintOutput,
10
+ KeyTerm,
11
+ MarginNote,
12
+ MissingProtection,
13
+ NegotiationItem,
14
+ )
15
+
16
+ __version__ = "0.1.0"
17
+
18
+ __all__ = [
19
+ "ACCEPTED",
20
+ "Clause",
21
+ "DocumentMeta",
22
+ "FinePrintAgent",
23
+ "FinePrintInput",
24
+ "FinePrintOutput",
25
+ "KeyTerm",
26
+ "MarginNote",
27
+ "MissingProtection",
28
+ "NegotiationItem",
29
+ "__version__",
30
+ ]
fine_print/agent.py ADDED
@@ -0,0 +1,192 @@
1
+ """Fine Print: reads contracts, leases, offers, and policies with notes in the margin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from margin_core import AgentResult, BaseAgent, Evidence, Finding, RunContext
6
+
7
+ from fine_print.models import FinePrintInput, FinePrintOutput
8
+
9
+ _SEVERITY_SCORE: dict[str, float] = {
10
+ "high": 1.0,
11
+ "medium": 0.6,
12
+ "low": 0.3,
13
+ "ok": 0.0,
14
+ }
15
+
16
+
17
+ class FinePrintAgent(BaseAgent):
18
+ id = "fine-print"
19
+ name = "Fine Print"
20
+ description = (
21
+ "Reads a contract, lease, offer, or policy and puts plain-English notes in the margin."
22
+ )
23
+ version = "0.1.0"
24
+ InputModel = FinePrintInput
25
+ OutputModel = FinePrintOutput
26
+ primary_input = "document"
27
+ uses_llm = True
28
+ requires_git = False
29
+
30
+ async def run(self, input: FinePrintInput, ctx: RunContext) -> AgentResult:
31
+ import asyncio
32
+ import math
33
+
34
+ from fine_print.exports import write_reports
35
+ from fine_print.extract import detect_doc_type, extract_key_terms, extract_parties
36
+ from fine_print.ingest import ingest_document
37
+ from fine_print.models import DocumentMeta
38
+ from fine_print.questions import confirm_review_context
39
+ from fine_print.rules import (
40
+ CAVEAT_TEXT,
41
+ analyze_clauses,
42
+ build_checklist,
43
+ build_template_headline,
44
+ find_missing_protections,
45
+ )
46
+ from fine_print.write import enrich_with_model
47
+
48
+ ctx.report_progress("ingest", "Reading document", 0.1)
49
+ doc = await asyncio.to_thread(ingest_document, input.document)
50
+
51
+ for warning in doc.warnings:
52
+ ctx.warn(warning)
53
+ ctx.check_cancelled()
54
+
55
+ ctx.report_progress("extract", "Extracting dates, amounts, and clauses", 0.25)
56
+ detected_type, indicators = detect_doc_type(doc.clauses)
57
+ parties = extract_parties(doc.clauses)
58
+ key_terms = extract_key_terms(doc.clauses)
59
+
60
+ review_ctx = await confirm_review_context(
61
+ detected_type,
62
+ indicators,
63
+ ctx,
64
+ preset=input.answers,
65
+ assume_defaults=input.assume_defaults,
66
+ )
67
+ ctx.check_cancelled()
68
+
69
+ meta = DocumentMeta(
70
+ filename=doc.filename,
71
+ file_format=doc.file_format,
72
+ pages=doc.pages,
73
+ word_count=doc.word_count,
74
+ paragraph_count=len(doc.clauses),
75
+ char_count=doc.char_count,
76
+ reading_minutes=max(1, math.ceil(doc.word_count / 220)),
77
+ detected_type=detected_type,
78
+ doc_type=review_ctx.doc_type,
79
+ party_side=review_ctx.party_side,
80
+ party_side_label=review_ctx.party_side_label,
81
+ priorities=review_ctx.priorities,
82
+ parties=parties,
83
+ )
84
+
85
+ ctx.report_progress("analyze", "Checking clauses and missing protections", 0.5)
86
+ notes = analyze_clauses(
87
+ doc.clauses,
88
+ doc_type=review_ctx.doc_type,
89
+ party_side=review_ctx.party_side,
90
+ priorities=review_ctx.priorities,
91
+ focus=input.focus,
92
+ )
93
+ missing = find_missing_protections(
94
+ review_ctx.doc_type,
95
+ review_ctx.party_side,
96
+ doc.clauses,
97
+ notes,
98
+ )
99
+ template_headline = build_template_headline(meta, notes, missing)
100
+ ctx.check_cancelled()
101
+
102
+ if input.use_llm and ctx.llm is not None and notes and input.max_clauses_for_llm > 0:
103
+ ctx.report_progress("write", "Writing plain-English notes with model", 0.7)
104
+ headline, notes, used_model = await enrich_with_model(
105
+ meta,
106
+ doc.clauses,
107
+ notes,
108
+ template_headline,
109
+ ctx,
110
+ use_llm=input.use_llm,
111
+ redact=input.redact_personal_info,
112
+ max_clauses=input.max_clauses_for_llm,
113
+ )
114
+ ctx.check_cancelled()
115
+
116
+ checklist = build_checklist(notes, missing)
117
+ risk_counts = {
118
+ "high": sum(1 for n in notes if n.severity == "high"),
119
+ "medium": sum(1 for n in notes if n.severity == "medium"),
120
+ "low": sum(1 for n in notes if n.severity == "low"),
121
+ "checked": sum(1 for n in notes if n.severity == "ok"),
122
+ }
123
+
124
+ output = FinePrintOutput(
125
+ document=meta,
126
+ caveat=CAVEAT_TEXT,
127
+ summary_headline=headline,
128
+ risk_counts=risk_counts,
129
+ clauses=doc.clauses,
130
+ notes=notes,
131
+ key_terms=key_terms,
132
+ missing_protections=missing,
133
+ checklist=checklist,
134
+ writer_mode="model" if used_model else "template",
135
+ )
136
+
137
+ if input.output_dir:
138
+ ctx.report_progress("export", f"Writing review files to {input.output_dir}", 0.92)
139
+ output.files = await asyncio.to_thread(write_reports, input.output_dir, output)
140
+
141
+ findings = _build_findings(output)
142
+ ctx.report_progress("done", "Finished", 1.0)
143
+ return self.make_result(
144
+ summary=headline,
145
+ output=output,
146
+ findings=findings,
147
+ status="partial" if doc.warnings else "ok",
148
+ )
149
+
150
+
151
+ def _build_findings(output: FinePrintOutput) -> list[Finding]:
152
+ findings: list[Finding] = []
153
+ for note in output.notes:
154
+ ev = [
155
+ Evidence(
156
+ kind="quote",
157
+ location=f"{note.clause_id} ({note.location})",
158
+ detail=f'"{note.quote}"',
159
+ )
160
+ ]
161
+ if note.suggested_question:
162
+ ev.append(
163
+ Evidence(
164
+ kind="question",
165
+ location=note.location,
166
+ detail=f"Ask before signing: {note.suggested_question}",
167
+ )
168
+ )
169
+ findings.append(
170
+ Finding(
171
+ title=f"{note.title} ({note.margin_tag})",
172
+ severity_or_score=_SEVERITY_SCORE.get(note.severity, 0.3),
173
+ summary=f"{note.explanation} {note.why_it_matters}",
174
+ evidence=ev,
175
+ )
176
+ )
177
+ for miss in output.missing_protections:
178
+ findings.append(
179
+ Finding(
180
+ title=f"Not mentioned: {miss.title}",
181
+ severity_or_score=0.5,
182
+ summary=miss.detail,
183
+ evidence=[
184
+ Evidence(
185
+ kind="question",
186
+ location="document",
187
+ detail=f"Ask before signing: {miss.suggested_question}",
188
+ )
189
+ ],
190
+ )
191
+ )
192
+ return findings
fine_print/exports.py ADDED
@@ -0,0 +1,299 @@
1
+ """Exports for Fine Print: standalone printable HTML review, Markdown checklist, and terms CSV."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import html
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from fine_print.models import FinePrintOutput, KeyTerm, MarginNote
12
+
13
+ _FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
14
+ _SAFE_STEM_RE = re.compile(r"[^A-Za-z0-9._-]+")
15
+
16
+
17
+ def safe_stem(filename: str) -> str:
18
+ stem = Path(filename).stem
19
+ cleaned = _SAFE_STEM_RE.sub("_", stem).strip("._-")
20
+ return cleaned[:64] or "document"
21
+
22
+
23
+ def _csv_safe(value: Any) -> Any:
24
+ if isinstance(value, str) and value.startswith(_FORMULA_PREFIXES):
25
+ return "'" + value
26
+ return value
27
+
28
+
29
+ def _write_terms_csv(path: Path, terms: list[KeyTerm]) -> None:
30
+ headers = ["id", "kind", "label", "value", "location", "section", "context"]
31
+ with path.open("w", encoding="utf-8-sig", newline="") as handle:
32
+ writer = csv.writer(handle)
33
+ writer.writerow(headers)
34
+ for t in terms:
35
+ writer.writerow(
36
+ [
37
+ _csv_safe(t.id),
38
+ _csv_safe(t.kind),
39
+ _csv_safe(t.label),
40
+ _csv_safe(t.value),
41
+ _csv_safe(t.location),
42
+ _csv_safe(t.section or ""),
43
+ _csv_safe(t.context),
44
+ ]
45
+ )
46
+
47
+
48
+ def _write_checklist_md(path: Path, output: FinePrintOutput) -> None:
49
+ meta = output.document
50
+ lines: list[str] = [
51
+ f"# Questions before signing — {meta.filename}",
52
+ "",
53
+ f"Reviewed as: **{meta.party_side_label}** · Type: `{meta.doc_type}` · "
54
+ f"{meta.word_count:,} words",
55
+ "",
56
+ f"> {output.caveat}",
57
+ "",
58
+ output.summary_headline,
59
+ "",
60
+ ]
61
+ if output.checklist:
62
+ lines.append("## Questions and requested edits")
63
+ lines.append("")
64
+ for item in output.checklist:
65
+ loc = f" (`{item.location}`)" if item.location else " (not in document)"
66
+ tag = "HIGH" if item.priority == "high" else "MEDIUM"
67
+ lines.append(f"- [ ] **[{tag}] {item.topic}**{loc}: {item.question}")
68
+ lines.append("")
69
+ else:
70
+ lines.append("No high- or medium-priority questions were generated for this document.")
71
+ lines.append("")
72
+
73
+ if output.missing_protections:
74
+ lines.append("## Standard protections not found in the text")
75
+ lines.append("")
76
+ for miss in output.missing_protections:
77
+ lines.append(f"- **{miss.title}**: {miss.detail}")
78
+ lines.append("")
79
+
80
+ if output.key_terms:
81
+ lines.append("## Key numbers, dates, and notice windows")
82
+ lines.append("")
83
+ lines.append("| Kind | Value | Location | Context |")
84
+ lines.append("|---|---|---|---|")
85
+ for term in output.key_terms[:40]:
86
+ ctx = term.context.replace("|", "\\|").replace("\n", " ")
87
+ lines.append(f"| {term.kind} | `{term.value}` | `{term.location}` | {ctx} |")
88
+ lines.append("")
89
+
90
+ path.write_text("\n".join(lines), encoding="utf-8")
91
+
92
+
93
+ _HTML_CSS = """
94
+ body {
95
+ margin:0; padding:36px 24px 72px;
96
+ font-family:system-ui,-apple-system,Segoe UI,sans-serif;
97
+ color:#111; background:#fff; line-height:1.55;
98
+ }
99
+ main { max-width:980px; margin:0 auto; }
100
+ header { border-bottom:2px solid #111; padding-bottom:16px; margin-bottom:24px; }
101
+ h1 { margin:0 0 6px; font-size:26px; }
102
+ h2 { margin:32px 0 12px; font-size:17px; border-bottom:1px solid #e4e4e7; padding-bottom:6px; }
103
+ .caveat {
104
+ padding:10px 14px; border-left:3px solid #71717a; background:#fafafa;
105
+ font-size:13px; color:#3f3f46; margin-bottom:20px;
106
+ }
107
+ .headline { font-family:Georgia,serif; font-size:18px; margin:12px 0 18px; }
108
+ .meta {
109
+ font-family:ui-monospace,Consolas,monospace; font-size:12.5px;
110
+ color:#52525b; display:flex; flex-wrap:wrap; gap:14px;
111
+ }
112
+ .counts { display:flex; flex-wrap:wrap; gap:14px; margin:16px 0 24px; }
113
+ .count {
114
+ padding:10px 14px; border:1px solid #e4e4e7; border-radius:2px;
115
+ font-family:ui-monospace,Consolas,monospace;
116
+ }
117
+ .count strong { font-size:20px; display:block; }
118
+ .count.red strong { color:#b91c1c; }
119
+ .count.blue strong { color:#1d4ed8; }
120
+ .row {
121
+ display:grid; grid-template-columns:220px 1fr; gap:20px;
122
+ padding:14px 0; border-bottom:1px solid #f0f0f2;
123
+ }
124
+ .margin-col {
125
+ border-right:1.5px solid #fca5a5; padding-right:16px; text-align:right;
126
+ }
127
+ .tag {
128
+ display:inline-block; padding:2px 6px; border-radius:2px;
129
+ font-family:ui-monospace,Consolas,monospace; font-size:11px; text-transform:uppercase;
130
+ }
131
+ .tag-red { background:#fee2e2; color:#b91c1c; }
132
+ .tag-blue { background:#dbeafe; color:#1d4ed8; }
133
+ .loc {
134
+ font-family:ui-monospace,Consolas,monospace; font-size:11.5px;
135
+ color:#71717a; margin-top:4px;
136
+ }
137
+ blockquote {
138
+ margin:8px 0; padding:8px 12px; border-left:2px solid #d4d4d8;
139
+ font-family:Georgia,serif; font-size:14px; background:#fafafa;
140
+ }
141
+ .why { font-size:13.5px; color:#3f3f46; margin:6px 0; }
142
+ .ask {
143
+ margin-top:8px; padding:8px 10px; border:1px solid #e4e4e7;
144
+ font-size:13px; background:#fff;
145
+ }
146
+ table { width:100%; border-collapse:collapse; font-size:13px; }
147
+ th, td { text-align:left; vertical-align:top; padding:8px; border-bottom:1px solid #e4e4e7; }
148
+ th { font-size:11px; color:#71717a; text-transform:uppercase; }
149
+ code { font-family:ui-monospace,Consolas,monospace; font-size:12px; }
150
+ .print-btn {
151
+ float:right; padding:6px 12px; border:1px solid #111;
152
+ background:#fff; cursor:pointer; border-radius:2px;
153
+ }
154
+ @media print { .print-btn { display:none; } }
155
+ @media (max-width: 720px) {
156
+ .row { grid-template-columns:1fr; }
157
+ .margin-col {
158
+ border-right:none; border-left:2px solid #fca5a5;
159
+ padding-left:12px; text-align:left;
160
+ }
161
+ }
162
+ """
163
+
164
+
165
+ def _render_note_html(note: MarginNote) -> str:
166
+ esc = html.escape
167
+ tone_cls = "tag-blue" if note.tone == "blue" else "tag-red"
168
+ sev_label = "checked" if note.severity == "ok" else note.severity
169
+ ask_html = (
170
+ f'<div class="ask"><strong>Ask before signing:</strong> '
171
+ f"{esc(note.suggested_question)}</div>"
172
+ if note.suggested_question
173
+ else ""
174
+ )
175
+ return (
176
+ '<div class="row">'
177
+ '<div class="margin-col">'
178
+ f'<span class="tag {tone_cls}">{esc(note.margin_tag)}</span>'
179
+ f'<div class="loc">{esc(sev_label)} · {esc(note.location)}</div>'
180
+ "</div>"
181
+ "<div>"
182
+ f"<strong>{esc(note.title)}</strong>"
183
+ f"<blockquote>“{esc(note.quote)}”</blockquote>"
184
+ f"<p>{esc(note.explanation)}</p>"
185
+ f'<p class="why">{esc(note.why_it_matters)}</p>'
186
+ f"{ask_html}"
187
+ "</div>"
188
+ "</div>"
189
+ )
190
+
191
+
192
+ def _write_review_html(path: Path, output: FinePrintOutput) -> None:
193
+ esc = html.escape
194
+ meta = output.document
195
+ notes_html = (
196
+ "".join(_render_note_html(n) for n in output.notes)
197
+ if output.notes
198
+ else "<p>No specific risk clauses or protections were matched.</p>"
199
+ )
200
+
201
+ missing_html = ""
202
+ if output.missing_protections:
203
+ items = "".join(
204
+ "<li>"
205
+ f"<strong>{esc(m.title)}</strong>: {esc(m.detail)}<br>"
206
+ f"<em>Ask: {esc(m.suggested_question)}</em>"
207
+ "</li>"
208
+ for m in output.missing_protections
209
+ )
210
+ missing_html = f"<h2>Not mentioned in the text</h2><ul>{items}</ul>"
211
+
212
+ terms_html = ""
213
+ if output.key_terms:
214
+ rows = "".join(
215
+ "<tr>"
216
+ f"<td><code>{esc(t.kind)}</code></td>"
217
+ f"<td><strong>{esc(t.value)}</strong></td>"
218
+ f"<td><code>{esc(t.location)}</code></td>"
219
+ f"<td>{esc(t.context)}</td>"
220
+ "</tr>"
221
+ for t in output.key_terms[:50]
222
+ )
223
+ terms_html = (
224
+ "<h2>Key numbers, dates, and notice windows</h2>"
225
+ "<table><thead><tr><th>Kind</th><th>Value</th><th>Location</th><th>Context</th>"
226
+ f"</tr></thead><tbody>{rows}</tbody></table>"
227
+ )
228
+
229
+ checklist_html = ""
230
+ if output.checklist:
231
+ items = "".join(
232
+ "<li>"
233
+ f"<strong>[{esc(c.priority.upper())}] {esc(c.topic)}</strong>"
234
+ + (f" (<code>{esc(c.location)}</code>)" if c.location else "")
235
+ + f": {esc(c.question)}"
236
+ "</li>"
237
+ for c in output.checklist
238
+ )
239
+ checklist_html = f"<h2>Questions to ask before signing</h2><ul>{items}</ul>"
240
+
241
+ pages_span = f"<span>pages: {meta.pages}</span>" if meta.pages is not None else ""
242
+ doc = f"""<!doctype html>
243
+ <html lang="en">
244
+ <head>
245
+ <meta charset="utf-8">
246
+ <title>Fine Print Review — {esc(meta.filename)}</title>
247
+ <style>{_HTML_CSS}</style>
248
+ </head>
249
+ <body>
250
+ <main>
251
+ <header>
252
+ <button class="print-btn" onclick="window.print()">Print / Save PDF</button>
253
+ <h1>Fine Print Review — {esc(meta.filename)}</h1>
254
+ <div class="meta">
255
+ <span>type: {esc(meta.doc_type)}</span>
256
+ <span>perspective: {esc(meta.party_side_label)}</span>
257
+ <span>format: {esc(meta.file_format)}</span>
258
+ {pages_span}
259
+ <span>words: {meta.word_count:,}</span>
260
+ <span>writer: {esc(output.writer_mode)}</span>
261
+ </div>
262
+ </header>
263
+ <div class="caveat">{esc(output.caveat)}</div>
264
+ <p class="headline">{esc(output.summary_headline)}</p>
265
+ <div class="counts">
266
+ <div class="count red"><strong>{output.risk_counts.get("high", 0)}</strong>high risk</div>
267
+ <div class="count"><strong>{output.risk_counts.get("medium", 0)}</strong>medium risk</div>
268
+ <div class="count"><strong>{output.risk_counts.get("low", 0)}</strong>minor notes</div>
269
+ <div class="count"><strong>{len(output.missing_protections)}</strong>missing protections</div>
270
+ <div class="count blue">
271
+ <strong>{output.risk_counts.get("checked", 0)}</strong>checked protections
272
+ </div>
273
+ </div>
274
+ <h2>Notes in the margin</h2>
275
+ {notes_html}
276
+ {missing_html}
277
+ {checklist_html}
278
+ {terms_html}
279
+ </main>
280
+ </body>
281
+ </html>
282
+ """
283
+ path.write_text(doc, encoding="utf-8")
284
+
285
+
286
+ def write_reports(folder: str, output: FinePrintOutput) -> list[str]:
287
+ """Write printable HTML review, Markdown checklist, and terms CSV into ``folder``."""
288
+ out = Path(folder).expanduser().resolve()
289
+ out.mkdir(parents=True, exist_ok=True)
290
+ stem = safe_stem(output.document.filename)
291
+
292
+ html_path = out / f"{stem}.review.html"
293
+ md_path = out / f"{stem}.checklist.md"
294
+ csv_path = out / f"{stem}.terms.csv"
295
+
296
+ _write_review_html(html_path, output)
297
+ _write_checklist_md(md_path, output)
298
+ _write_terms_csv(csv_path, output.key_terms)
299
+ return [str(html_path), str(md_path), str(csv_path)]