#!/usr/bin/env python3 """ Batch extract OCR text layer from PDF using PyMuPDF. Outputs per-page .txt files and per-section combined files. """ import fitz import os import json PDF_PATH = "pdf/科研費申請書の教科書.pdf" OUTPUT_DIR = "raw_text" # Sections: (filename_prefix, start_page, end_page) - 1-indexed SECTIONS = [ # 第1章 申請書を書く前に (p.1-33) ("ch01_1.1_本書の使い方", 1, 5), ("ch01_1.2_研究費の種類", 6, 10), ("ch01_1.3_何を研究するか", 11, 15), ("ch01_1.4_オズボーンのチェックリスト", 16, 17), ("ch01_1.5_エフォート", 18, 25), ("ch01_1.6_研究課題名", 26, 33), # 第2章 何を・どこに書くか (p.34-160) ("ch02_2.1_申請書の原則", 34, 36), ("ch02_2.2_要素と構成", 37, 46), ("ch02_2.2A_概要要旨", 47, 55), ("ch02_2.2B_背景と問い", 56, 73), ("ch02_2.2C_研究動向と位置づけ", 74, 83), ("ch02_2.2D_独自性独創性特色", 84, 91), ("ch02_2.2E_本研究の目的", 92, 98), ("ch02_2.2F_研究方法研究計画", 99, 109), ("ch02_2.2G_準備状況", 110, 114), ("ch02_2.2H_申請者の役割", 115, 119), ("ch02_2.2I_創造性将来展望", 120, 124), ("ch02_2.2J_研究環境", 125, 127), ("ch02_2.2K_人権の保護", 128, 132), ("ch02_2.2L_研究室の選定理由", 133, 139), ("ch02_2.2M_研究遂行能力業績", 140, 147), ("ch02_2.2N_自己分析自己PR", 148, 154), ("ch02_2.2O_評価書推薦書", 155, 160), # 第3章 申請書のデザイン (p.161-209) ("ch03_3.1_図表のテクニック", 161, 166), ("ch03_3.2_日本語作文の基本テクニック", 167, 172), ("ch03_3.3_わかりやすい日本語作文", 173, 175), ("ch03_3.4_ニュアンスを示す日本語作文", 176, 178), ("ch03_3.5_引用文献のテクニック", 179, 180), ("ch03_3.6_頻出Wordテクニック", 181, 184), ("ch03_3.7_フォントと修飾のテクニック", 185, 194), ("ch03_3.8_配置と間隔のテクニック", 195, 202), ("ch03_3.9_揃えるテクニック", 203, 205), ("ch03_3.10_削る詰め込むテクニック", 206, 209), # 第4章 申請書を書いた後に (p.210-216) ("ch04_4.1_チェックリスト", 210, 211), ("ch04_4.2_推敲", 212, 216), ] def main(): os.makedirs(OUTPUT_DIR, exist_ok=True) doc = fitz.open(PDF_PATH) print(f"PDF has {doc.page_count} pages") # Extract per-page text files (all pages for future use) for page_num in range(doc.page_count): page = doc[page_num] text = page.get_text("text") out_file = os.path.join(OUTPUT_DIR, f"page_{page_num+1:04d}.txt") with open(out_file, "w", encoding="utf-8") as f: f.write(text) print(f"Extracted {doc.page_count} per-page text files") # Combine per-section for name, start, end in SECTIONS: combined = [] for pg in range(start, end + 1): pg_file = os.path.join(OUTPUT_DIR, f"page_{pg:04d}.txt") with open(pg_file, "r", encoding="utf-8") as f: combined.append(f"===== Page {pg} =====\n{f.read()}") section_file = os.path.join(OUTPUT_DIR, f"{name}.txt") with open(section_file, "w", encoding="utf-8") as f: f.write("\n\n".join(combined)) print(f" {name}: pages {start}-{end}") doc.close() print("Done!") if __name__ == "__main__": main()