Skip to content

Texomy vs a script from your AI

Your agent can write a Python parser in a minute, and it runs locally for free. Texomy makes the result easier to review and to keep correct as the formats add up.

Python script from your AITexomy
Cost per documentNoneNone
Runs offlineYesYes
What a reviewer readsRegexes, group names and conversion codeNamed types, fields and patterns
OutputWhatever the script builds, often flat strings and numbersA typed tree with offsets and typed values
TestsOnly if someone writes themExpected output in *.test.yml, run with texomy test
Overlapping patternsThe first match in code order winsDefined rules: explicit order, length, position, specificity, fixed text
Many formatsOne script per format, each with its own structureOne language, with types shared through imports and packages
Shared fieldsA shared prefix or helper, if the author factored one outDeclared once on a parent type and inherited by its subtypes
A new variant of a valueEdit the regex, then the code that maps the matchAdd a subtype: every pattern that references the parent accepts it
What runsCode from your AI, with your permissionsA spec: data that cannot touch files or the network
RuntimePython; this example uses only the standard libraryA single native binary, the same result on every machine
Seeing the resultPrint statements and a debuggerStudio highlights every match in the text

The whole parser, both ways

Both read the invoice example into the same 13 facts: supplier, address, invoice number, issue and due dates, service period, amount payable, four line items and three references. The spec is longer because it also reads subtotals, tax, payment terms, more labels and four date forms, and it declares its numbers, money and dates in values.yml, shown below invoices.yml.

parse_invoices.py
import json
import re
import sys
from datetime import datetime

LABELS = {
    "supplier": r"Supplier|Vendor|Seller|From",
    "address": r"Address|Supplier address|Remit to address",
    "invoice_number": r"Invoice(?: number| no\.?| #)?",
    "issue_date": r"Issued(?: on)?|Issue date|Date of issue|Invoice date|Date",
    "due_date": r"Due date|Payment due|Pay by",
    "service_period": r"Services covered|Service period|Billing period|Period",
    "amount_payable": r"Amount payable|Amount due|Total due|Balance due|Total",
    "order": r"Order reference|Purchase order|PO(?: number)?",
    "task_order": r"Task order",
    "contract": r"Contract(?: number| no\.?)?",
}
COLUMNS = {
    "description": r"Description|Item|Service|Product|Particulars|Details|Activity|School",
    "quantity": r"Qty\.?|Quantity|Hours|Days|Weeks|Months|Units",
    "rate": r"Rate|(?:Hourly|Daily|Weekly|Monthly) rate|Unit price|Price|Unit cost",
    "amount": r"Amount|Total|Line total",
}
CURRENCIES = {"USD": "USD", "US$": "USD", "$": "USD", "EUR": "EUR", "€": "EUR", "GBP": "GBP", "£": "GBP"}
UNITS = {"hour": "hour", "hr": "hour", "h": "hour", "day": "day", "week": "week", "wk": "week", "month": "month"}
DATE_FORMATS = ["%Y-%m-%d", "%d.%m.%Y", "%d %B %Y", "%d %b %Y", "%B %d, %Y", "%b %d, %Y"]
CUR = r"USD|US\$|\$|EUR|€|GBP|£"
MONEY = re.compile(rf"(?:(?P<cur>{CUR}) ?)?(?P<num>\d{{1,3}}(?:,\d{{3}})*(?:\.\d+)?)(?: ?(?P<cur2>{CUR}))?"
                   r"(?:(?: ?/ ?| per )(?P<unit>[a-z]+?)s?\b)?", re.I)
CODE = re.compile(r"[A-Za-z]*[-/]?\d[A-Za-z0-9]*(?:[-/.][A-Za-z0-9]+)*")


def date(text):
    for fmt in DATE_FORMATS:
        try:
            return datetime.strptime(text.strip(), fmt).date().isoformat()
        except ValueError:
            pass
    return None


def money(text):
    for m in MONEY.finditer(text):
        cur = m.group("cur") or m.group("cur2")
        if cur:
            unit = m.group("unit") and UNITS.get(m.group("unit").lower())
            return {"amount": m.group("num").replace(",", ""), "currency": CURRENCIES[cur.upper()], "per": unit}
    return None


