diff options
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/extract-shihou-text.py | 57 | ||||
| -rw-r--r-- | scripts/verify-shihou.mjs | 190 |
2 files changed, 247 insertions, 0 deletions
diff --git a/scripts/extract-shihou-text.py b/scripts/extract-shihou-text.py new file mode 100644 index 0000000..0ce5fe8 --- /dev/null +++ b/scripts/extract-shihou-text.py @@ -0,0 +1,57 @@ +# 市報こだいらのPDFから、照合に使うテキストを取り出す。 +# +# 使い方: +# py -X utf8 scripts/extract-shihou-text.py ../作業tmp/市報こだいら/20261120号 +# py -X utf8 scripts/extract-shihou-text.py <フォルダ> # フォルダ内の*.pdfをまとめて処理 +# +# PDFの文字は、内容ストリームの順に並べると読み順になる(Adobe等で全選択してコピーしたのと同じ順)。 +# 座標で並べ替えると縦組み・横組みが混ざって崩れるため、ここでは「並べ替えずに」連結する。 +# 出力: 同じフォルダに「○面-pdftext.txt」(例: 6面-pdftext.txt) +import glob +import os +import re +import sys +import unicodedata + +import pdfplumber + + +def label_from_name(name: str) -> str: + """「市報こだいら令和8年11月20日号(6面).pdf」→「6面」""" + base = os.path.basename(name).replace(".pdf", "") + m = re.search(r"[((]([^))]+)[))]\s*$", base) + return m.group(1).strip() if m else base + + +def extract(path: str) -> str: + with pdfplumber.open(path) as pdf: + raw = "".join( + c["text"] for page in pdf.pages for c in page.chars if c.get("text") + ) + return unicodedata.normalize("NFKC", raw) + + +def main() -> int: + if len(sys.argv) < 2: + print(__doc__ or "使い方: extract-shihou-text.py <フォルダ>", file=sys.stderr) + return 2 + + folder = os.path.abspath(sys.argv[1]) + pdfs = sorted(glob.glob(os.path.join(folder, "*.pdf"))) + if not pdfs: + print(f"PDFがありません: {folder}", file=sys.stderr) + return 1 + + for path in pdfs: + label = label_from_name(path) + text = extract(path) + out = os.path.join(folder, f"{label}-pdftext.txt") + with open(out, "w", encoding="utf-8", newline="\n") as f: + f.write(text + "\n") + print(f"{label}: {len(text)}文字 -> {os.path.basename(out)}") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify-shihou.mjs b/scripts/verify-shihou.mjs new file mode 100644 index 0000000..c3b4078 --- /dev/null +++ b/scripts/verify-shihou.mjs @@ -0,0 +1,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; |
