mirror of
https://github.com/bitbaum/diplodoctor.git
synced 2026-12-05 13:38:30 +01:00
57 lines
2.0 KiB
TypeScript
57 lines
2.0 KiB
TypeScript
import type { ReportFile, ReportResult } from "./report";
|
|
|
|
/**
|
|
* Models often leave out `quote`, the line a value was read from. The document
|
|
* is in hand, so the line can be found without asking the model again: the
|
|
* line that has the printed name (or the analyte) AND the printed value.
|
|
* A quote the model did give is never replaced; a value with no such line gets
|
|
* none, and the page then shows no source for it rather than an empty one.
|
|
*/
|
|
|
|
const norm = (s: string) => s.toLowerCase().replace(/\s+/g, " ").trim();
|
|
|
|
function hasToken(line: string, token: string): boolean {
|
|
const t = norm(token);
|
|
if (!t) return false;
|
|
const escaped = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
// Not inside a longer word or number: "14" must not match "114".
|
|
return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(line);
|
|
}
|
|
|
|
/** The line of `text` that carries this result's name (or analyte) and value. */
|
|
export function findSourceLine(
|
|
text: string,
|
|
result: Pick<ReportResult, "name" | "analyte" | "value">,
|
|
): string | undefined {
|
|
const lines = text
|
|
.split(/\r?\n/)
|
|
.map((l) => l.trim())
|
|
.filter(Boolean);
|
|
for (const label of [result.name, result.analyte]) {
|
|
if (!label) continue;
|
|
const hit = lines.find((l) => {
|
|
const n = norm(l);
|
|
return hasToken(n, label) && hasToken(n, result.value);
|
|
});
|
|
if (hit) return hit.slice(0, 400);
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/** The report with every missing quote filled from the first source that has the line. */
|
|
export function backfillQuotes(report: ReportFile, sources: (string | undefined)[]): ReportFile {
|
|
const texts = sources.filter((s): s is string => !!s && s.trim() !== "");
|
|
if (texts.length === 0) return report;
|
|
return {
|
|
...report,
|
|
results: report.results.map((r) => {
|
|
if (r.quote) return r;
|
|
for (const text of texts) {
|
|
const quote = findSourceLine(text, r);
|
|
if (quote) return { ...r, quote };
|
|
}
|
|
return r;
|
|
}),
|
|
};
|
|
}
|