def header_fact(kind, value):
    if kind in ("issue_date", "due_date"):
        return date(value)
    if kind == "service_period":
        parts = re.split(r"\s+(?:through|to|until|-)\s+|\s*–\s*", value, maxsplit=1)
        if len(parts) == 2 and date(parts[0]) and date(parts[1]):
            return {"start": date(parts[0]), "end": date(parts[1])}
        return None
    if kind == "amount_payable":
        amount = money(value)
        return amount and {"amount": amount["amount"], "currency": amount["currency"]}
    if kind in ("invoice_number", "order", "task_order", "contract"):
        code = CODE.fullmatch(value.strip())
        return code and code.group()
    return value.strip()


def column_of(cell):
    for name, pattern in COLUMNS.items():
        if re.fullmatch(pattern, cell.strip(), re.I):
            return name
    return None


def pieces(line):
    return [(m.start(), m.group()) for m in re.finditer(r"\S+(?: \S+)*", line)]


def read_row(line, columns):
    # A column runs from the start of its header to the start of the next one.
    cells = {}
    for start, text in pieces(line):
        end = start + len(text)
        overlaps = [(min(end, hi) - max(start, lo), col) for lo, hi, col in columns]
        size, col = max(overlaps, key=lambda o: o[0])
        if size * 2 <= len(text):
            return None
        if col:
            cells[col] = (cells.get(col, "") + " " + text).strip()
    return cells if len(cells) >= 2 else None


def line_item(section, cells):
    item = {"section": section, "description": cells.get("description"),
            "quantity": None, "rate": None, "per": None, "amount": None, "currency": None}
    if "quantity" in cells:
        item["quantity"] = cells["quantity"].replace(",", "")
    if "rate" in cells:
        rate = money(cells["rate"]) or {}
        item["rate"], item["per"] = rate.get("amount"), rate.get("per")
    if "amount" in cells:
        amount = money(cells["amount"]) or {}
        item["amount"], item["currency"] = amount.get("amount"), amount.get("currency")
    return item


def parse(text):
    facts, lines, i = [], text.splitlines(), 0
    while i < len(lines):
        line = lines[i]
        heads = pieces(line)
        names = [column_of(cell) for _, cell in heads]
        if len({n for n in names if n}) >= 2:
            section = lines[i - 1].strip() if i > 0 and lines[i - 1].strip() else None
            starts = [start for start, _ in heads] + [10**6]
            columns = [(0 if k == 0 else starts[k], starts[k + 1], names[k]) for k in range(len(heads))]
            i += 1
            while i < len(lines) and (cells := read_row(lines[i], columns)):
                facts.append({"type": "line_item", "value": line_item(section, cells)})
                i += 1
            continue
        for kind, label in LABELS.items():
            m = re.match(rf"\s*(?:{label})\s*(?::|#|\s)\s*(.+)$", line, re.I)
            if m and (value := header_fact(kind, m.group(1))) is not None:
                facts.append({"type": kind, "value": value})
                break
        i += 1
    return facts


for fact in parse(sys.stdin.read()):
    print(json.dumps(fact, ensure_ascii=False))
invoices.yml, then values.yml
# Invoices: the facts an invoice states about itself, each a label and its value, and the rows of its
# tables of charges. Slash dates are not read, because their day and month order is not stated.

$imports: 'values'
$flags: [ CASE_INSENSITIVE ]

