PT Calculators 如何將軍事體能評分表由 PDF 轉成 JSON 並驗證數據
Turning military fitness score tables from PDF into JSON, and proving the numbers match
PT Calculators 將美國陸軍 AFT 和海軍陸戰隊 PFT 的 PDF 評分表轉成 JSON,並透過多項檢查核對資料是否與 PDF 一致。流程先用 `pdftotext -layout` 擷取文字,再由解析器讀取文字檔,而非直接解析 PDF。AFT 評分表共整理出 397 行、7,940 個儲存格;重複列若有差異,建置便會失敗。
Disclosure: I run PT Calculators, the site this post is about. There are no affiliate links here. This post was written with AI assistance; every code excerpt and number below was copied from the project repo or from a test run on 2026-11-24.
PT Calculators is a small static site with score calculators for the US Army Fitness Test (AFT) and the Marine Corps Physical Fitness Test (PFT). The whole product is a lookup: you enter age, sex and a performance, and the site returns the points the official table gives. If one cell in the table is wrong, the calculator is wrong, and nobody will tell you until a Soldier or a Marine gets a different score on test day.
The official tables only exist as PDFs. This post is about how I get them out of the PDF and into JSON, and the checks I use to convince myself the JSON says what the PDF says.
The sources
- Army:
AFT_Scoring_Scales_250601.pdf, approved 15 May 2025, effective 1 June 2025. 9 pages. - Marines:
MCO 6100.13A W/ADMIN CH-5, signed 28 May 2025. 80 pages, of which the scoring tables are a handful (tables 2-2 and 2-4 to 2-8).
army.mil blocks scripted downloads and marines.mil returns 403 to scripts, so the copies in the repo came from Wayback Machine captures. The README records where each file came from and when it was fetched, and the PFT order also has a sha256 noted, so if the official file changes I can tell which version the site was built from.
Step 1: pdftotext -layout
I do not parse the PDF directly. pdftotext -layout (from poppler) keeps the column positions as spaces, which is good enough for tables:
pdftotext -layout data/sources/AFT_Scoring_Scales_250601.pdf data/sources/aft.txt
pdftotext -layout data/sources/MCO_6100.13A_W_ADMIN_CH-5.pdf data/sources/pft.txt
The text files are committed next to the PDFs. The parsers read the text, never the PDF, so a parse is reproducible and a diff of the text file shows exactly what changed when a new PDF comes out.
The Army tables: fixed width, so check the row shape
The AFT tables are regular. Every row starts and ends with the point value, and between them sit 20 cells: 10 age groups, each with a M|C (male and combat) column and an F column. Here is the top of the deadlift table as pdftotext prints it:
Points M|C F M|C F M|C F ...
100 340 220 350 230 350 240 ... 100
99 --- --- 340 --- --- 230 ... 99
98 330 210 --- 220 340 220 ... 98
--- means that point value cannot be earned in that column. For a 17-21 male, 340 lb is 100 points and 330 lb is 98; there is no 99.
So the row filter is strict on purpose. A line is a data row only if it has exactly 22 tokens and the first and last token are the same number:
const tok = line.trim().split(/\s+/);
if (tok.length !== 22 || !/^\d+$/.test(tok[0]) || tok[0] !== tok[21]) continue;
const points = Number(tok[0]);
const vals = tok.slice(1, 21).map(toVal);
const prev = tables[current].get(points);
if (prev && JSON.stringify(prev) !== JSON.stringify(vals)) throw new Error(`${current} ${points}: page overlap differs`);
tables[current].set(points, vals);
The prev check exists because of a quirk of this PDF. In the sprint-drag-carry, plank and two-mile run tables, the 60-point row (the passing line) is printed at the bottom of one page and again at the top of the next. The parser keeps one copy, but only if both copies agree cell for cell. If a future PDF has a typo in one of them, the build fails instead of picking one silently.
The output from the current PDF:
mdl 47 point rows
hrp 47 point rows
sdc 101 point rows
plk 101 point rows
run 101 point rows
That is 397 rows of 20 cells, 7,940 cells. Counting the duplicated 60 rows, the PDF prints 8,000 cells, and 1,326 of them are ---. Values are stored per age group as [points, value] pairs with the blanks dropped, and times are converted to seconds.
The four alternate aerobic events (walk, bike, swim, row) are a single row each, so the parser just asserts it found exactly four rows of 20 times and throws otherwise.
The Marine tables: ragged rows, so use the Max/Min header
The PFT tables are harder. Here is part of the male and female pull-up table from pft.txt:
17-20 21-25 26-30 31-35 36-40 41-45 46-50 51+ ...
Max 20 23 23 23 21 20 19 18 Max 7 ...
Min 4 5 5 5 5 5 4 3 Min 1 ...
Reps 17-20 21-25 26-30 31-35 36-40 41-45 46-50 51+ ...
23 100 100 100
22 97 97 97
21 93 93 93 100
20 100 90 90 90 96 100
The 23-rep row has three values, and they belong to the 21-25, 26-30 and 31-35 columns. Nothing in the text says that except their horizontal position, and positions in pdftotext output drift by a character or two between rows. Matching cells to columns by x coordinate would work most of the time, which is the worst kind of parser.
What the PDF does give you is a Max row and a Min row for every column. A column only has a value for a given rep count (or run time) if that count falls between its Min and Max. So for each data row, the parser computes which columns must have a value, and requires the number of cells it found to be exactly that:
const key = toVal(st[0].s);
const want = AGES.map((_, i) => i).filter((i) =>
kind === 'reps' ? key >= min[sex][i] && key <= max[sex][i] : key <= min[sex][i] && key >= max[sex][i],
);
const vals = st.slice(1).map((x) => Number(x.s));
if (vals.length !== want.length) fail(`${id} ${sex} ${st[0].s}: ${vals.length} cells, expected ${want.length} (line: ${line.trim()})`);
want.forEach((col, j) => {
if (cols[sex][col].has(key)) fail(`${id} ${sex} ${AGES[col]} ${st[0].s}: duplicate row`);
cols[sex][col].set(key, vals[j]);
});
For the 23-rep row, only columns with Max >= 23 qualify (21-25, 26-30, 31-35), so three cells are expected and three are found. The x coordinate is only used once, to split the male half of the line from the female half.
After a table is assembled, every column gets checked against what the PDF header promised:
if (rows[0][0] !== max[sex][i] || rows[0][1] !== maxPts) fail(`${where}: top row ${rows[0]} != Max ${max[sex][i]}/${maxPts}`);
const last = rows[rows.length - 1];
const minP = typeof minPts === 'object' ? minPts[sex] : minPts;
if (last[0] !== min[sex][i] || last[1] !== minP) fail(`${where}: bottom row ${last} != Min ${min[sex][i]}/${minP}`);
for (let k = 1; k < rows.length; k++) {
if (Math.abs(rows[k][0] - rows[k - 1][0]) !== step) fail(`${where}: gap between ${rows[k - 1][0]} and ${rows[k][0]}`);
if (rows[k][1] > rows[k - 1][1]) fail(`${where}: points rise at ${rows[k][0]}`);
}
So each column must start at the printed Max with the right points (100, or 70 for push-ups, which cap at 70), end at the printed Min with the right points (40, or 60 for female pull-ups), have no gaps in the step (1 rep, 10 seconds for the run, 5 seconds for the row) and never go up in points as performance gets worse. A shifted cell almost always breaks one of these.
The plank is a single table for everyone, printed as two Time/Score column pairs, so it gets an exact assertion: 61 rows, from 3:45 = 100 down to 1:10 = 40, with the points dropping by exactly one per row.
Current output:
pullup 196 cells
pushup 593 cells
run 1053 cells
runAlt 1053 cells
row 1126 cells
rowAlt 1126 cells
plank 61 rows
The tests: spot checks read off the PDF, not off the JSON
Shape checks catch misaligned columns. They do not catch a parser that is consistently wrong in a way that still looks like a valid table. For that, the tests compare the calculator against values I read from the PDF by eye.
For the PFT, 29 combinations of table, sex, age group and performance were drawn with a seeded random generator, and the expected points for each were read off the rendered PDF pages (the text layer for the 3-mile run table). The rule was that they are not copied from the parser output, because then the test would only prove the parser agrees with itself.
const PDF_COMBOS: Combo[] = [
['rowAlt', 'M', '36-40', '21:25', 82],
['run', 'M', '36-40', '25:40', 57],
['pushup', 'F', '26-30', '48', 68],
['pullup', 'M', '17-20', '13', 74],
['plank', 'F', '51+', '2:36', 73],
// ... 24 more
];
function mismatches(combos: Combo[]) {
return combos.filter(([t, sex, age, raw, pts]) => score(t, age, sex, perfOf(t, raw)) !== pts);
}
test('29 random combos match the PDF', () => {
assert.equal(PDF_COMBOS.length >= 20, true);
assert.deepEqual(mismatches(PDF_COMBOS), []);
});
The positive control
A test like the one above has a quiet failure mode: if the comparison in mismatches() were written wrong, for example comparing against the wrong field, it could return an empty list for any input and the test would pass. So there is a second test that adds one deliberately wrong row and requires the helper to report exactly that row:
test('positive control: a wrong expected value is caught', () => {
// Male 17-20 pull-ups: 20 reps is 100 points in the PDF, so expecting 99 must be reported as a mismatch.
const bad: Combo = ['pullup', 'M', '17-20', '20', 99];
assert.deepEqual(mismatches([...PDF_COMBOS, bad]), [bad]);
});
If this test ever fails, the spot-check test is not checking anything and its green result means nothing.
The Army side has the same kind of hand-checked values, chosen around the places where mistakes are likely: the --- gaps and the 60-point line.
assert.equal(scoreEvent('mdl', '17-21', 'M', 330), 98); // 99 is "---"
assert.equal(scoreEvent('sdc', '17-21', 'M', parseTime('2:28')!), 60);
assert.equal(scoreEvent('sdc', '17-21', 'M', parseTime('2:29')!), 59);
assert.equal(scoreEvent('plk', '17-21', 'M', parseTime('1:29')!), 58); // 59 is "---"
There are also tests for the rules around the tables rather than the tables themselves, for example that a PFT total of 120 from three minimum scores is still a fail (the order needs 150), that one event under the minimum fails the whole test however high the total is, and that female Marines in the 32 combat arms PMOS are scored on the male tables. In the AFT, the combat standard scores everyone on the M|C column and needs 350 total.
The full run today: 19 tests, 19 pass. The parsers also regenerated byte-identical aft.json and pft.json.
What I would tell someone doing the same
- Keep the source PDF and its text dump in the repo, with a note of where and when you got it. Government sites move and block scripts.
- Make the parser strict and loud. Count tokens, check that duplicated rows agree, and use whatever invariants the document prints about itself (here, the Max/Min rows) to decide what a row must contain instead of guessing from positions.
- Check shape and content separately. Shape checks catch misalignment across thousands of cells. Spot checks against the rendered page catch a parser that is wrong in a consistent way.
- Take expected values from the document, not from your own output, and add a positive control so a broken comparison cannot pass.
If you want to see the result, the Army tables are browsable at ptcalculators.com/aft-score-chart and the Marine calculator is at ptcalculators.com/marine-pft-calculator. If you find a cell that disagrees with the PDF, I would like to know.
來源:DEV Community · dev.to