src/text.js
// Deterministic text helpers: HTML-free cleaning, sentence splitting, light stemming, content terms,
// negation detection and number/date extraction. No models, no randomness.
export const STOPWORDS = new Set(
(
"a about above after again against all almost also am among an and any are around as at be because been before being below between both but by " +
"can could did do does doing down during each either else even ever every few for from further get gets got had has have having he her here hers " +
"herself him himself his how however i if in into is it its itself just let like made make makes many may me might more most much must my myself " +
"near need nor now of off often on once one only or other others ought our ours ourselves out over own per put rather really said same say says " +
"see seen she should since so some still such than that the their theirs them themselves then there these they this those though through thus to " +
"too toward towards under until up upon us use used using very via want was way we well were what when where whether which while who whom whose why " +
"will with within would yet you your yours yourself yourselves according reported reports report according also"
).split(/\s+/),
);
export const NEGATIONS = new Set([
"not", "no", "never", "none", "neither", "nor", "without", "cannot", "can't", "won't", "isn't", "aren't", "wasn't", "weren't", "doesn't", "don't",
"didn't", "hasn't", "haven't", "hadn't", "shouldn't", "wouldn't", "couldn't", "denied", "denies", "deny", "false", "untrue", "refuted",
]);
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", mdash: "—", ndash: "–", hellip: "…", rsquo: "’", lsquo: "‘", ldquo: "“", rdquo: "”" };
export function cleanText(s) {
return String(s ?? "")
.replace(/<(script|style)[\s\S]*?<\/\1\s*>/gi, " ")
.replace(/<\/(p|div|li|h[1-6]|tr)>/gi, ". ")
.replace(/<[^>]*>/g, " ")
.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (m, b) => {
if (b[0] === "#") {
const cp = b[1] === "x" || b[1] === "X" ? Number.parseInt(b.slice(2), 16) : Number.parseInt(b.slice(1), 10);
return Number.isFinite(cp) && cp > 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff) ? String.fromCodePoint(cp) : "";
}
return ENTITIES[b.toLowerCase()] ?? m;
})
.replace(/[\u0000-\u001f\u007f]/g, " ")
.replace(/\s+/g, " ")
.replace(/(\.\s*){2,}/g, ". ")
.trim();
}
const ABBREVIATIONS = new Set([
"e.g", "i.e", "etc", "vs", "mr", "mrs", "ms", "dr", "prof", "sr", "jr", "st", "inc", "ltd", "co", "corp", "no", "fig", "approx", "est", "u.s", "u.k", "u.n", "e.u",
"jan", "feb", "mar", "apr", "jun", "jul", "aug", "sep", "sept", "oct", "nov", "dec", "gov", "gen", "rep", "sen",
]);
/** Splits prose into sentences without breaking on decimals ("3.5"), initials or common abbreviations. */
export function splitSentences(text) {
const out = [];
let start = 0;
const re = /[.!?]+["'”’)\]]*(?=\s|$)/g;
let m;
while ((m = re.exec(text))) {
const end = m.index + m[0].length;
if (m[0][0] === ".") {
const lastWord = (/([A-Za-z][A-Za-z.]*)$/.exec(text.slice(start, m.index))?.[1] ?? "").toLowerCase();
if (ABBREVIATIONS.has(lastWord) || /^[a-z]$/.test(lastWord)) continue;
}
const next = text.slice(end).trimStart()[0];
if (next && !/[\p{Lu}\p{N}"“'‘([]/u.test(next)) continue;
const s = text.slice(start, end).trim();
if (s) out.push(s);
start = end;
}
const rest = text.slice(start).trim();
if (rest) out.push(rest);
return out;
}
const WORD_RE = /[\p{L}\p{N}]+(?:['’.\-][\p{L}\p{N}]+)*/gu;
export function words(text) {
return [...String(text).normalize("NFKC").toLowerCase().matchAll(WORD_RE)].map((m) => m[0].replace(/’/g, "'"));
}
/** Very light suffix stripping so "launches", "launched" and "launching" compare equal. */
export function stem(w) {
let s = w.endsWith("'s") ? w.slice(0, -2) : w;
if (s.length <= 3) return s;
if (s.endsWith("ies") && s.length > 4) s = `${s.slice(0, -3)}y`;
else if (s.endsWith("sses")) s = s.slice(0, -2);
else if (/(ch|sh|x|z)es$/.test(s)) s = s.slice(0, -2);
else if (s.endsWith("ing") && s.length > 5) s = s.slice(0, -3);
else if (s.endsWith("ed") && s.length > 4) s = s.slice(0, -2);
else if (s.endsWith("s") && !/(ss|us|is)$/.test(s)) s = s.slice(0, -1);
if (s.endsWith("e") && s.length > 4) s = s.slice(0, -1);
return s;
}
const isNumberish = (w) => /^[\p{N}.,'-]+$/u.test(w);
// Direction-of-change words. They are not content terms ("rose" and "grew" say the same thing);
// direction() reports them separately so "rose 18%" versus "fell 18%" is a disagreement.
const UP_WORDS = new Set(
"rise rises rose risen rising grow grows grew grown growing growth increase increases increased increasing climb climbs climbed climbing jump jumps jumped jumping surge surges surged surging soar soars soared soaring gained boosted".split(" "),
);
const DOWN_WORDS = new Set(
"fall falls fell fallen falling drop drops dropped dropping decline declines declined declining decrease decreases decreased decreasing shrink shrinks shrank shrunk shrinking plunge plunges plunged plunging slump slumps slumped tumble tumbles tumbled slid reduce reduces reduced reducing reduction".split(" "),
);
/** "up", "down", "mixed" (both kinds of words) or null (no direction-of-change word). */
export function direction(text) {
let up = false;
let down = false;
for (const w of words(text)) {
if (UP_WORDS.has(w)) up = true;
else if (DOWN_WORDS.has(w)) down = true;
}
return up && down ? "mixed" : up ? "up" : down ? "down" : null;
}
/** True when both texts state a single, opposite direction of change ("rose" versus "fell"). */
export const directionClash = (a, b) => (a === "up" && b === "down") || (a === "down" && b === "up");
/** Set of stemmed content words (stopwords, negations, direction-of-change words and bare numbers removed). */
export function contentTerms(text, extraStop) {
const out = new Set();
for (const w of words(text)) {
if (w.length < 2 || isNumberish(w) || STOPWORDS.has(w) || NEGATIONS.has(w) || UP_WORDS.has(w) || DOWN_WORDS.has(w) || extraStop?.has(w)) continue;
out.add(stem(w));
}
return out;
}
export function hasNegation(text) {
return words(text).some((w) => NEGATIONS.has(w) || w.endsWith("n't"));
}
export function jaccard(a, b) {
if (!a.size && !b.size) return 0;
let inter = 0;
for (const x of a) if (b.has(x)) inter++;
return inter / (a.size + b.size - inter);
}
// ------------------------------------------------------------------------------------------------
// Numbers and dates
// ------------------------------------------------------------------------------------------------
const MONTHS = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
const MONTH = "(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)";
const monthNum = (s) => MONTHS[s.slice(0, 3).toLowerCase()];
const DATE_PATTERNS = [
{ re: /\b(\d{4})-(\d{2})-(\d{2})\b/g, f: (m) => ({ y: +m[1], m: +m[2], d: +m[3] }) },
{ re: new RegExp(`\\b${MONTH}\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s+(\\d{4})\\b`, "gi"), f: (m) => ({ y: +m[3], m: monthNum(m[1]), d: +m[2] }) },
{ re: new RegExp(`\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?${MONTH}\\.?,?\\s+(\\d{4})\\b`, "gi"), f: (m) => ({ y: +m[3], m: monthNum(m[2]), d: +m[1] }) },
{ re: new RegExp(`\\b${MONTH}\\.?,?\\s+(\\d{4})\\b`, "gi"), f: (m) => ({ y: +m[2], m: monthNum(m[1]) }) },
{ re: new RegExp(`\\b${MONTH}\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b`, "gi"), f: (m) => ({ m: monthNum(m[1]), d: +m[2] }) },
];
const SCALES = { thousand: 1e3, million: 1e6, billion: 1e9, trillion: 1e12, k: 1e3, m: 1e6, mn: 1e6, b: 1e9, bn: 1e9, tn: 1e12 };
const NUM_RE = /(?<![\p{L}\p{N}.,])([$€£¥])?\s?(\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?(?!(?:st|nd|rd|th)\b)(?:\s?(%)|\s(percent|per cent)\b|\s?(thousand|million|billion|trillion)\b|\s?(bn|mn|tn|k|m|b)\b)?/giu;
const fmtDate = (d) => [d.y ?? "????", d.m ? String(d.m).padStart(2, "0") : null, d.d ? String(d.d).padStart(2, "0") : null].filter(Boolean).join("-");
/** Extracts quantities: [{kind: percent|currency|number|year|date, value?, date?, raw}] */
export function extractQuantities(text) {
let s = String(text);
const out = [];
for (const { re, f } of DATE_PATTERNS) {
s = s.replace(re, (...args) => {
const m = args.slice(0, -2);
const d = f(m);
if (d.m && d.m >= 1 && d.m <= 12 && (!d.d || (d.d >= 1 && d.d <= 31))) out.push({ kind: "date", date: d, raw: m[0], label: fmtDate(d) });
return " ".repeat(m[0].length);
});
}
for (const m of s.matchAll(NUM_RE)) {
const [raw, cur, intPart, dec, pct, pctWord, scaleWord, scaleLetter] = m;
let value = Number(intPart.replace(/,/g, "") + (dec ?? ""));
if (!Number.isFinite(value)) continue;
// bn/mn/tn always scale; single letters (k, m, b) only after a currency symbol ("5 m" could be metres).
const letterScales = scaleLetter && (cur || /^(bn|mn|tn)$/i.test(scaleLetter));
const scale = scaleWord ? SCALES[scaleWord.toLowerCase()] : letterScales ? SCALES[scaleLetter.toLowerCase()] : 1;
value *= scale;
let kind = "number";
if (pct || pctWord) kind = "percent";
else if (cur) kind = "currency";
else if (!dec && !intPart.includes(",") && scale === 1 && value >= 1900 && value <= 2100) kind = "year";
const shown = scaleLetter && !letterScales ? raw.slice(0, raw.length - scaleLetter.length).trim() : raw.trim();
out.push({ kind, value, raw: shown, ...(cur ? { currency: cur } : {}) });
}
return out;
}
const compatible = (a, b) => {
if (a.kind === "date" || b.kind === "date") return a.kind === b.kind;
if (a.kind === "percent" || b.kind === "percent") return a.kind === b.kind;
if (a.kind === "year" || b.kind === "year") return a.kind === b.kind;
if (a.kind === "currency" && b.kind === "currency") return a.currency === b.currency;
return true; // number <-> currency
};
function dateRelation(a, b) {
const fields = ["y", "m", "d"].filter((k) => a[k] !== undefined && b[k] !== undefined);
if (!fields.length) return "unrelated";
return fields.every((k) => a[k] === b[k]) ? "match" : "conflict";
}
export function sameQuantity(a, b) {
if (!compatible(a, b)) return false;
if (a.kind === "date") return dateRelation(a.date, b.date) === "match";
return Math.abs(a.value - b.value) <= 1e-9 * Math.max(1, Math.abs(a.value), Math.abs(b.value));
}
/**
* Compares the quantities of a claim with those of an excerpt.
* Returns { matched: [raw], missing: [raw], conflicts: [{claim, kind, source: [raw]}] }.
* A claim quantity "conflicts" when it is absent from the excerpt but the excerpt states a
* compatible quantity of the same kind that matches none of the claim's quantities (for example
* 45% versus 30%).
*/
export function compareQuantities(claimQ, excerptQ) {
const res = { matched: [], missing: [], conflicts: [] };
// An excerpt quantity that equals one of the claim's quantities is accounted for, so it is never a
// rival: "9.4 km" versus "9.4 km, compared with 5.1 km" is an extra figure, not a disagreement.
const free = excerptQ.filter((e) => !claimQ.some((q) => sameQuantity(q, e)));
for (const q of claimQ) {
if (excerptQ.some((e) => sameQuantity(q, e))) {
res.matched.push(q.raw);
continue;
}
const rivals = free.filter((e) => compatible(q, e) && (q.kind !== "date" || dateRelation(q.date, e.date) === "conflict"));
if (rivals.length) res.conflicts.push({ claim: q.raw, kind: q.kind, source: [...new Set(rivals.map((r) => r.raw))] });
else res.missing.push(q.raw);
}
return res;
}