"""Command line for Clairic on MLX.""" from __future__ import annotations import argparse import json from pathlib import Path from clairic_mlx.pipeline import build_demo from clairic_mlx.weights import convert, load SAMPLE_STATE = """Coffee House 12 Main Street Latte 4.50 Muffin 3.25 Subtotal 7.75 Tax 0.64 Total 8.39 Date: 2026-03-14 """ SAMPLE_FIELDS = { "merchant": {"type": "text", "instructions": "The merchant name."}, "total": {"type": "number", "decimals": 2}, "issued": {"type": "date", "instructions": "The receipt date."}, "items": { "type": "list", "items": "text", "max_items": 2, "instructions": "The purchased item names, in order.", }, } def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description="Run Cloudflare Clairic on Apple MLX") sub = parser.add_subparsers(dest="command", required=True) demo = sub.add_parser("demo", help="Run the receipt example on a tiny random model") demo.add_argument("--state", default=SAMPLE_STATE) demo.add_argument("--fields", type=Path, help="JSON object of field specs") extract = sub.add_parser("extract", help="Extract fields with a local Clairic snapshot") extract.add_argument("--model", required=True, help="Hugging Face id or local snapshot") extract.add_argument("--state", required=True) extract.add_argument("--fields", type=Path, required=True) extract.add_argument("--quant", type=int, choices=(4, 8)) extract.add_argument("--reference-date") extract.add_argument("--quantiles", action="store_true") exported = sub.add_parser("convert", help="Write MLX weights, optionally quantized") exported.add_argument("--model", required=True) exported.add_argument("--out", type=Path, required=True) exported.add_argument("--bits", type=int, choices=(4, 8)) args = parser.parse_args(argv) if args.command == "demo": fields = json.loads(args.fields.read_text()) if args.fields else SAMPLE_FIELDS print(json.dumps(build_demo().extract(args.state, fields), indent=2, ensure_ascii=False)) return if args.command == "extract": fields = json.loads(args.fields.read_text()) extractor = load(args.model, quant_bits=args.quant) response = extractor.extract( args.state, fields, reference_date=args.reference_date, include_quantiles=args.quantiles, ) print(json.dumps(response, indent=2, ensure_ascii=False)) return convert(args.model, args.out, bits=args.bits) print(f"Wrote MLX weights to {args.out}") if __name__ == "__main__": main()