Metadata-Version: 2.5
Name: prose-audit
Version: 0.1.0
Summary: Find LLM writing tics and numeric over-density in reports (Markdown, LaTeX, text); export findings as JSON/YAML for an LLM to correct.
Author: Yassine Abdelouadoud
License-Expression: MIT
License-File: LICENSE
Keywords: latex,linter,llm,markdown,prose,style,writing
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: English
Classifier: Natural Language :: French
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Topic :: Text Processing :: Markup :: LaTeX
Classifier: Topic :: Text Processing :: Markup :: Markdown
Requires-Python: >=3.11
Requires-Dist: pyyaml>=6
Description-Content-Type: text/markdown

# prose-audit

Finds LLM writing tics and numeric over-density in reports (Markdown, LaTeX, plain text) and
exports the findings as JSON or YAML that an LLM can use to correct the text.

| command | what it does |
|---|---|
| `tics` | regex catalogues of LLM tics (French and English), by category, each rule with a severity and a rewrite instruction |
| `density` | numbers per 100 words, long sentences and em dashes, section by section |
| `tokens` | dump of every number in the prose, to diff before and after an edit |
| `overlap` | sentences one document copies verbatim from another |
| `check` | `tics` + `density` (the default) |

## Install

```bash
uv tool install prose-audit      # puts `prose-audit` on PATH
pip install prose-audit          # or, in an environment
uvx prose-audit check report.md  # or, without installing
```

Python ≥ 3.11 (uses `tomllib`); one dependency, PyYAML.

## Usage

```bash
prose-audit report.md                         # = check: tics + density, human report
prose-audit check paper.tex -f json > audit.json
prose-audit check report.md -o audit.yaml     # format inferred from extension
prose-audit tics post.md --sections POST "PREMIER COMMENTAIRE"   # only those headings
prose-audit tics paper.tex --skip-category social,formatting     # leave whole families out
prose-audit tics draft.md --category chat                        # one family only
prose-audit density paper.tex --show 10       # print the 10 longest sentences
prose-audit tokens paper.tex                  # block<TAB>number lines, for diff
prose-audit overlap p1.tex p2.tex             # sentences p2 copies verbatim from p1
prose-audit catalogue --self-test             # examples trigger, counter-examples don't
prose-audit catalogue --list -c en            # rules, with category and severity
prose-audit catalogue --categories            # the categories and their rule counts
```

Output: the human-readable report goes to stdout with `-f text` (the default). With
`-f json`/`-f yaml`, only the data goes to stdout or `-o FILE`, and the human report is logged
to stderr. `-q` silences it and `-v` adds debug lines. Colour only on a TTY, and never with
`NO_COLOR`. `catalogue` prints its listing to stdout.

Exit status: `0` clean, `1` findings at or above `--fail-on` (`blocking` by default; `review`,
`never`), `2` usage, file, config or catalogue error. `density`, `tokens` and `overlap` always
exit 0.

### Applying checks selectively

Every rule belongs to one category, the same names in every built-in catalogue:

| category | what it catches | typically skipped for |
|---|---|---|
| `rhetoric` | staged constructions: corrective antithesis, question-then-answer, reveals, signposting | |
| `vocabulary` | overused or hollow words, intensifiers, stock collocations | |
| `typography` | dashes, emoji, ellipses, exclamation marks | house styles that use em dashes |
| `formatting` | Markdown habits: bold emphasis, inline-header lists | manuals and READMEs |
| `structure` | triads, concession templates, paragraph closers, and the review checklist | |
| `chat` | assistant residue: greetings, sign-offs, disclaimers, placeholders, leaked markers | |
| `social` | engagement bait and marketing hooks | papers and reports |
| `sourcing` | vague attribution ("studies show") | |

* `--category NAME`: apply only these categories. Repeat it or separate names with commas.
* `--skip-category NAME`: leave these out.
* `--disable RULE_ID`: drop single rules, e.g. `--disable gras-markdown`. `paragraph-closer`
  is a rule id like any other.

An unknown category is an error (exit 2) and an unknown rule id a warning: a typo must not turn
into an audit that checks nothing and passes. The report records what was left out under
`selection`, and counts findings per category under `summary.by_category`.

### Options worth knowing

