casepatch 0.5.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.
Files changed (104) hide show
  1. casepatch/__init__.py +10 -0
  2. casepatch/__main__.py +143 -0
  3. casepatch/agent/__init__.py +4 -0
  4. casepatch/agent/__main__.py +22 -0
  5. casepatch/agent/run.py +611 -0
  6. casepatch/agent/tools.py +836 -0
  7. casepatch/agent/verify.py +329 -0
  8. casepatch/bench/__init__.py +1 -0
  9. casepatch/bench/categories_eval.py +161 -0
  10. casepatch/bench/detectors.py +91 -0
  11. casepatch/bench/parsers.py +104 -0
  12. casepatch/bench/replay.py +283 -0
  13. casepatch/bench/score.py +582 -0
  14. casepatch/client/__init__.py +11 -0
  15. casepatch/client/cli.py +51 -0
  16. casepatch/client/cloud.py +103 -0
  17. casepatch/client/core.py +156 -0
  18. casepatch/client/local.py +67 -0
  19. casepatch/core.py +269 -0
  20. casepatch/docs/__init__.py +7 -0
  21. casepatch/docs/byok.py +264 -0
  22. casepatch/docs/categories.py +609 -0
  23. casepatch/docs/category_fakes.py +439 -0
  24. casepatch/docs/category_vocab.py +197 -0
  25. casepatch/docs/consistency.py +1181 -0
  26. casepatch/docs/cues.py +27 -0
  27. casepatch/docs/data/LICENSES.md +11 -0
  28. casepatch/docs/data/eval_key_fingerprints.json +11 -0
  29. casepatch/docs/data/given_names_intl.txt +76865 -0
  30. casepatch/docs/data/given_names_us.txt +4553 -0
  31. casepatch/docs/detect.py +451 -0
  32. casepatch/docs/editor_pick.py +862 -0
  33. casepatch/docs/extract.py +639 -0
  34. casepatch/docs/fonts.py +127 -0
  35. casepatch/docs/forms.py +359 -0
  36. casepatch/docs/hosted_detect.py +225 -0
  37. casepatch/docs/hosted_edit.py +461 -0
  38. casepatch/docs/iddoc.py +232 -0
  39. casepatch/docs/legal.py +791 -0
  40. casepatch/docs/letters.py +177 -0
  41. casepatch/docs/model.py +88 -0
  42. casepatch/docs/models.py +21 -0
  43. casepatch/docs/mrz.py +103 -0
  44. casepatch/docs/native.py +1521 -0
  45. casepatch/docs/pack_refresh.py +148 -0
  46. casepatch/docs/pipeline.py +602 -0
  47. casepatch/docs/render.py +923 -0
  48. casepatch/docs/resolve.py +737 -0
  49. casepatch/docs/review_html.py +90 -0
  50. casepatch/docs/verify.py +240 -0
  51. casepatch/docs/visual.py +362 -0
  52. casepatch/fixtures/dispute.json +29 -0
  53. casepatch/fonts/DejaVuSans.ttf +0 -0
  54. casepatch/fonts/LICENSE-DejaVu.txt +78 -0
  55. casepatch/fonts/LICENSE-Liberation.txt +130 -0
  56. casepatch/fonts/LiberationMono-Bold.ttf +0 -0
  57. casepatch/fonts/LiberationMono-Regular.ttf +0 -0
  58. casepatch/fonts/LiberationSans-Bold.ttf +0 -0
  59. casepatch/fonts/LiberationSans-Regular.ttf +0 -0
  60. casepatch/fonts/LiberationSerif-Bold.ttf +0 -0
  61. casepatch/fonts/LiberationSerif-Regular.ttf +0 -0
  62. casepatch/fonts/README.md +7 -0
  63. casepatch/hosted/__init__.py +9 -0
  64. casepatch/hosted/cli.py +137 -0
  65. casepatch/hosted/client.py +396 -0
  66. casepatch/hosted/config.py +170 -0
  67. casepatch/hosted/editbench.py +482 -0
  68. casepatch/hosted/evalscore.py +323 -0
  69. casepatch/hosted/faledit.py +147 -0
  70. casepatch/hosted/ledger.py +117 -0
  71. casepatch/hosted/localvlm.py +164 -0
  72. casepatch/hosted/modeleval.py +884 -0
  73. casepatch/hosted/pricing.py +270 -0
  74. casepatch/ledger.py +161 -0
  75. casepatch/metering/__init__.py +11 -0
  76. casepatch/metering/active.py +49 -0
  77. casepatch/metering/collector.py +184 -0
  78. casepatch/metering/cost_model.py +110 -0
  79. casepatch/metering/events.py +293 -0
  80. casepatch/pricing.py +32 -0
  81. casepatch/py.typed +0 -0
  82. casepatch/review.py +387 -0
  83. casepatch/server.py +177 -0
  84. casepatch/web/app.js +145 -0
  85. casepatch/web/index.html +23 -0
  86. casepatch/web/json-import.js +74 -0
  87. casepatch/web/styles.css +1 -0
  88. casepatch-0.5.0.dist-info/METADATA +106 -0
  89. casepatch-0.5.0.dist-info/RECORD +104 -0
  90. casepatch-0.5.0.dist-info/WHEEL +5 -0
  91. casepatch-0.5.0.dist-info/entry_points.txt +3 -0
  92. casepatch-0.5.0.dist-info/licenses/LICENSE +202 -0
  93. casepatch-0.5.0.dist-info/licenses/NOTICE +94 -0
  94. casepatch-0.5.0.dist-info/top_level.txt +2 -0
  95. casepatch_studio/__init__.py +2 -0
  96. casepatch_studio/__main__.py +47 -0
  97. casepatch_studio/agent_review.py +242 -0
  98. casepatch_studio/assets.py +81 -0
  99. casepatch_studio/compare_api.py +129 -0
  100. casepatch_studio/curate_names.py +116 -0
  101. casepatch_studio/live_compare.py +401 -0
  102. casepatch_studio/server.py +1058 -0
  103. casepatch_studio/setup.py +98 -0
  104. casepatch_studio/worker.py +189 -0