Invoice:
  $local:
    # Between a label and its value: a colon, a number sign, both, or a space.
    Is: '[ \t]*#?[ \t]*:[ \t]*|[ \t]*#[ \t]*|[ \t]+'
    # Up to the end of the line.
    Name: '\S([^\r\n]*\S)?'
    # A document number: INV-20241219-001, 2025-0042, RE-24/118, 4500123987.
    Code:
      $flags: [ -CASE_INSENSITIVE ]
      $patterns: '[A-Za-z]*[-/]?\d[A-Za-z0-9]*([-/.][A-Za-z0-9]+)*'
    Till: '[ \t]+(through|thru|to|until|till)[ \t]+|[ \t]*[-–—][ \t]*'

  Supplier:
    $local:
      Label: [ 'Supplier', 'Vendor', 'Seller', 'Contractor', 'From', 'Billed by', '(Service )?provider' ]
    $fields: { name: Name }
    # Only after a colon: 'services from 2025-01-01' names no supplier.
    $patterns: '${Label}[ \t]*:[ \t]*#{name}'
    $value: '#{name}'

  Address:
    $local:
      Label: [ 'Address', '(Supplier|Remit to|Billing) address' ]
    $fields: { address: Name }
    $patterns: '${Label}[ \t]*:[ \t]*#{address}'
    $value: '#{address}'

  Id:
    $local:
      Label: [ 'Invoice', 'Invoice (number|no\.?|id)', 'Inv\. no\.?' ]
    $fields: { code: Code }
    $patterns: '${Label}${Is}#{code}'
    $value: '#{code}'

  # A date the invoice states: each kind declares its label.
  Dates:
    $flags: [ MULTILINE ]
    $fields: { date: Date }
    $patterns: '${Label}${Is}#{date}'
    $value: '#{date}'

    Issue:
      $local:
        # A bare 'Date' counts only at the start of a line, not in 'Due date' or 'Order date'.
        Label: [ 'Issued( on)?', 'Issue date', 'Date of issue', 'Invoice date', 'Dated', '^[ \t]*Date' ]

    Due:
      $local:
        Label: [ 'Due date', '(Payment )?due( on| by)?', 'Pay by' ]

  ServicePeriod:
    $local:
      Label:
        - 'Services covered'
        - 'Services( rendered| provided| performed)?'
        - '(Service|Billing|Invoice) period'
        - 'Period( of service)?'
        - 'For the period'
    $fields: { start: Date, end: Date }
    $patterns: '${Label}${Is}(from[ \t]+)?#{start}${Till}#{end}'
    $value: { start: '#{start}', end: '#{end}' }

  # An amount the invoice states: each kind declares its label.
  Amounts:
    $fields: { amount: Money::Amount }
    $patterns: '${Label}${Is}#{amount}'
    $value: { amount: '#{amount.amount}', currency: '#{amount.currency}' }

    Subtotal:
      $local:
        Label: [ 'Sub-?total' ]

    Tax:
      $local:
        # Sales tax, VAT 20%, Tax (8%)
        Label: [ '((Sales )?tax|VAT|GST)( \(?\d+(\.\d+)?%\)?)?' ]

    Payable:
      $local:
        Label:
          - 'Amount (payable|due)'
          - 'Total( amount)? (payable|due)'
          - 'Balance due'
          - 'Please pay'
          - '(Grand|Invoice) total'
          - 'Total'

  # When payment is due, counted in days: Net 30, payable within 30 days.
  PaymentTerms:
    $local: { Days: '\d+' }
    $fields: { days: Days }
    $patterns:
      - 'Net ?#{days}'
      - '(payable |due )?(within|in) #{days} days'
    $value: '#{days}'

  # A reference to another document: each kind declares its label.
  Reference:
    $fields: { code: Code }
    $patterns: '${Label}${Is}#{code}'
    $value: '#{code}'

    Order:
      $local:
        Label:
          - '(Purchase )?order( reference| ref\.?| number| no\.?)?'
          - 'P\.?O\.?( number| no\.?)?'

    TaskOrder:
      $local:
        Label: 'Task order( number| no\.?)?'

    Contract:
      $local:
        Label:
          - 'Contract( reference| ref\.?| number| no\.?)?'
          - 'Agreement( number| no\.?)?'

    Other:
      $local:
        Label: '((Our|Your|Customer) )?(reference|ref\.?)( number| no\.?)?'