* `-c/--catalogue NAME|PATH`: `fr`, `en`, or any TOML file. Repeat to stack; a later rule with
  the same `id` replaces the earlier one. Default: picked per file by detected language
  (`--lang auto|fr|en`).
* `--sections H1 H2 …`: Markdown only; audit just the text under those exact headings. If none
  exists, the whole file is audited and a warning is logged.
* `--min-words`, `--long-sentence` (45), `--density-threshold` (6.0 statistics/100 words;
  negative disables), `--closer-words`/`--closer-min` (paragraph-closer heuristic; 0 disables).

### Config file

`prose-audit.toml`, `.prose-audit.toml`, or `[tool.prose-audit]` in `pyproject.toml`, found in the
current directory, or `--config FILE`. Keys are the long option names. Command-line flags win,
except `disable` and `skip-category`, which add to the file's. A misspelled key is reported with
a suggestion; a value of the wrong type is an error.

```toml
catalogue = ["en", "house-rules.toml"]
skip-category = ["social"]
disable = ["bold-emphasis"]
long-sentence = 40
density-threshold = 5.0
fail-on = "blocking"
```

## Correcting with an LLM

```bash
prose-audit tokens report.md > before.tsv
prose-audit check report.md -f json -q > audit.json
# give the LLM report.md + audit.json; ask it to follow audit.json "guidance" and fix findings
prose-audit tokens report.md | diff before.tsv -    # no number changed by accident?
prose-audit check report.md                          # re-audit
```

The JSON is meant to work as a correction brief on its own:

```jsonc
{
  "tool": "prose-audit", "version": "0.1.0", "schema_version": 1, "generated_at": "…",
  "summary": {"files": 1, "blocking": 6, "review": 9, "dense_blocks": 0, "long_sentences": 2},
  "guidance": ["Fix every finding with severity 'blocking'…", "Do not swap a tic for a synonym…", …],
  "files": [{
    "path": "post.md", "kind": "markdown", "lang": "fr", "catalogues": ["fr"],
    "summary": {"blocking": 6, "review": 9, "by_category": {"rhetoric": 8, …},
                "by_rule": {"fleches-emojis": 4, …}},
    "findings": [{
      "rule": "revelation-cachee", "severity": "blocking", "category": "rhetoric",
      "line": 34, "column": 12, "end_line": 34, "end_column": 29,   // end exclusive
      "block": "POST",                       // section heading the finding sits under
      "match": "cache des écarts",           // exact source text at that position
      "sentence": "…la moyenne cache des écarts…",
      "rewrite": "Donner la dispersion : …",
      "occurrences": 1, "max": 0
    }],
    "density": {
      "thresholds": {"min_words": 40, "long_sentence": 45, "density": 6.0},
      "totals": {"words": …, "numbers": …, "statistics": …, "per_100_words": …, …},
      "blocks": [{"name": "results", "line": 120, "words": 812, "statistics": 61,
                  "per_100_words": 7.5, "em_dashes": 0, "longest_sentence_words": 58,
                  "longest_sentence_line": 131, "flags": ["dense: 7.5 statistics/100 words > 6.0", …]}],
      "long_sentences": [{"line": 131, "block": "results", "words": 58, "text": "…"}]
    }
  }],
  "selection": {"categories": [], "skip_categories": ["social"], "disabled": []},
  "rules": {"revelation-cachee": {"why": "…", "rewrite": "…", "severity": "…", …}},
  "structure_checklist": [{"id": "gabarit-repete", "category": "structure", "test": "…"}]
                                                                  // what no regex can see
}
```

Line and column always refer to the file as audited. Masking blanks non-prose text with spaces
instead of deleting it, so offsets never shift.

## What is scanned

| kind | tics see | density counts |
|---|---|---|
| Markdown (`.md`, `.qmd`, `.rmd`, stdin) | prose, headings, tables; not front matter, code, inline code, math, URLs, HTML comments/tags, images | prose incl. inline math; not tables, display math, list numbering |
| LaTeX (`.tex`) | prose and captions, between `\begin{document}` and `\end{document}`; not math, comments, macros, `\label/\ref/\cite…`, tabular/equation/align/tikz/bibliography… | prose incl. inline math; not floats (figure/table incl. captions), display math |
| text | everything except URLs | everything except list numbering |