casepatch/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """CasePatch: a fixture-only proof of decision-preserving case transformation."""
2
+
3
+ __version__ = "0.5.0"
4
+
5
+
6
+ def __getattr__(name): # `from casepatch import CasePatch` without importing the client on every engine import
7
+ if name in ("CasePatch", "CasePatchError", "Result", "local_available"):
8
+ from . import client
9
+ return getattr(client, name)
10
+ raise AttributeError(name)
casepatch/__main__.py ADDED
@@ -0,0 +1,143 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import secrets
5
+ import sys
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+
9
+ from .core import PolicyError, transform
10
+ from .pricing import estimate
11
+
12
+
13
+ def exclusive_json(path, value):
14
+ with open(path, "x", encoding="utf-8", opener=lambda p, f: os.open(p, f, 0o600)) as handle:
15
+ json.dump(value, handle, ensure_ascii=False, indent=2, allow_nan=False)
16
+ handle.write("\n")
17
+
18
+
19
+ def main():
20
+ parser = argparse.ArgumentParser(prog="casepatch")
21
+ commands = parser.add_subparsers(dest="command", required=True)
22
+ gen = commands.add_parser("keygen")
23
+ gen.add_argument("--out", required=True)
24
+ run = commands.add_parser("transform")
25
+ run.add_argument("input")
26
+ run.add_argument("--key-file", required=True)
27
+ run.add_argument("--out", required=True, help="A NEW output directory; existing paths are refused")
28
+ demo = commands.add_parser("demo", help="Run bundled fictional records without setup or an account")
29
+ demo.add_argument("--out", required=True, help="A NEW output directory")
30
+ app = commands.add_parser("app", help="Open the local import, review and export product")
31
+ app.add_argument("--port", type=int, default=0, help="Local port; 0 selects a free port")
32
+ app.add_argument("--open", action="store_true", dest="open_browser", help="Open the browser after binding the local port")
33
+ app.add_argument("--rules-only", action="store_true", help="Limited mode without learned name detection")
34
+ quote = commands.add_parser("estimate", help="Preview a proposed usage price locally; no actual billing")
35
+ quote.add_argument("input", help="JSON case bundle with records, or a JSON list of records")
36
+ quote.add_argument("--monthly-used-chars", type=int, default=0, help="Assumed prior monthly account usage; not fetched")
37
+ docs = commands.add_parser("docs", help="Transform a case folder of PDFs, scans, photos, images and JSON traces (v0.3 spike)")
38
+ docs.add_argument("input_dir")
39
+ docs.add_argument("--out", required=True, help="A NEW output directory (transformed files + report.json, no identity map)")
40
+ docs.add_argument("--detector", choices=["rules", "gliner", "llm", "hosted"], default="rules",
41
+ help="Learned detector added to the rules (hosted is a disabled stub)")
42
+ docs.add_argument("--review-dir", help="Local review folder (proposals, review.html, decisions.json, case key). Default: <out>.review")
43
+ docs.add_argument("--decisions", help="decisions.json from review (accept/reject per text proposal, replace/keep/erase per region; optional _add list of {text, kind} reviewer additions)")
44
+ docs.add_argument("--no-verify", action="store_true")
45
+ docs.add_argument("--hosted-detect", action="store_true",
46
+ help="OPT-IN, bring your own key: also send each page image + its OCR text directly from this computer to "
47
+ "Anthropic (Claude Sonnet 5.5) for detection, using YOUR ANTHROPIC_API_KEY under your agreement "
48
+ "with Anthropic. Per-case estimate limit $2 (CASEPATCH_BYOK_MAX_USD_PER_CASE). "
49
+ "Model-only suggestions are applied only after you accept them in review (decisions _accept_text)")
50
+ docs.add_argument("--accept-hosted-notice", action="store_true",
51
+ help="Confirm you read the hosted-detection notice (page images leave this computer)")
52
+ from .client.cli import add_parsers as add_client_parsers
53
+ add_client_parsers(commands)
54
+ hosted = commands.add_parser("hosted", help="Hosted frontier adapters (disabled by default; spend-capped)")
55
+ hosted.add_argument("action", choices=["status", "verify"])
56
+ hosted.add_argument("--auth-check", action="store_true",
57
+ help="verify only: also call each provider's free list-models endpoint (no paid call)")
58
+ args = parser.parse_args()
59
+ if args.command in ("anonymize", "setup-local"):
60
+ from .client.cli import run as run_client
61
+ return run_client(args)
62
+ if args.command == "hosted":
63
+ from .hosted.cli import status, verify
64
+ print(verify(auth_check=args.auth_check) if args.action == "verify" else status())
65
+ return 0
66
+ if args.command == "docs":
67
+ return docs_command(args)
68
+ try:
69
+ if args.command == "app":
70
+ from .server import serve
71
+ serve(args.port, args.rules_only, args.open_browser)
72
+ return 0
73
+ if args.command == "keygen":
74
+ with open(args.out, "xb", opener=lambda p, f: os.open(p, f, 0o600)) as handle:
75
+ handle.write(secrets.token_bytes(32))
76
+ print("KEY_CREATED")
77
+ return 0
78
+ if args.command == "estimate":
79
+ value = json.loads(Path(args.input).read_text())
80
+ records = value.get("records") if isinstance(value, dict) else value
81
+ print(json.dumps(estimate(records, args.monthly_used_chars), indent=2))
82
+ return 0
83
+ if args.command == "demo":
84
+ bundle = json.loads(files("casepatch").joinpath("fixtures/dispute.json").read_text())
85
+ key = secrets.token_bytes(32)
86
+ else:
87
+ bundle = json.loads(Path(args.input).read_text())
88
+ key = Path(args.key_file).read_bytes()
89
+ # Validate everything before creating the output directory.
90
+ result = transform(bundle, key)
91
+ destination = Path(args.out)
92
+ destination.mkdir(mode=0o700, parents=False, exist_ok=False)
93
+ exclusive_json(destination / "report.json", result.report)
94
+ if result.candidate is not None:
95
+ exclusive_json(destination / "candidate.json", result.candidate)
96
+ print(result.report["status"])
97
+ return 2 if result.candidate is None else 0
98
+ except PolicyError as exc:
99
+ print("POLICY_ERROR: " + str(exc), file=sys.stderr)
100
+ return 2
101
+ except (OSError, ValueError, TypeError, KeyError, OverflowError):
102
+ print("INPUT_OR_OUTPUT_ERROR: inspect local files; no source text logged", file=sys.stderr)
103
+ return 2
104
+
105
+
106
+ def docs_command(args):
107
+ try:
108
+ from .docs.pipeline import run
109
+ except ImportError:
110
+ print("DOCS_EXTRAS_MISSING: pip install -e '.[docs]'", file=sys.stderr)
111
+ return 2
112
+ hosted = None
113
+ if args.hosted_detect:
114
+ from .docs.hosted_detect import NOTICE, HostedNotAllowed, HostedPageDetector
115
+ if not args.accept_hosted_notice:
116
+ print("HOSTED_NOTICE: " + NOTICE + "\nRe-run with --accept-hosted-notice to proceed.", file=sys.stderr)
117
+ return 2
118
+ try:
119
+ hosted = HostedPageDetector.from_user(True)
120
+ except HostedNotAllowed as exc:
121
+ print("HOSTED_DISABLED: " + str(exc), file=sys.stderr); return 2
122
+ try:
123
+ report, *_ = run(args.input_dir, args.out, args.detector, args.review_dir, args.decisions, not args.no_verify, hosted=hosted)
124
+ except FileExistsError:
125
+ print("OUTPUT_DIRECTORY_EXISTS", file=sys.stderr); return 2
126
+ except (RuntimeError, ValueError) as exc:
127
+ print("DOCS_ERROR: " + str(exc).split(":")[0], file=sys.stderr); return 2
128
+ ver = report.get("verification", {})
129
+ for doc_id, d in report["documents"].items():
130
+ v = ver.get(doc_id, {})
131
+ print(f"{doc_id} {d['type']:5} replaced={sum(d['replacements_by_kind'].values()):3} regions_edited={len(d['edited_regions'])} "
132
+ f"residual={v.get('residual_original_values', '-')} facts_missing={len(v.get('facts_missing', [])) if v else '-'} "
133
+ f"pixel_diff={','.join(p['verdict'] for p in v.get('pixel_diff', [])) or '-'}")
134
+ h = report.get("hosted_detection")
135
+ if h:
136
+ print(f"hosted={h['provider']}:{h['model']} pages_sent={h['pages_sent']} model_only_suggestions={h['model_only_values']} "
137
+ f"accepted={h['model_only_values_accepted']} error={h['error'] or '-'}")
138
+ print(f"needs_review={len(report['needs_review'])} status={report['status']} report={args.out}/report.json")
139
+ return 0
140
+
141
+
142
+ if __name__ == "__main__":
143
+ raise SystemExit(main())
@@ -0,0 +1,4 @@
1
+ """CasePatch agent mode (2026-11-12 redesign, bench/agentic/RESULTS.md): a frontier model does the reading and decides
2
+ what to replace; CasePatch's own working pieces are exposed to it as tools (OCR with boxes, font-matched in-place text
3
+ replacement, erase, native PDF text edits), and CasePatch's deterministic checks verify the result and feed failures
4
+ back for a bounded number of fix rounds. Product use is BYOK only (the customer's own key, off by default)."""
@@ -0,0 +1,22 @@
1
+ import argparse, json, os, sys
2
+
3
+ from .run import run_case, DEFAULT_MODEL, ESCALATE_MODEL
4
+
5
+ ap = argparse.ArgumentParser(prog="python -m casepatch.agent", description="CasePatch agent mode (BYOK; off by default)")
6
+ ap.add_argument("input"); ap.add_argument("--out", required=True)
7
+ ap.add_argument("--enable-agent", action="store_true", help="agent mode is off unless this flag (or CASEPATCH_AGENT=1) is given")
8
+ ap.add_argument("--eval", action="store_true", help="bench only: CasePatch eval key, public samples, spend ledger")
9
+ ap.add_argument("--budget", type=float, default=6.0, help="case ceiling (USD)"); ap.add_argument("--doc-budget", type=float, default=1.5); ap.add_argument("--faces", choices=["swap", "keep"], default="swap"); ap.add_argument("--model", default=DEFAULT_MODEL); ap.add_argument("--escalate", default=ESCALATE_MODEL)
10
+ ap.add_argument("--fix-rounds", type=int, default=2); ap.add_argument("--workers", type=int, default=4); ap.add_argument("--run", default="run")
11
+ ap.add_argument("--effort", default="high"); ap.add_argument("--only", nargs="*")
12
+ ap.add_argument("--replay", metavar="LOGS_DIR", help="re-execute a recorded run's transcripts with the local tools: no key, no network, $0")
13
+ a = ap.parse_args()
14
+ if a.replay:
15
+ r = run_case(a.input, a.out, mode="replay", replay_dir=a.replay, budget=a.budget, doc_budget=a.doc_budget, faces=a.faces, fix_rounds=a.fix_rounds, workers=a.workers)
16
+ print(json.dumps({k: r[k] for k in ("case", "wall_s", "spent_usd", "model_calls")} | {"open_issues": len(r["review_issues"]), "mode": "replay"}))
17
+ sys.exit(0)
18
+ if not (a.enable_agent or os.environ.get("CASEPATCH_AGENT") == "1"):
19
+ sys.exit("Agent mode is off by default. It sends document pages to your own Anthropic account; pass --enable-agent to opt in.")
20
+ r = run_case(a.input, a.out, mode="eval" if a.eval else "product", budget=a.budget, doc_budget=a.doc_budget, faces=a.faces, model=a.model, escalate=a.escalate or None,
21
+ fix_rounds=a.fix_rounds, workers=a.workers, run_tag=a.run, effort=a.effort, only=a.only)
22
+ print(json.dumps({k: r[k] for k in ("case", "wall_s", "spent_usd", "list_usd", "model_calls")} | {"open_issues": len(r["review_issues"])}))