# One row of a table of charges. The header names the columns, and a caption above the header, such as
# 'Tutoring', names the section of every row.
LineItem:
  $local:
    Text: '\S([^\r\n]*\S)?'
    DescriptionHeader: [ 'Description', 'Item', 'Service', 'Product', 'Particulars', 'Details', 'Activity', 'School' ]
    QuantityHeader: [ 'Qty\.?', 'Quantity', 'Hours', 'Days', 'Weeks', 'Months', 'Units' ]
    RateHeader: [ 'Rate', '(Hourly|Daily|Weekly|Monthly) rate', 'Unit price', 'Price', 'Unit cost' ]
    AmountHeader: [ 'Amount', 'Total', 'Line total' ]
  $fields:
    section: Text
    description: Text
    quantity: Number
    rate: Money
    amount: Money::Amount
  $tables:
    $caption: section
    $columns:
      description: DescriptionHeader
      quantity: QuantityHeader
      rate: RateHeader
      amount: AmountHeader
  $value:
    section: '[#{section}]'
    description: '#{description}'
    quantity: '[#{quantity}]'
    rate: '[#{rate.amount}]'
    per: '[#{rate.per}]'
    amount: '[#{amount.amount}]'
    currency: '[#{amount.currency}]'

# ── values.yml ──

# Values that invoices state: numbers, amounts of money, rates and dates.

Number:
  $local: { Digits: '\d+' }
  $fields:
    groups: { $type: 'Digits[]', $separator: ',' }
    fraction: Digits
  $patterns: '#{groups}(\.#{fraction})?'
  $value: '#{groups}[.#{fraction}]'

Currency:
  Usd: { $patterns: [ 'USD', 'US\$', '\$' ], $value: 'USD' }
  Eur: { $patterns: [ 'EUR', '€' ], $value: 'EUR' }
  Gbp: { $patterns: [ 'GBP', '£' ], $value: 'GBP' }

Money:
  $fields: { amount: Number, currency: Currency }
  $value: { amount: '#{amount}', currency: '#{currency}' }

  # USD 5,000.00, $640.00, 3,230.00 EUR
  Amount:
    $patterns:
      - '#{currency} ?#{amount}'
      - '#{amount} ?#{currency}'

  # A price for one unit of time or work: USD 20/hour, $150 per day.
  Rate:
    $flags: [ CASE_INSENSITIVE ]
    $local:
      Unit:
        Hour: { $patterns: [ 'hours?', 'hrs?', 'h' ], $value: 'hour' }
        Day: { $patterns: [ 'days?', 'd' ], $value: 'day' }
        Week: { $patterns: [ 'weeks?', 'wk' ], $value: 'week' }
        Month: { $patterns: [ 'months?', 'mo' ], $value: 'month' }
        Item: { $patterns: [ 'units?', 'items?', 'pcs', 'each', 'ea' ], $value: 'unit' }
    $fields: { per: Unit }
    $patterns: '(#{currency} ?#{amount}|#{amount} ?#{currency})( ?/ ?| per )#{per}'
    $value: { amount: '#{amount}', currency: '#{currency}', per: '#{per}' }

Date:
  $flags: [ CASE_INSENSITIVE ]
  $local:
    Year: '\d{4}'
    Digit: '[1-9]'
    Day:
      Two: '0[1-9]|[12]\d|3[01]'
      One: { $fields: { digit: Digit }, $patterns: '#{digit}', $value: '0#{digit}' }
    Month:
      Numeric: '0[1-9]|1[0-2]'
      Name:
        Jan: { $patterns: [ 'January', 'Jan\.?' ], $value: '01' }
        Feb: { $patterns: [ 'February', 'Feb\.?' ], $value: '02' }
        Mar: { $patterns: [ 'March', 'Mar\.?' ], $value: '03' }
        Apr: { $patterns: [ 'April', 'Apr\.?' ], $value: '04' }
        May: { $patterns: [ 'May' ], $value: '05' }
        Jun: { $patterns: [ 'June', 'Jun\.?' ], $value: '06' }
        Jul: { $patterns: [ 'July', 'Jul\.?' ], $value: '07' }
        Aug: { $patterns: [ 'August', 'Aug\.?' ], $value: '08' }
        Sep: { $patterns: [ 'September', 'Sept?\.?' ], $value: '09' }
        Oct: { $patterns: [ 'October', 'Oct\.?' ], $value: '10' }
        Nov: { $patterns: [ 'November', 'Nov\.?' ], $value: '11' }
        Dec: { $patterns: [ 'December', 'Dec\.?' ], $value: '12' }
  $fields: { year: Year, month: Month, day: Day }
  $value: '#{year}-#{month}-#{day}'

  # 2024-12-19
  Iso:
    $fields: { month: Month::Numeric }
    $patterns: '#{year}-#{month}-#{day}'

  # 19.12.2024
  Dotted:
    $fields: { month: Month::Numeric }
    $patterns: '#{day}\.#{month}\.#{year}'

  # 19 December 2024
  DayMonth:
    $fields: { month: Month::Name }
    $patterns: '#{day} #{month},? #{year}'

  # December 19, 2024
  MonthDay:
    $fields: { month: Month::Name }
    $patterns: '#{month} #{day}(st|nd|rd|th)?,? #{year}'