Hard-wrapped lines are joined before matching, so a rule anchored at the start of a sentence
does not fire in the middle of one.

Sections are Markdown headings or LaTeX `\section`-level commands. A `# comment` inside a code
block or a YAML front matter is not a heading. A finding in a heading is reported under the
section that heading opens. Density and sentence length are measured on section bodies: a
heading is not a sentence.

What counts as a number:

* `5{,}464`, `1\,176\,149` and `3 965` (no-break or thin space) are one number each;
* subscripts and identifiers are not numbers (`g_0`, `R^2`, `CO2`, `P1`);
* calendar years (19xx, 20xx) are numbers but not statistics, so they do not weigh on density;
* the `1.`, `2.` of an ordered list are not numbers; a year that starts a wrapped line still is;
* `$5 and $10` are two prices, not a formula (Pandoc's rule for Markdown, `\$` in LaTeX);
* totals include sections shorter than `--min-words`; that option only hides rows from the table.

## Catalogues

Two catalogues are built in (`src/prose_audit/catalogues/`): `en` with 72 rules and 24 checklist
items, `fr` with 64 and 26. Every rule has examples that must trigger it and counter-examples
that must not; `catalogue --self-test` checks both. A catalogue can be written with English keys
or French ones (`motifs`, `gravite`, `categorie`, `pourquoi`, `reecrire`, `exemples`,
`contre_exemples`, `vue`).

Many rules carry a `sources` list: the pages where the tell is documented, mainly Wikipedia's
"Signs of AI writing", corpus studies of excess vocabulary since 2023 (Kobak et al., Liang et
al., Juzek & Ward, Reinhart et al.) and Graphite's "AI Tells". New rules were kept only when
they stayed under 3 matches per 100,000 words on human prose written before 2022 (man pages,
licences, arXiv and HAL abstracts); rules whose frequency is the tell are `review` with a `max`.

```toml
[[tic]]
id = "meta-commentary"
category = "rhetoric"          # one of the categories above, or a label of your own
severity = "blocking"          # or "review" (bloquant / a-justifier)
max = 0                        # occurrences tolerated before reporting
scope = "file"                 # or "block": max counts per section (long reports)
view = "prose"                 # or "source": see below
patterns = ['''\bit is (?:important|worth) to note\b''']
why = "Comments on the importance of what follows instead of saying it."
rewrite = "Delete the formula. If the information matters, it stands on its own."
examples = ["It is important to note that the time step is hourly."]
counter_examples = ["The note in Table 2 gives the source."]
sources = ["https://…"]        # optional: where the tell is documented

[[structure]]
id = "restating-conclusion"
test = "Does the last paragraph rephrase what was already said?"
category = "structure"         # the default for checklist items
```

A rule scans the prose view by default: what a reader sees, with URLs, code, math and markup
blanked. With `view = "source"` it scans the text as written instead, markup included (URLs,
heading markers, HTML tags, LaTeX commands; code blocks, comments and front matter stay out).
That is how `chatbot-tracking-url` sees `?utm_source=chatgpt.com` in a link, and how
`title-case-heading` or `inline-header-list` see a heading or a `\item \textbf{…}`.

When a reviewer corrects a pattern that keeps coming back, add it with an example, then
run `prose-audit catalogue --self-test`.

## Caveats

Sentence splitting is regex-based: semicolon lists, itemize runs and equations can read as one
long sentence, and abbreviations can split one. Thresholds are judgement calls, so compare
blocks within one document, or one document before and after an edit. `tokens` compares
numbers per block as a multiset: two numbers swapping places in one block are invisible, and
a renamed block reads as a wholesale change. `overlap` sees copying, not duplication.

## Development

```bash
uv sync
uv run pytest
uv run prose-audit catalogue --self-test
```

`tests/corpus/` holds excerpts of real reports, papers and notes in both languages and both
formats. `tests/test_corpus.py` checks invariants on each (offsets, exact match positions, token
counts) and compares the audit with a snapshot, `tests/corpus/expected.json`. A change in masking
or in a catalogue shows up as a diff there; read it, then accept it:

```bash
PROSE_AUDIT_UPDATE_SNAPSHOTS=1 uv run pytest tests/test_corpus.py
```
