Files
stack/src/pfs/origin.py

949 lines
36 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Origin and formation of a code family (``pfs.code_origin``): the statute,
regulation, program, demonstration, CPT Editorial Panel action, CMS G-code
creation or coverage rule behind each code.
Three sources, every row citing the exact place that supports it:
* Federal Register paragraphs (``fr_para``: item + paragraph), read by the
local model through a resumable ledger. A model item survives only when
its ``reference`` is written in a plain sentence of the paragraph (no
recap of another year's rule, hypothetical or commenter's request), the
codes it names are family codes the paragraph names, and no number in
its summary is absent from the paragraph.
* The licensed AMA book *CPT Changes* (``cpt_book``: item + printed page).
Book text goes only to the local model; a summary is kept only as a
paraphrase (no 8-word run shared with the page), is at most 240
characters, and the ledger stores only the guarded paraphrases.
* ``pfs.code_guidance`` rows (deterministic): CFR cites become
``regulation`` rows, IOM and MLN cites ``coverage`` rows.
"""
from __future__ import annotations
import re
from collections.abc import Collection, Iterator, Sequence
from pathlib import Path
from typing import Any
from pfs.codetables import ORIGIN_KINDS, OriginRow, read_guidance
from pfs.descriptors import rule_year_of
from pfs.families import code_pattern
from pfs.lineage import _expand_ranges
from pfs.rounds import (
_HYPOTHETICAL,
_PRINTED_PAGE,
_anchor_rows,
_named,
_recap,
_sentences,
context_paragraphs,
rule_items,
)
from pfs.runlog import RunLog, input_hash, ledger_path, run_units
ORIGIN_PROMPT_VERSION = "origin-v1"
DEFAULT_BOOK = "3ANRT854" # "CPT Changes 2023"
ORIGIN_SCHEMA: dict = {
"type": "object",
"required": ["origins"],
"properties": {
"origins": {
"type": "array",
"items": {
"type": "object",
"required": ["kind", "reference", "year", "codes", "summary"],
"properties": {
"kind": {"type": "string", "enum": list(ORIGIN_KINDS)},
"reference": {"type": "string", "maxLength": 120},
"year": {"type": ["integer", "null"]},
"codes": {"type": "array", "items": {"type": "string"}},
"summary": {"type": "string", "maxLength": 240},
},
},
}
},
}
_COMMON = (
"You read one passage about CPT/HCPCS codes and list the ORIGINS the "
"passage states for the listed codes: the statute, regulation, program, "
"demonstration, CPT Editorial Panel action, CMS G-code creation or "
"coverage rule that created, defined or governs them. kind is one of "
"statute, regulation, program, demonstration, cpt_panel, cms_gcode, "
"coverage. List one origin per distinct statute, program, demonstration "
"or panel action; leave out anything the passage only proposes, "
"imagines, recaps from another year, or attributes to a commenter. "
"codes = EVERY listed code that origin applies to that the passage "
"names (all of them, ranges included); year = the year the passage gives for it, else null; summary = "
"one plain sentence (under 240 characters) in YOUR OWN WORDS of what "
"that origin did for the codes; never add a fact, name or number the "
"passage does not state. These are NOT origins: quality-measure or "
"MIPS denominator lists, additions to the Medicare telehealth list, "
"payment rates, valuations, utilization, a pointer to another section "
"of the same rule, and anything CMS only proposes. If the passage "
"states no origin, return an empty list. "
)
ORIGIN_SYSTEM = {
"fr": _COMMON
+ (
"reference = the statute, rule, program or action written EXACTLY as "
'the passage writes it (for example "section 1861(m) of the Act"), '
"so it can be found in the text word for word. CONTEXT paragraphs "
"(the paragraphs just before the PASSAGE) may state the statute or "
"program; the codes must be named in the PASSAGE itself, and the summary "
"must describe only what the PASSAGE itself says about the listed codes "
"or what the cited provision requires according to the PASSAGE (a "
"CONTEXT paragraph only supplies the reference; never take the "
"summary from it). Paraphrase the summary; never quote."
),
"book": _COMMON
+ (
"The passage is a page of licensed text. A code listed with its "
"descriptor and symbols is NOT an origin; use only prose that says "
"a code was created, revised, deleted, merged or moved (usually in "
"a Rationale paragraph), and say which of those it was. reference = "
'a short label you write (for example "CPT Editorial Panel '
'action"), not a quotation. Paraphrase: never copy eight or more '
"consecutive words of the passage into the reference or the summary."
),
}
#: a commenter's request, not CMS stating something
_REQUEST = re.compile(
r"\b(?:commenters?|requesters?)\b[^.;]{0,60}\b"
r"(?:recommend|request|suggest|urg|ask|support|oppos)\w*",
re.I,
)
#: the FR paragraphs that can state an origin
_ORIGIN_WORDS = re.compile(
r"section 1\d{3}|of the Act\b|statut|demonstration|Independence at Home|"
r"CPT Editorial Panel|establish|creat|benefit|homebound|coverage",
re.I,
)
_PROPOSAL = re.compile(r"\bpropos\w*", re.I)
#: a summary of a review under way, not of an origin
_PROCESS = re.compile(r"\b(?:review|consider|evaluat|examin|discuss)\w*", re.I)
#: "we are proposing to create ...": a sentence proposing now (one that also
#: finalizes is a statement)
_PROPOSING = re.compile(r"\b(?:we|CMS)\s+(?:are\s+)?propos(?:e|ing)\b", re.I)
_FINALIZING = re.compile(r"\bfinaliz", re.I)
#: what a reference must look like for its kind: a statute is a section of
#: the Act (or the U.S. Code), a regulation a CFR cite or a decimal section
#: ("§ 425.20"), a G-code creation names a HCPCS code; a pointer into the
#: same rule is no origin
_USC = re.compile(r"U\.S\.C", re.I)
_ACT = re.compile(
r"\bof the (?:Social Security )?Act\b|\bsections? 1\d{3}[A-Z]{0,2}\b", re.I
)
_CFR = re.compile(r"\bCFR\b|§\s*\d+\.\d+")
_GCODE = re.compile(r"\b[A-Z]\d{4}\b|\bG[A-Z]{3,4}\d\b|\bHCPCS\b")
_POINTER = re.compile(
r"\bof this (?:proposed |final |interim final )?rule\b|^section [IVX]+\.", re.I
)
#: bodies a trimmed reference may be cut down to when the model's longer
#: wording is not verbatim
_CANON = (
re.compile(r"CPT Editorial Panel", re.I),
re.compile(
r"\bsections? 1\d{3}[A-Z]{0,2}(?:\([A-Za-z0-9]+\))*"
r"(?: of the (?:Social Security )?Act)?",
re.I,
),
re.compile(r"\b\d+ CFR (?:part |§§? ?)?\d+(?:\.\d+)?(?:\([A-Za-z0-9]+\))*", re.I),
re.compile(r"§\s*\d+\.\d+(?:\([A-Za-z0-9]+\))*"),
)
#: only a paragraph that introduces what follows ("... the following codes:")
#: lends its reference to the next paragraphs
_INTRODUCES = re.compile(r"\bfollowing\b|:\s*$", re.I)
_AMA = re.compile(r"^(?:the\s+)?AMA\s+", re.I)
_PRINTED = re.compile(r"\(\s*printed page (\d+)\s*\)", re.I)
_ANY_CODE = re.compile(r"\b(?:\d{5}|[A-Z]\d{4})\b")
_NUM = re.compile(r"\d+")
_WORD = re.compile(r"[a-z0-9]+")
def _words(text: str) -> list[str]:
return _WORD.findall(text.lower())
def shares_run(summary: str, text: str, n: int = 8) -> bool:
"""True when *summary* and *text* share a run of *n* consecutive words
(case- and punctuation-insensitive): the copy guard for licensed text."""
a = _words(summary)
b = _words(text)
grams = {tuple(b[i : i + n]) for i in range(len(b) - n + 1)}
return any(tuple(a[i : i + n]) in grams for i in range(len(a) - n + 1))
def _collapse(text: str) -> str:
return " ".join(_PRINTED_PAGE.sub(" ", text).split()).casefold()
def _names(text: str, code: str) -> bool:
return bool(re.search(rf"\b{re.escape(code)}\b", _expand_ranges(text)))
def _named_codes(text: str, codes: Sequence[str]) -> list[str]:
return [c for c in codes if _names(text, c)]
def _listed(it: dict) -> list[str]:
"""The codes a model item lists, a range entry ("99324-99328") expanded."""
text = _expand_ranges(" ".join(str(c).upper() for c in it["codes"]))
return list(dict.fromkeys(_ANY_CODE.findall(text)))
def _said_codes(text: str) -> set[str]:
"""Every code *text* names, ranges (dash, "through", "to") expanded."""
return set(_ANY_CODE.findall(_expand_ranges(text)))
def origin_user(
text: str,
codes: Sequence[str],
*,
label: str,
context: Sequence[tuple[int, int, str]] = (),
) -> str:
before = "".join(f"[¶{p}] {t}\n\n" for p, _page, t in context)
ctx = f"CONTEXT (paragraphs just before the PASSAGE):\n{before}" if before else ""
return f"CODES: {', '.join(codes)}\nSOURCE: {label}\n\n{ctx}PASSAGE:\n{text}"
def _copy_free(it: dict, text: str) -> bool:
return not (shares_run(it["summary"], text) or shares_run(it["reference"], text))
def _plain(sentence: str, rule_year: int | None) -> bool:
"""A sentence that states something: no recap of another year's rule,
hypothetical or commenter's request."""
return not (
_recap(sentence, rule_year)
or _HYPOTHETICAL.search(sentence)
or _REQUEST.search(sentence)
or (_PROPOSING.search(sentence) and not _FINALIZING.search(sentence))
)
def _window(ref: str, text: str, rule_year: int | None) -> str | None:
"""The sentences of *text* that write *ref* in a plain sentence, each
with its neighbours (where the codes it applies to are named); ``None``
when no plain sentence writes it."""
want = _collapse(ref)
sents = _sentences(text)
hit = [
i for i, s in enumerate(sents) if want in _collapse(s) and _plain(s, rule_year)
]
if not hit:
return None
near = sorted({j for i in hit for j in (i - 1, i, i + 1) if 0 <= j < len(sents)})
return " ".join(sents[j] for j in near)
def _cut_back(cite: str) -> Iterator[str]:
"""*cite*, then without a trailing "of the Act", then one deepest
sub-paragraph at a time, always keeping the first one: "425.400(c)(1)"
may be cut to "425.400(c)" but never to a bare section."""
yield cite
core = re.sub(r" of the (?:Social Security )?Act$", "", cite, flags=re.I)
if core != cite:
yield core
while re.search(r"\([A-Za-z0-9]+\)\([A-Za-z0-9]+\)$", core):
core = re.sub(r"\([A-Za-z0-9]+\)$", "", core)
yield core
def _anchor(ref: str, text: str) -> tuple[str, str] | None:
"""``(reference to store, span to find in text)`` for *ref* against
*text*: *ref* itself when it is written there word for word; else, when
a canonical body inside it ("CPT Editorial Panel", "section 1861(m) of
the Act", a CFR cite) is, the longest verbatim span of the
model's wording that contains it is stored; else ``None``."""
want = _collapse(text)
if _collapse(ref) in want:
return ref, ref
for pat in _CANON:
m = pat.search(ref)
if m is None:
continue
body = next((c for c in _cut_back(m.group(0)) if _collapse(c) in want), None)
if body is not None:
return _longest_span(ref, body, want), body
return None
def _longest_span(ref: str, body: str, want: str) -> str:
"""The longest run of *ref*'s words that contains *body* and is written
in the text (*want*, collapsed): every word of what is stored occurs in
the paragraph, in that order."""
toks, core = ref.split(), body.split()
n = len(core)
at = next((i for i in range(len(toks) - n + 1) if toks[i : i + n] == core), None)
if at is None:
return body
for size in range(len(toks), n - 1, -1):
for lo in range(max(0, at + n - size), min(at, len(toks) - size) + 1):
span = " ".join(toks[lo : lo + size])
if _collapse(span) in want:
return span
return body
def _locate(
ref: str,
text: str,
context: Sequence[tuple[int, int, str]],
rule_year: int | None,
) -> tuple[str, int, str, str] | None:
"""``(reference, ref_p_id, near text, anchor)`` for the nearest place
that writes *ref* in a plain sentence: the paragraph itself
(``ref_p_id`` 0; the codes must sit near the sentence) or, failing
that, the closest earlier context paragraph (the codes then need only
be named in the paragraph)."""
sources = [(0, text)] + [
(p, t) for p, _page, t in reversed(context) if _INTRODUCES.search(t)
]
for p_id, src in sources:
fit = _anchor(ref, src)
if fit is None:
continue
near = _window(fit[1], src, rule_year)
if near is not None:
return _AMA.sub("", fit[0]), p_id, (near if p_id == 0 else text), fit[1]
return None
def _kind_of(it: dict) -> str | None:
"""The item's kind. A statute/regulation claim is settled by what its
reference is (U.S. Code or a section of the Act: statute; CFR cite or
decimal section: regulation) and dropped when the reference is neither;
a G-code creation must name a HCPCS code. Other kinds (a program that
cites the Act is still a program) stand."""
ref, kind = it["reference"], it["kind"]
if kind in ("statute", "regulation"):
if _USC.search(ref):
return "statute"
if _CFR.search(ref):
return "regulation"
return "statute" if _ACT.search(ref) else None
if kind == "cms_gcode" and not _GCODE.search(ref):
return None
return kind
# ── the licensed book: prose, not listings ───────────────────────────
_HEADING = re.compile(r"^Rationale\s*$", re.M)
_NOTE = re.compile(r"▶\((.*?)\)◀", re.S)
#: a sentence that only conforms another section to a change made elsewhere
_CONFORMING = re.compile(
r"in accordance with the (?:deletion|revision|addition|creation) of|"
r"in accommodation of|to reflect (?:these|the) (?:changes|deletion)|"
r"refer to the codebook",
re.I,
)
_FLAG = re.compile(r"\((?:deleted|revised|new|resequenced)\)")
_VERBS = {
"deleted": re.compile(r"\b(?:deleted|deletion)\b", re.I),
"revised": re.compile(r"\b(?:revised|merged|combined|replaced|renamed)\b", re.I),
"created": re.compile(r"\b(?:created|added|introduced|established)\b", re.I),
}
_LIST = (
r"\d{5}(?:\s*(?:[-–]|through|to)\s*\d{5})?"
r"(?:\s*(?:,|and)\s*(?:and\s+)?\d{5}(?:\s*(?:[-–]|through|to)\s*\d{5})?)*"
)
_DEL_BEFORE = re.compile(rf"({_LIST})\s+(?:has|have) been deleted", re.I)
_DEL_AFTER = re.compile(rf"deletions? of (?:CPT )?codes? ({_LIST})", re.I)
_DEL_FLAG = re.compile(r"\b(\d{5}) \(deleted\)")
def book_deleted(pages: Sequence[tuple[str, str]]) -> frozenset[str]:
"""Every code the book itself marks deleted: "(99343) has been
deleted", "the deletion of codes ...", or a "(deleted)" index flag."""
out: set[str] = set()
for _label, text in pages:
for pat in (_DEL_BEFORE, _DEL_AFTER):
for m in pat.finditer(text):
out |= set(re.findall(r"\d{5}", _expand_ranges(m.group(1))))
out |= set(_DEL_FLAG.findall(text))
return frozenset(out)
def action_of(summary: str) -> str | None:
"""deleted / revised / created: what a paraphrase says happened (the
first of that order that its wording carries)."""
return next((a for a, pat in _VERBS.items() if pat.search(summary)), None)
def book_support(text: str, code: str, deleted: Collection[str]) -> dict[str, str]:
"""``{action: level}`` of what a page says happened to *code*: level
``own`` = a Rationale sentence about the code itself (never one that
only conforms another section), ``note`` = a "have been deleted"
parenthetical of the page's own section. An index page, or one with
neither, supports nothing; "deleted" needs the book to mark the code
deleted, and a deleted code is never "revised"."""
if len(_FLAG.findall(text)) >= 5:
return {}
acts: dict[str, str] = {}
parts = _HEADING.split(text, maxsplit=1)
head, body = (parts[0], parts[1]) if len(parts) == 2 else (text, "")
for sent in _sentences(body):
if _CONFORMING.search(sent) or not _names(sent, code):
continue
for act, pat in _VERBS.items():
if pat.search(sent):
acts.setdefault(act, "own")
for note in _NOTE.findall(head):
for sent in _sentences(note):
if _DEL_BEFORE.search(sent) and _names(sent, code):
acts.setdefault("deleted", "note")
if code not in deleted:
acts.pop("deleted", None)
else:
acts.pop("revised", None)
return acts
# ── guarded items from one reply ─────────────────────────────────────
def _fr_items(
out: dict,
text: str,
codes: Collection[str] | None,
rule_year: int | None,
context: Sequence[tuple[int, int, str]],
) -> list[dict]:
own = set(_NUM.findall(text))
wider = own.union(*(set(_NUM.findall(t)) for _p, _page, t in context))
kept: list[dict] = []
for it in out.get("origins") or []:
found = _locate(it["reference"], text, context, rule_year)
if (
found is None
or _PROPOSAL.search(it["summary"])
or _PROCESS.search(it["summary"])
):
continue
ref, ref_p_id, near, anchor = found
it = {**it, "reference": ref}
kind = _kind_of(it)
if kind is None or _POINTER.search(ref) or "410.78" in ref:
continue
# a reference in the passage itself: the passage alone backs the
# summary and its numbers; one lent by a context paragraph also
# draws on the context
have = own if ref_p_id == 0 else wider
if set(_NUM.findall(it["summary"])) - have:
continue
said = _said_codes(it["summary"])
mine = [
c
for c in _listed(it)
if (codes is None or c in codes)
and _names(near, c)
and (not said or c in said)
]
if not mine:
continue
year = (
it["year"] if it["year"] is not None and str(it["year"]) in have else None
)
kept.append(
{
**it,
"kind": kind,
"codes": mine,
"year": year,
"ref_p_id": ref_p_id,
"anchor": anchor,
}
)
return kept
def _book_items(
out: dict, text: str, codes: Collection[str] | None, deleted: Collection[str]
) -> list[dict]:
have = set(_NUM.findall(text))
kept: list[dict] = []
for it in out.get("origins") or []:
kind = _kind_of(it)
act = action_of(it["summary"])
if kind is None or act is None or not _copy_free(it, text):
continue
if set(_NUM.findall(it["summary"])) - have:
continue
said = _said_codes(it["summary"])
year = (
it["year"] if it["year"] is not None and str(it["year"]) in have else None
)
for c in _listed(it):
if (codes is not None and c not in codes) or (said and c not in said):
continue
level = book_support(text, c, deleted).get(act)
if level is not None:
kept.append(
{
**it,
"kind": kind,
"codes": [c],
"year": year,
"action": act,
"level": level,
}
)
return kept
def origins_from_output(
out: dict,
text: str,
*,
source: str,
codes: Collection[str] | None = None,
rule_year: int | None = None,
context: Sequence[tuple[int, int, str]] = (),
deleted: Collection[str] = (),
) -> list[dict]:
"""Guarded origin items from one model reply. Codes outside *codes* (or
the family) and codes the text does not name are dropped, an item left
with none is dropped; a summary that names codes applies only to those;
a summary number the text lacks drops the item; a year the text lacks
becomes ``None``.
FR source: the ``reference`` must be written in a plain sentence of
*text* (the codes near it) or of a *context* paragraph (``ref_p_id`` =
that paragraph; the codes need only be named in *text*); a long
wording is trimmed to the canonical body ("CPT Editorial Panel",
"section N of the Act", a CFR cite) that is verbatim. Summaries that
propose are dropped.
Book source (*text* is one printed page): an item needs a summary
action (deleted/revised/created) that the page's prose supports for
that code (``book_support``) and no 8-word run shared with the page."""
if source == "book":
return _book_items(out, text, codes, deleted)
return _fr_items(out, text, codes, rule_year, context)
def extract_origin(
text: str,
ask: Any,
*,
source: str,
codes: Collection[str] | None = None,
rule_year: int | None = None,
context: Sequence[tuple[int, int, str]] = (),
deleted: Collection[str] = (),
) -> list[dict]:
"""Ask the local model for the origins *text* states and apply the
guards of :func:`origins_from_output`. A failed reply gives ``[]``."""
if source not in ORIGIN_SYSTEM:
raise ValueError(f"unknown origin source {source!r}")
named = sorted(codes) if codes else []
user = origin_user(text, named, label=source, context=context)
out = ask(ORIGIN_SYSTEM[source], user, ORIGIN_SCHEMA)
if out is None:
return []
return origins_from_output(
out,
text,
source=source,
codes=codes,
rule_year=rule_year,
context=context,
deleted=deleted,
)
# ── candidates ───────────────────────────────────────────────────────
def fr_origin_candidates(
store: Any, codes: Sequence[str], phrases: Sequence[str]
) -> list[dict]:
"""``fr_anchors`` paragraphs of the (de-duplicated, non-correction)
rules that name a family code or phrase and talk about a statute,
program, creation or coverage; oldest rule first. Each carries
``rule_kind``, ``rule_year``, ``fr_volume`` (``""`` when unknown) and
``context`` = the three paragraphs before it, ``(p_id, page, text)``."""
if not codes and not phrases:
return []
pattern = code_pattern(codes) if codes else None
low = [x.lower() for x in phrases]
anchors = _anchor_rows(store, codes, phrases)
kinds = {it["item_key"]: it["kind"] for it in rule_items(store, anchors)}
volumes = dict(
store._con() # noqa: SLF001
.execute("SELECT item_key, fr_volume FROM fr_anchor_docs")
.fetchall()
)
out = []
for r in anchors:
text = r["text"] or ""
if r["item_key"] not in kinds:
continue
named = bool(pattern and _named(text, pattern)) or any(
x in text.lower() for x in low
)
if not named or not _ORIGIN_WORDS.search(text):
continue
out.append(
{
**r,
"rule_kind": kinds[r["item_key"]],
"rule_year": rule_year_of(r["title"], r["date_published"]),
"fr_volume": str(volumes.get(r["item_key"]) or ""),
"context": context_paragraphs(store, r["item_key"], r["p_id"], 3),
}
)
return out
def book_pages(path: Path) -> list[tuple[str, str]]:
# lazy: importing ``rex`` pulls the lake extras, which ``stack`` must
# start without
from rex.comments.epub_text import epub_pages # noqa: PLC0415
return epub_pages(path)
def book_candidates(path: Path, codes: Sequence[str]) -> list[tuple[str, str]]:
"""Printed pages of the EPUB naming a family code. Text before the
first page marker has no page to cite and is left out."""
if not codes:
return []
return [
(label, text)
for label, text in book_pages(path)
if label and _named_codes(text, codes)
]
def resolve_book(store: Any, item_key: str) -> tuple[str, Path] | None:
"""``(title, EPUB path)`` of a bib item with an ``.epub`` attachment."""
con = store._con() # noqa: SLF001
for title, fn, sp in con.execute(
"SELECT i.title, a.filename, a.storage_path FROM attachments a "
"JOIN items i ON i.id = a.item_id WHERE i.key = ? ORDER BY a.id",
(item_key,),
).fetchall():
if str(fn).lower().endswith(".epub") and sp and Path(sp).is_file():
return str(title), Path(sp)
return None
# ── guidance (deterministic) ─────────────────────────────────────────
_GUIDANCE_KIND = {"cfr": "regulation", "iom": "coverage", "mln": "coverage"}
#: the CFR section itself: "42 CFR 425.400(c)(1)(v)" -> "42 CFR 425.400"
_CFR_SECTION = re.compile(r"^(\d+ CFR [\d.]+)")
#: telehealth-listing rules say which services may be furnished by
#: telehealth; they create none of the family's codes
_NOT_ORIGINS = ("42 CFR 410.78",)
_REMOVAL = re.compile(r"\b(?:remov|eliminat|rescind)\w*", re.I)
def _removed(store: Any, item_key: str, p_id: int, locator: str) -> bool:
"""The sentence that cites the manual provision *locator* is about
removing it ("100-04 ch.12 §30.6.14.1" is cited as "Section 30.6.14.1",
"100-04 ch.26" as "Chapter 26")."""
row = (
store._con()
.execute( # noqa: SLF001
"SELECT text FROM fr_anchors WHERE item_key = ? AND p_id = ?",
(item_key, p_id),
)
.fetchone()
)
if not row:
return False
if "§" in locator:
key = re.compile(re.escape(locator.rsplit("§", 1)[1]))
else:
key = re.compile(
r"\bChapter\s+" + re.escape(locator.rsplit("ch.", 1)[-1]) + r"\b"
)
return any(
key.search(sent) and _REMOVAL.search(sent) for sent in _sentences(row[0] or "")
)
#: 42 CFR chapter IV (CMS) is parts 400-699; any other part is a typo in the
#: FR text (a "42 CFR 25.400" for 425.400)
_CMS_PARTS = range(400, 700)
def guidance_origins(con: Any, family: str, store: Any = None) -> list[OriginRow]:
"""One ``regulation`` (CFR section, sub-paragraph variants collapsed) or
``coverage`` (IOM, MLN) row per distinct ``(code, cite)`` in
``pfs.code_guidance``, citing the first paragraph that carries it. Not
origins: telehealth-listing CFR sections, and (with a *store* to read
the citing paragraph) manual provisions that paragraph is removing."""
rows: dict[tuple[str, str, str], OriginRow] = {}
for g in read_guidance(con, family):
locator = g.locator
if g.kind == "cfr":
m = _CFR_SECTION.match(locator)
locator = m.group(1) if m else locator
part = re.match(r"\d+ CFR (\d+)", locator)
if part and int(part.group(1)) not in _CMS_PARTS:
continue
key = (g.code, g.kind, locator)
if key in rows or locator in _NOT_ORIGINS:
continue
if (
store is not None
and g.kind == "iom"
and _removed(store, g.item_key_src, g.p_id_src, locator)
):
continue
rows[key] = OriginRow(
family=family,
code=g.code,
kind=_GUIDANCE_KIND[g.kind],
reference=locator,
year=None,
summary=f"CMS guidance for {g.code} points to {locator}.",
cite_kind=g.kind,
item_key=g.item_key_src,
p_id=g.p_id_src,
page_label=str(g.page_src) if g.page_src else "",
locator=locator,
extractor="guidance",
)
return list(rows.values())
# ── family run ───────────────────────────────────────────────────────
def _page_of(text: str, anchor: str, default: int) -> int:
"""The FR page the sentence writing *anchor* sits on: the last
"(printed page N)" marker before it, else the paragraph's own page."""
m = re.search(r"\s+".join(re.escape(w) for w in anchor.split()), text, re.I)
if m is None:
return default
marks = [int(x.group(1)) for x in _PRINTED.finditer(text[: m.start()])]
return marks[-1] if marks else default
def _fr_job(p: dict, family: Any) -> dict:
codes = _named_codes(_PRINTED_PAGE.sub(" ", p["text"]), family.codes)
label = f"Federal Register, CY{p['rule_year']} {p['rule_kind']} rule"
return {
"unit": f"fr:{p['item_key']}:{p['p_id']}",
"source": "fr",
"text": p["text"],
"context": p["context"],
"codes": codes,
"user": origin_user(p["text"], codes, label=label, context=p["context"]),
"year": p["rule_year"],
"cite_kind": "fr_para",
"item_key": p["item_key"],
"p_id": p["p_id"],
"page": p["page"],
"volume": p["fr_volume"],
"rule_kind": p["rule_kind"],
}
def _book_job(
item_key: str,
edition: str,
label: str,
text: str,
family: Any,
deleted: frozenset[str],
order: int,
) -> dict:
codes = _named_codes(text, family.codes)
return {
"unit": f"book:{item_key}:{label}",
"source": "book",
"text": text,
"context": (),
"codes": codes,
"user": origin_user(text, codes, label=f"{edition}, page {label}"),
"year": None,
"cite_kind": "cpt_book",
"item_key": item_key,
"p_id": 0,
"page_label": label,
"locator": f"{edition}, p. {label}",
"deleted": deleted,
"order": order,
}
def origin_inventory(
store: Any, family: Any, books: Sequence[tuple[str, str, Path]]
) -> tuple[list[dict], dict[str, list[str]]]:
"""What a run would work on without a model call: the candidate FR
paragraphs and, per book item, the labels of the pages naming a code."""
paras = [j for j in _jobs(store, family, ()) if j["source"] == "fr"]
pages = {
key: [label for label, _ in book_candidates(path, family.codes)]
for key, _edition, path in books
}
return paras, pages
def _jobs(
store: Any, family: Any, books: Sequence[tuple[str, str, Path]]
) -> list[dict]:
jobs = [
_fr_job(p, family)
for p in fr_origin_candidates(store, family.codes, family.synonyms)
]
for key, edition, path in books:
pages = book_pages(path)
deleted = book_deleted(pages)
jobs += [
_book_job(key, edition, label, text, family, deleted, i)
for i, (label, text) in enumerate(pages)
if label and _named_codes(text, family.codes)
]
return [j for j in jobs if j["codes"]]
def _ask_job(ask: Any, job: dict) -> dict | None:
"""One model call. A book reply is reduced to its paraphrases before
it reaches the ledger, so the ledger never holds copied book text."""
out = ask(ORIGIN_SYSTEM[job["source"]], job["user"], ORIGIN_SCHEMA)
if out is None or job["source"] != "book":
return out
return {
"origins": [
it for it in out.get("origins") or [] if _copy_free(it, job["text"])
]
}
def _locator(job: dict, it: dict) -> tuple[str, str]:
"""``(page label, locator)`` of an FR item: the volume and printed page
of the sentence that writes the reference."""
ref_p = it["ref_p_id"]
if ref_p:
page, text = next((pg, t) for p, pg, t in job["context"] if p == ref_p)
else:
page, text = job["page"], job["text"]
page = _page_of(text, it["anchor"], page)
cite = f"{job['volume']} FR {page}" if job["volume"] else f"FR p. {page}"
note = f" (reference ¶{ref_p})" if ref_p else ""
return str(page), f"{cite}, ¶{job['p_id']}{note}"
def _rows(
job: dict, out: dict, family: Any, model: str
) -> list[tuple[OriginRow, dict]]:
items = origins_from_output(
out,
job["text"],
source=job["source"],
codes=set(family.codes),
rule_year=job["year"],
context=job["context"],
deleted=job.get("deleted", ()),
)
rows = []
for it in items:
if job["source"] == "fr":
page_label, locator = _locator(job, it)
ref_p_id = it["ref_p_id"] or job["p_id"]
else:
page_label, locator, ref_p_id = job["page_label"], job["locator"], 0
for code in it["codes"]:
row = OriginRow(
family=family.key,
code=code,
kind=it["kind"],
reference=it["reference"],
year=it["year"],
summary=it["summary"],
cite_kind=job["cite_kind"],
item_key=job["item_key"],
p_id=job["p_id"],
page_label=page_label,
locator=locator,
extractor=f"model:{model}@{ORIGIN_PROMPT_VERSION}",
ref_p_id=ref_p_id,
)
rows.append((row, {"job": job, "item": it}))
return rows
_ACT_SUFFIX = re.compile(r" of the (?:Social Security )?Act$", re.I)
def _consolidate(rows: list[tuple[OriginRow, dict]]) -> list[OriginRow]:
"""FR: one row per ``(code, kind, reference, year)`` (the verbatim span,
without "of the Act"; a Panel action dated 2021 and its 2023 effective
date are two facts), from a final rule before a proposed one, the
statement naming the most family codes first (the comprehensive one),
then the oldest. Book: one row per ``(code, kind, action)`` on the page
where the code's own section is the subject: a Rationale sentence about
it before a section note, then page order."""
best: dict[tuple, tuple[tuple, OriginRow]] = {}
for n, (row, meta) in enumerate(rows):
job, it = meta["job"], meta["item"]
if job["source"] == "book":
key = (row.code, row.kind, it["action"])
rank = (it["level"] != "own", job["order"])
else:
ref = _ACT_SUFFIX.sub("", _AMA.sub("", it["anchor"])).casefold()
key = (row.code, row.kind, ref, row.year)
rank = (job["rule_kind"] != "final", -len(it["codes"]), n)
if key not in best or rank < best[key][0]:
best[key] = (rank, row)
return [row for _rank, row in best.values()]
def family_origin(
con: Any,
store: Any,
family: Any,
*,
ask: Any | None,
log: RunLog | None,
books: Sequence[tuple[str, str, Path]],
limit: int = 0,
retry_failed: bool = False,
replay_model: str | None = None,
) -> tuple[list[OriginRow], dict[str, int]]:
"""Guidance rows plus model rows from FR paragraphs and book pages.
``books`` is ``(item_key, edition_label, epub path)``. The model runs
through the ledger *log* (resumable, ``limit`` caps new calls); without
*ask* nothing is asked but the finished ledger for *replay_model* is
replayed, so ``--write`` never drops model rows. Model rows are
consolidated by ``_consolidate``. Returns ``(rows, run counts)``."""
counts = {"done": 0, "skipped": 0, "failed": 0, "failed_pending": 0}
model_rows: list[tuple[OriginRow, dict]] = []
model = ask.model if ask is not None else replay_model
if model is not None:
jobs = _jobs(store, family, books)
for j in jobs:
j["hash"] = input_hash(j["user"], ORIGIN_SYSTEM[j["source"]])
log = log or RunLog(ledger_path("origin", family.key))
if ask is not None:
units = [(j["unit"], j["hash"], lambda j=j: _ask_job(ask, j)) for j in jobs]
counts = run_units(
units,
log,
model=model,
version=ORIGIN_PROMPT_VERSION,
limit=limit,
retry_failed=retry_failed,
)
for j in jobs:
entry = log.get(j["unit"], j["hash"], model, ORIGIN_PROMPT_VERSION)
if entry is not None and entry.output is not None:
model_rows += _rows(j, entry.output, family, model)
rows = _consolidate(model_rows) + guidance_origins(con, family.key, store)
rows.sort(
key=lambda r: (r.code, r.kind, r.year or 0, r.reference, r.item_key, r.p_id)
)
return rows, counts