| |
| """ |
| extract_text.py — Text Extraction: Extract plain text from all content files in CatholicCorpus. |
| |
| Walks Tasks 01–17 and extracts plain text from PDF, EPUB, HTML, HTM, XML, |
| and TXT files. Output is written to a parallel directory structure under |
| text_extraction/extracted/ so the extracted text ships alongside the |
| raw source files as part of the corpus. |
| |
| Each source file produces one .txt file with the same relative path. |
| |
| Usage: |
| python3 extract_text.py # Process all tasks |
| python3 extract_text.py --task 05_ccel # Process a single task |
| python3 extract_text.py --resume # Skip files already extracted |
| python3 extract_text.py --dry-run # Show what would be processed |
| |
| Requirements: |
| pip install pdfplumber lxml beautifulsoup4 ebooklib |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import html |
| import json |
| import logging |
| import os |
| import re |
| import sys |
| import time |
| import zipfile |
| from pathlib import Path |
| from typing import Optional |
|
|
| |
| TASK_DIR = Path(__file__).resolve().parent |
| CORPUS_ROOT = TASK_DIR.parent |
| OUTPUT_DIR = TASK_DIR / "extracted" |
| MANIFEST = CORPUS_ROOT / "master_manifest.json" |
|
|
| |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s [%(levelname)s] %(message)s", |
| handlers=[ |
| logging.FileHandler(TASK_DIR / "extract_text.log"), |
| logging.StreamHandler(), |
| ], |
| ) |
| log = logging.getLogger(__name__) |
|
|
| |
| SKIP_TASKS = {"text_extraction"} |
|
|
| |
|
|
| def extract_pdf(path: Path) -> Optional[str]: |
| """Extract text from PDF using pdfplumber, with page-at-a-time processing.""" |
| import pdfplumber |
|
|
| |
| file_size_mb = path.stat().st_size / (1024 * 1024) |
| if file_size_mb > 200: |
| log.warning(" Skipping oversized PDF (%.0f MB): %s", file_size_mb, path.name) |
| return None |
|
|
| pages = [] |
| try: |
| with pdfplumber.open(path) as pdf: |
| for i, page in enumerate(pdf.pages): |
| try: |
| text = page.extract_text() |
| if text: |
| pages.append(text) |
| except Exception as e: |
| log.warning(" Page %d failed in %s: %s", i, path.name, e) |
| continue |
| except Exception as e: |
| log.warning(" Could not open PDF %s: %s", path.name, e) |
| return None |
|
|
| return "\n\n".join(pages) if pages else None |
|
|
|
|
| def extract_epub(path: Path) -> Optional[str]: |
| """Extract text from EPUB using ebooklib + BeautifulSoup.""" |
| try: |
| import ebooklib |
| from ebooklib import epub |
| except ImportError: |
| log.warning("ebooklib not installed — skipping EPUB: %s", path) |
| return None |
|
|
| from bs4 import BeautifulSoup |
|
|
| try: |
| book = epub.read_epub(str(path), options={"ignore_ncx": True}) |
| except Exception as e: |
| log.warning(" Could not open EPUB %s: %s", path.name, e) |
| return None |
|
|
| texts = [] |
| for item in book.get_items(): |
| if item.get_type() == ebooklib.ITEM_DOCUMENT: |
| soup = BeautifulSoup(item.get_content(), "html.parser") |
| text = soup.get_text(separator="\n", strip=True) |
| if text: |
| texts.append(text) |
| return "\n\n".join(texts) if texts else None |
|
|
|
|
| def extract_html(path: Path) -> Optional[str]: |
| """Extract text from HTML/HTM using BeautifulSoup.""" |
| from bs4 import BeautifulSoup |
|
|
| try: |
| content = path.read_text(encoding="utf-8", errors="replace") |
| except Exception: |
| content = path.read_bytes().decode("latin-1", errors="replace") |
|
|
| soup = BeautifulSoup(content, "html.parser") |
|
|
| |
| for tag in soup(["script", "style", "nav", "header", "footer"]): |
| tag.decompose() |
|
|
| text = soup.get_text(separator="\n", strip=True) |
| return text if text.strip() else None |
|
|
|
|
| def extract_tei_xml(path: Path) -> Optional[str]: |
| """Extract text from TEI XML, stripping all tags.""" |
| from lxml import etree |
|
|
| try: |
| tree = etree.parse(str(path)) |
| except etree.XMLSyntaxError: |
| |
| try: |
| content = path.read_text(encoding="utf-8", errors="replace") |
| text = re.sub(r"<[^>]+>", " ", content) |
| text = html.unescape(text) |
| text = re.sub(r"\s+", " ", text).strip() |
| return text if text else None |
| except Exception: |
| return None |
|
|
| |
| ns = {"tei": "http://www.tei-c.org/ns/1.0"} |
| body = tree.find(".//tei:body", ns) |
| if body is None: |
| body = tree.find(".//body") |
| if body is None: |
| body = tree.getroot() |
|
|
| |
| text = etree.tostring(body, method="text", encoding="unicode") |
| text = re.sub(r"\s+", " ", text).strip() |
| return text if text else None |
|
|
|
|
| def extract_pos_xml(path: Path) -> Optional[str]: |
| """Extract text from .pos.xml files (ZIP-compressed POS-tagged XML).""" |
| try: |
| with zipfile.ZipFile(path, "r") as zf: |
| for name in zf.namelist(): |
| if name.endswith(".xml") or name.endswith(".POS.xml"): |
| content = zf.read(name).decode("utf-8", errors="replace") |
| text = re.sub(r"<[^>]+>", " ", content) |
| text = html.unescape(text) |
| text = re.sub(r"\s+", " ", text).strip() |
| if text: |
| return text |
| except (zipfile.BadZipFile, Exception) as e: |
| log.warning("Could not extract .pos.xml %s: %s", path, e) |
| return None |
|
|
|
|
| def extract_txt(path: Path) -> Optional[str]: |
| """Read plain text file.""" |
| try: |
| text = path.read_text(encoding="utf-8", errors="replace") |
| return text if text.strip() else None |
| except Exception: |
| return None |
|
|
|
|
| |
|
|
| EXTRACTORS = { |
| ".pdf": extract_pdf, |
| ".epub": extract_epub, |
| ".html": extract_html, |
| ".htm": extract_html, |
| ".xml": extract_tei_xml, |
| ".txt": extract_txt, |
| } |
|
|
|
|
| def extract_file(source: Path) -> Optional[str]: |
| """Route a file to the appropriate extractor.""" |
| ext = source.suffix.lower() |
|
|
| |
| if source.name.endswith(".pos.xml"): |
| return extract_pos_xml(source) |
|
|
| extractor = EXTRACTORS.get(ext) |
| if extractor is None: |
| return None |
| return extractor(source) |
|
|
|
|
| |
|
|
| def process_task(task_name: str, task_dir: Path, resume: bool, dry_run: bool) -> dict: |
| """Process all content files in a task directory.""" |
| stats = {"processed": 0, "skipped": 0, "failed": 0, "empty": 0, "already_done": 0} |
| out_task = OUTPUT_DIR / task_name |
|
|
| |
| target_exts = {".pdf", ".epub", ".html", ".htm", ".xml", ".txt"} |
|
|
| for source in sorted(task_dir.rglob("*")): |
| if not source.is_file(): |
| continue |
| if source.suffix.lower() not in target_exts: |
| continue |
| |
| if source.name.startswith("_source") or source.name == "download_script.py": |
| continue |
| |
| if source.name.endswith(".pos.xml"): |
| stats["skipped"] += 1 |
| continue |
|
|
| rel = source.relative_to(task_dir) |
| out_path = out_task / rel.with_suffix(".txt") |
|
|
| if resume and out_path.exists() and out_path.stat().st_size > 0: |
| stats["already_done"] += 1 |
| continue |
|
|
| if dry_run: |
| log.info(" [DRY-RUN] Would extract: %s", rel) |
| stats["processed"] += 1 |
| continue |
|
|
| try: |
| text = extract_file(source) |
| if text and len(text.strip()) > 10: |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| out_path.write_text(text, encoding="utf-8") |
| stats["processed"] += 1 |
| else: |
| stats["empty"] += 1 |
| except Exception as e: |
| log.warning(" FAILED: %s — %s", rel, e) |
| stats["failed"] += 1 |
|
|
| return stats |
|
|
|
|
| def discover_tasks() -> list: |
| """Find all task directories (NN_*) in the corpus root, excluding this one.""" |
| import re as _re |
| pattern = _re.compile(r"^\d{2}_") |
| found = [p.name for p in CORPUS_ROOT.iterdir() |
| if p.is_dir() and pattern.match(p.name) and p.name not in SKIP_TASKS] |
| return sorted(found) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Task 18: Extract plain text from all CatholicCorpus content files" |
| ) |
| parser.add_argument("--task", help="Process only this task folder (e.g., 05_ccel)") |
| parser.add_argument("--resume", action="store_true", help="Skip files already extracted") |
| parser.add_argument("--dry-run", action="store_true", help="Show what would be processed") |
| args = parser.parse_args() |
|
|
| OUTPUT_DIR.mkdir(exist_ok=True) |
|
|
| task_names = [args.task] if args.task else discover_tasks() |
|
|
| log.info("=" * 60) |
| log.info("CatholicCorpus — Text Extraction") |
| log.info("Corpus root: %s", CORPUS_ROOT) |
| log.info("Output: %s", OUTPUT_DIR) |
| log.info("Tasks to process: %s", ", ".join(task_names)) |
| if args.resume: |
| log.info("Mode: RESUME (skipping existing)") |
| if args.dry_run: |
| log.info("Mode: DRY-RUN") |
| log.info("=" * 60) |
|
|
| grand_stats = {"processed": 0, "skipped": 0, "failed": 0, "empty": 0, "already_done": 0} |
| start = time.time() |
|
|
| for task_name in task_names: |
| task_dir = CORPUS_ROOT / task_name |
| if not task_dir.exists(): |
| log.warning("Skipping %s — directory not found", task_name) |
| continue |
|
|
| log.info("") |
| log.info("TASK: %s", task_name) |
| log.info("-" * 40) |
|
|
| stats = process_task(task_name, task_dir, args.resume, args.dry_run) |
|
|
| for k in grand_stats: |
| grand_stats[k] += stats[k] |
|
|
| log.info(" Extracted: %d | Empty: %d | Failed: %d | Skipped: %d | Already done: %d", |
| stats["processed"], stats["empty"], stats["failed"], |
| stats["skipped"], stats["already_done"]) |
|
|
| elapsed = time.time() - start |
| log.info("") |
| log.info("=" * 60) |
| log.info("EXTRACTION COMPLETE") |
| log.info(" Total extracted: %d", grand_stats["processed"]) |
| log.info(" Empty/no-text: %d", grand_stats["empty"]) |
| log.info(" Failed: %d", grand_stats["failed"]) |
| log.info(" Skipped (.pos): %d", grand_stats["skipped"]) |
| log.info(" Already done: %d", grand_stats["already_done"]) |
| log.info(" Time: %.1f minutes", elapsed / 60) |
| log.info("=" * 60) |
|
|
| |
| summary = { |
| "generated_at": int(time.time()), |
| "generated_at_iso": time.strftime("%Y-%m-%d %H:%M:%S %Z", time.localtime()), |
| "stats": grand_stats, |
| "elapsed_seconds": round(elapsed, 1), |
| } |
| (OUTPUT_DIR / "_extraction_summary.json").write_text( |
| json.dumps(summary, indent=2) |
| ) |
| log.info("Wrote %s", OUTPUT_DIR / "_extraction_summary.json") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|