1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
|
// 市報こだいらのPDFから取り出したテキストと、イベント抽出ドラフトを照合する。
//
// 使い方:
// npm run shihou:verify # 作業tmp/市報こだいら の最新号
// node scripts/verify-shihou.mjs <フォルダ> # 号のフォルダを指定
// node scripts/verify-shihou.mjs <フォルダ> --md 別のドラフト.md
// node scripts/verify-shihou.mjs <フォルダ> --only-ng
//
// テキストの入手方法は2通り。どちらでも動く。
// 1) scripts/extract-shihou-text.py が作る「○面-pdftext.txt」(無ければ自動で作る)
// 2) PDFビューアで全選択してコピーした「○面コピペ.txt」
// 1) を優先して使う。PDFの文字は内容ストリーム順に並べると読み順になり、数字も分断されない。
//
// 照合の考え方:
// ドラフト(イベント抽出.md)に書いた日付・電話番号・市HP IDが、PDFのテキストに実在するかを見る。
// 表記ゆれを吸収するため NFKC 正規化し、空白・改行を落としてから比較する。
// NG は「PDFに無い」と断定できない(数字が欠けている・別表記など)。NG は目視で確認する。
import { execFileSync } from 'node:child_process';
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
const args = process.argv.slice(2);
const flag = (name) => args.includes(name);
const option = (name) => {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : null;
};
const positional = args.filter((a) => !a.startsWith('--') && a !== option('--md'));
const DEFAULT_ROOT = path.resolve('../作業tmp/市報こだいら');
// テキストファイルの優先順位(先頭ほど優先)
const PAGE_SUFFIXES = ['-pdftext.txt', 'コピペ.txt'];
/** フォルダ内の面テキストを探す */
function findPageFiles(dir) {
const files = readdirSync(dir);
for (const suffix of PAGE_SUFFIXES) {
const hits = files.filter((f) => f.endsWith(suffix)).sort();
if (hits.length > 0) return { files: hits, suffix };
}
return { files: [], suffix: null };
}
/** PDFから面テキストを作る(pdfplumber が必要) */
function runExtractor(dir) {
const script = path.join(SCRIPT_DIR, 'extract-shihou-text.py');
let lastError = '';
for (const cmd of ['py', 'python']) {
try {
const out = execFileSync(cmd, ['-X', 'utf8', script, dir], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
});
for (const line of out.trim().split('\n')) console.log(` ${line}`);
return true;
} catch (error) {
lastError = String(error.stderr ?? error.message);
}
}
if (lastError) console.error(lastError.trim());
return false;
}
/** 号のフォルダかどうか(面テキストかPDFがある) */
function isIssueDir(dir) {
return readdirSync(dir).some(
(f) => f.endsWith('-pdftext.txt') || f.endsWith('コピペ.txt') || f.endsWith('.pdf'),
);
}
// 「20261120号」のようなフォルダ名を新しい順に並べる
function latestIssueDir(root) {
const dirs = readdirSync(root)
.filter((name) => statSync(path.join(root, name)).isDirectory())
.map((name) => path.join(root, name))
.filter(isIssueDir)
.sort();
if (dirs.length === 0) throw new Error(`号のフォルダが見つかりません: ${root}`);
return dirs[dirs.length - 1];
}
let dir;
if (positional[0]) {
dir = path.resolve(positional[0]);
if (!statSync(dir).isDirectory()) throw new Error(`フォルダではありません: ${dir}`);
if (!isIssueDir(dir)) dir = latestIssueDir(dir);
} else {
dir = latestIssueDir(DEFAULT_ROOT);
}
let { files: pageFiles, suffix } = findPageFiles(dir);
if (pageFiles.length === 0) {
console.log('面テキストが無いので、PDFから取り出します…');
if (!runExtractor(dir)) {
throw new Error(
`PDFからテキストを取り出せませんでした。pdfplumber が入っているか確認してください(py -m pip install pdfplumber)。\n` +
`または、PDFを全選択してコピーしたテキストを「○面コピペ.txt」として ${dir} に置いてください。`,
);
}
({ files: pageFiles, suffix } = findPageFiles(dir));
if (pageFiles.length === 0) throw new Error(`テキストを取り出せませんでした: ${dir}`);
}
const mdPath = path.resolve(option('--md') ?? path.join(dir, 'イベント抽出.md'));
if (!existsSync(mdPath)) {
throw new Error(
`照合するドラフトが見つかりません: ${mdPath}\n--md でファイルを指定できます(例: --md イベント抽出.md)。`,
);
}
const md = readFileSync(mdPath, 'utf8');
// 全角数字・全角括弧をそろえ、空白と改行をすべて落とす(数字の分断を戻すため)
const normalize = (s) => s.normalize('NFKC').replace(/[\s\u3000\u200b\ufeff]+/g, '');
const digitsOnly = (s) => normalize(s).replace(/\D/g, '');
const labelOf = (file) => file.slice(0, -suffix.length);
const pages = pageFiles.map((file) => {
const text = normalize(readFileSync(path.join(dir, file), 'utf8'));
return { label: labelOf(file), text, digits: text.replace(/\D/g, '') };
});
/** 対象がどの面に出てくるかを返す(電話番号は数字だけで照合する) */
function findIn(needle, asDigits = false) {
return pages
.filter((p) => (asDigits ? p.digits : p.text).includes(needle))
.map((p) => p.label);
}
const unique = (list) => [...new Set(list)];
// ドラフトから照合したい項目を拾う
const phones = unique(md.match(/0\d{1,4}-\d{2,4}-\d{3,4}/g) ?? []);
const ids = unique(md.match(/(?<![0-9])1\d{5}(?![0-9])/g) ?? []);
const dates = unique(md.match(/(?<![0-9])\d{1,2}月\d{1,2}日/g) ?? []);
const sections = [
{
title: '電話番号',
items: phones.map((value) => ({ value, needle: digitsOnly(value), asDigits: true })),
},
{
title: '市HP ID',
items: ids.map((value) => ({ value, needle: value })),
},
{
title: '日付',
items: dates.map((value) => ({ value, needle: value.normalize('NFKC') })),
},
];
console.log(`対象: ${dir}`);
console.log(`テキスト: ${pages.map((p) => p.label).join('、')}(${suffix})`);
console.log(`ドラフト: ${mdPath}`);
console.log('');
let ok = 0;
let ng = 0;
const ngList = [];
for (const section of sections) {
console.log(`■ ${section.title}(${section.items.length}件)`);
for (const { value, needle, asDigits } of section.items) {
const hits = findIn(needle, asDigits);
if (hits.length > 0) {
ok += 1;
if (!flag('--only-ng')) console.log(` OK ${value} → ${hits.join('、')}`);
} else {
ng += 1;
ngList.push(`${section.title}: ${value}`);
console.log(` NG ${value} → 見つかりません(分断・表記ゆれの可能性。目視で確認)`);
}
}
console.log('');
}
console.log(`結果: OK ${ok} / NG ${ng}`);
if (ng > 0) {
console.log('NGの項目:');
for (const line of ngList) console.log(` - ${line}`);
console.log(
'※NGは「PDFに無い」と断定できません。数字が欠けている・別表記などの場合があるので、面の画像で確認してください。',
);
}
// NG があれば終了コード 1(CIや npm script から気づけるように)
process.exitCode = ng > 0 ? 1 : 0;
|