The same change, in review

A second supplier sends invoices whose charge tables separate cells with tabs and name their columns Item, Unit price, Seats, Discount, Line total, in that order. Seats is a header neither parser knows, and Discount is a column neither needs. This is what each pull request looks like.

parse_invoices.py+14−3
COLUMNS = {    "description": r"Description|Item|Service|Product|Particulars|Details|Activity|School",    "quantity": r"Qty\.?|Quantity|Hours|Days|Weeks|Months|Units",    "quantity": r"Qty\.?|Quantity|Hours|Days|Weeks|Months|Units|Seats",⋯    return cells if len(cells) >= 2 else None  def read_tabbed_row(line, names):    # Cells go in the order of the headers; empty text between two tabs is an empty cell.    cells = line.split("\t")    if len(cells) != len(names):        return None    found = {name: cell.strip() for name, cell in zip(names, cells) if name and cell.strip()}    return found if len(found) >= 2 else None  def line_item(section, cells):⋯        line = lines[i]        heads = pieces(line)        tabbed = "\t" in line        heads = [(0, cell) for cell in line.split("\t")] if tabbed else pieces(line)        names = [column_of(cell) for _, cell in heads]⋯            i += 1            while i < len(lines) and (cells := read_row(lines[i], columns)):            read = (lambda row: read_tabbed_row(row, names)) if tabbed else (lambda row: read_row(row, columns))            while i < len(lines) and (cells := read(lines[i])):                facts.append({"type": "line_item", "value": line_item(section, cells)})

The script finds cells by their position under the header, and tabs break that. It needs a second way to read a row, by header order, and a branch that picks one. Before the change it still ran without an error on the new invoice: it returned two of the three rows, both without a description, and gave the first one its discount as the amount. No test is added unless someone writes one.

invoices.yml+2−1
LineItem:  $local:⋯    QuantityHeader: [ 'Qty\.?', 'Quantity', 'Hours', 'Days', 'Weeks', 'Months', 'Units' ]    QuantityHeader: [ 'Qty\.?', 'Quantity', 'Hours', 'Days', 'Weeks', 'Months', 'Units', 'Seats' ]    RateHeader: [ 'Rate', '(Hourly|Daily|Weekly|Monthly) rate', 'Unit price', 'Price', 'Unit cost' ]⋯  $tables:    $caption: section    $separator: '\t| {2,}'    $columns:
tests/samples.test.yml+54
tabbed_table:  input: |    INVOICE    Supplier: Kestrel Office Systems Ltd    Address: 12 Harbour Road, Portwell, PW3 8QT    Invoice: KOS-2025-0311    Issued: 2025-03-11    Services covered: 2025-03-01 through 2025-03-31    Due date: 2025-04-10    Amount payable: GBP 1,020.00     Software    Item	Unit price	Seats	Discount	Line total    Accounting suite	GBP 30.00	20	GBP 60.00	GBP 540.00    Payroll add-on	GBP 12.00	20		GBP 240.00     Support    Item	Unit price	Seats	Discount	Line total    Priority support	GBP 240.00	1		GBP 240.00     Order reference: PO-88412  output:    - !Invoice::Supplier 'Kestrel Office Systems Ltd'    - !Invoice::Address '12 Harbour Road, Portwell, PW3 8QT'    - !Invoice::Id 'KOS-2025-0311'    - !Invoice::Dates::Issue '2025-03-11'    - !Invoice::ServicePeriod { start: '2025-03-01', end: '2025-03-31' }    - !Invoice::Dates::Due '2025-04-10'    - !Invoice::Amounts::Payable { amount: '1020.00', currency: 'GBP' }    - !LineItem      section: 'Software'      description: 'Accounting suite'      quantity: '20'      rate: '30.00'      per: null      amount: '540.00'      currency: 'GBP'    - !LineItem      section: 'Software'      description: 'Payroll add-on'      quantity: '20'      rate: '12.00'      per: null      amount: '240.00'      currency: 'GBP'    - !LineItem      section: 'Support'      description: 'Priority support'      quantity: '1'      rate: '240.00'      per: null      amount: '240.00'      currency: 'GBP'    - !Invoice::Reference::Order 'PO-88412'

Two lines. Seats joins QuantityHeader, the headers of quantity, and $separator accepts a tab as well as two or more spaces. The column order and the Discount column need nothing: the header names the columns, and a column the spec does not declare fills no field. The new case pins all 11 facts, and texomy test keeps the six existing cases green.

Both are quick to write. Only one is quick to review.

Your agent writes either in minutes. The cost comes later: every new supplier layout is a change someone has to read. In a script, the meaning hides in regex strings and the code that walks lines and columns. In a spec, the change says it directly: a column, the headers it answers to and the separator, next to a test with the exact expected output.

The header names the columns

$columns gives each field of LineItem the headers it answers to. Columns may stand in any order, a cell may be empty, and a column the spec does not declare is ignored. A new layout usually means a new header name or a new separator, not new code.

Each row knows its section

$caption: section fills section from the line above the header, so the rows under Tutoring and under Administration say which table they come from, in every row of the output.

Values in one form

The invoice says USD 1,200.00 and 2024-12-20; another says 5 November 2024 or 01.10.2024. $value templates build 1200.00 with its currency, and ISO dates from all four date forms, so the output does not depend on how the supplier wrote them.

Tests pin the exact output

Each case in tests/*.test.yml gives an input and every fact expected from it, with its type and value. texomy test checks them all after each change, so a new layout cannot quietly change what the old ones return.

A spec is data, not code

A script from your agent runs with your permissions: it can read and delete files, call the network and install packages. Someone has to check it does none of that before it runs on real data, and again after every change. A spec cannot do any of it. The worst a bad pattern can do is run slowly, and --timeout stops it. Over MCP, the agent reads and writes only in your project folders.

Choose your runtime

This script uses the Python standard library and needs a compatible Python interpreter. Other scripts may add dependencies. Texomy is a native binary for macOS, Linux and Windows; specs and their package dependencies travel with your project.

One output shape for every format

A script returns whatever its author chose that day. Texomy returns the same shape for every spec: nodes with a type, character offsets, named fields and typed values. Code downstream reads the result of every format the same way.

Formats add up

One script is easy. Ten scripts from ten prompts each have their own structure, naming and helpers. Texomy specs share one language and can import common types such as dates and money from packages, so the tenth format reads like the first.

Extend instead of rewriting

In the spec, Dates::Issue and Dates::Due inherit the field and pattern of Dates and declare only their labels; amounts and references work the same way. A new currency added as Currency::Jpy is accepted by every pattern that references Currency, in this spec and in every spec that imports it. How types and inheritance work.

When a script is the better choice

  • Parsing needs real logic: lookups, state across many records or calls to other systems.
  • A one-off migration you will run once and delete.
  • Your team already maintains a parsing library and wants to extend it.

Questions

Is the Texomy spec longer than the script?

Sometimes. In the invoice example the spec also reads subtotals, tax, payment terms, more labels and four date forms, and it types every value it reads. What matters in review is how quickly someone can see what changed.

Can my agent write and test a spec as easily as a script?

Yes. The Texomy MCP server gives agents tools to check a spec, parse a sample and run tests, so the agent iterates until the tests pass.

Can I use Texomy from Python?

Run the texomy CLI as a step. It reads a file or standard input and writes JSON lines that any language can read.

More comparisons: Texomy vs regular expressions · Texomy vs LLM extraction · Texomy vs Grok patterns

Write the spec once. Run it on everything.

Install the CLI, connect your agent, and turn your first sample into typed data in minutes.

brew install texomy/tap/texomy