| from __future__ import annotations |
|
|
| |
|
|
| import argparse |
| import csv |
| import os |
| import shutil |
| import sys |
| import re |
| from pathlib import Path |
|
|
| try: |
| from scripts.defextra_markers import ( |
| doi_suffix, |
| normalize_arxiv, |
| normalize_doi, |
| normalize_paper_id, |
| ) |
| from scripts.defextra_pdf_aliases import candidate_pdf_aliases |
| except ModuleNotFoundError as exc: |
| if exc.name != "scripts": |
| raise |
| PROJECT_ROOT = Path(__file__).resolve().parent.parent |
| if str(PROJECT_ROOT) not in sys.path: |
| sys.path.insert(0, str(PROJECT_ROOT)) |
| from scripts.defextra_markers import ( |
| doi_suffix, |
| normalize_arxiv, |
| normalize_doi, |
| normalize_paper_id, |
| ) |
| from scripts.defextra_pdf_aliases import candidate_pdf_aliases |
|
|
|
|
| def _build_pdf_index( |
| source_dirs: list[Path], |
| *, |
| skip_dir: Path | None = None, |
| ) -> dict[str, Path]: |
| index: dict[str, Path] = {} |
| version_re = re.compile(r"^(?P<base>.+?)(v\d+)$", re.IGNORECASE) |
| arxiv_re = re.compile(r"^(?P<base>\d{4}\.\d{4,5})v\d+$", re.IGNORECASE) |
| pii_re = re.compile(r"(S\d{8,})", re.IGNORECASE) |
| for source_dir in source_dirs: |
| if not source_dir.exists(): |
| continue |
| for suffix in ("*.pdf", "*.PDF"): |
| for path in source_dir.rglob(suffix): |
| if skip_dir is not None: |
| try: |
| path_abs = path.resolve() |
| except (OSError, RuntimeError): |
| path_abs = path.absolute() |
| if skip_dir == path_abs or skip_dir in path_abs.parents: |
| continue |
| stem = path.stem |
| for key in {stem, stem.lower()}: |
| index.setdefault(key, path) |
| if stem.startswith("paper_"): |
| stripped = stem[len("paper_") :] |
| if stripped: |
| index.setdefault(stripped, path) |
| index.setdefault(stripped.lower(), path) |
| if stem.endswith("_fixed") or stem.endswith("-fixed"): |
| base = ( |
| stem[: -len("_fixed")] |
| if stem.endswith("_fixed") |
| else stem[: -len("-fixed")] |
| ) |
| if base: |
| index[base] = path |
| index[base.lower()] = path |
| if base.startswith("paper_"): |
| stripped_base = base[len("paper_") :] |
| if stripped_base: |
| index[stripped_base] = path |
| index[stripped_base.lower()] = path |
| match = arxiv_re.match(stem) |
| if match: |
| base = match.group("base") |
| index.setdefault(base, path) |
| index.setdefault(base.lower(), path) |
| match = version_re.match(stem) |
| if match: |
| base = match.group("base") |
| index.setdefault(base, path) |
| index.setdefault(base.lower(), path) |
| pii_match = pii_re.search(stem) |
| if pii_match: |
| pii = pii_match.group(1) |
| index.setdefault(pii, path) |
| index.setdefault(pii.lower(), path) |
| return index |
|
|
|
|
| def _candidate_ids(paper_id: str, doi: str, arxiv: str) -> list[str]: |
| candidates = [] |
| if paper_id: |
| candidates.append(paper_id) |
| candidates.append(normalize_paper_id(paper_id)) |
| if doi: |
| norm_doi = normalize_doi(doi) |
| candidates.append(norm_doi) |
| candidates.append(doi_suffix(norm_doi)) |
| if arxiv: |
| norm_arxiv = normalize_arxiv(arxiv) |
| candidates.append(norm_arxiv) |
| ordered: list[str] = [] |
| seen = set() |
| for item in candidates: |
| value = (item or "").strip() |
| if not value: |
| continue |
| if value not in seen: |
| seen.add(value) |
| ordered.append(value) |
| for alias in candidate_pdf_aliases(paper_id, doi, arxiv): |
| value = (alias or "").strip() |
| if not value: |
| continue |
| if value not in seen: |
| seen.add(value) |
| ordered.append(value) |
| return ordered |
|
|
|
|
| def _normalize_title(title: str) -> str: |
| return " ".join(title.lower().split()) |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser( |
| description="Build a test-only PDF folder for DefExtra hydration.", |
| ) |
| parser.add_argument( |
| "--legal-csv", |
| type=Path, |
| default=Path("results/paper_results/defextra_legal.csv"), |
| help="Legal DefExtra CSV with paper_ids.", |
| ) |
| parser.add_argument( |
| "--source-dir", |
| action="append", |
| type=Path, |
| default=[ |
| Path("ManualPDFsGROBID"), |
| Path("ManualPDFsGROBID/manual_pdfs/manual_pdfs"), |
| ], |
| help="Source PDF directory (can be repeated).", |
| ) |
| parser.add_argument( |
| "--output-dir", |
| type=Path, |
| default=Path("ManualPDFsGROBID/test_pdfs"), |
| help="Output directory for test PDFs.", |
| ) |
| parser.add_argument( |
| "--mode", |
| choices=("symlink", "copy"), |
| default="symlink", |
| help="Whether to symlink or copy PDFs into the output dir.", |
| ) |
| parser.add_argument( |
| "--report", |
| type=Path, |
| default=None, |
| help="Optional report file listing missing PDFs.", |
| ) |
| args = parser.parse_args() |
|
|
| if not args.legal_csv.exists(): |
| raise SystemExit(f"Legal CSV not found: {args.legal_csv}") |
|
|
| pdf_index = _build_pdf_index( |
| args.source_dir, |
| skip_dir=args.output_dir.resolve(), |
| ) |
| args.output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| missing: list[str] = [] |
| matched = 0 |
| seen_ids: set[str] = set() |
|
|
| with args.legal_csv.open("r", encoding="utf-8", newline="") as handle: |
| reader = csv.DictReader(handle) |
| rows = list(reader) |
|
|
| title_to_candidates: dict[str, list[str]] = {} |
| for row in rows: |
| title = _normalize_title(row.get("paper_title") or "") |
| if not title: |
| continue |
| paper_id = (row.get("paper_id") or "").strip() |
| doi = (row.get("paper_doi") or "").strip() |
| arxiv = (row.get("paper_arxiv") or "").strip() |
| candidates = _candidate_ids(paper_id, doi, arxiv) |
| if candidates: |
| title_to_candidates.setdefault(title, []).extend(candidates) |
|
|
| for row in rows: |
| paper_id = (row.get("paper_id") or "").strip() |
| if not paper_id or paper_id in seen_ids: |
| continue |
| seen_ids.add(paper_id) |
| doi = (row.get("paper_doi") or "").strip() |
| arxiv = (row.get("paper_arxiv") or "").strip() |
| title_key = _normalize_title(row.get("paper_title") or "") |
| path = None |
| for candidate in _candidate_ids(paper_id, doi, arxiv): |
| key = candidate.lower() |
| path = pdf_index.get(key) or pdf_index.get(f"paper_{key}") |
| if path is not None: |
| break |
| if path is None and title_key in title_to_candidates: |
| for candidate in title_to_candidates[title_key]: |
| key = candidate.lower() |
| path = pdf_index.get(key) or pdf_index.get(f"paper_{key}") |
| if path is not None: |
| break |
| if path is None: |
| missing.append(paper_id) |
| continue |
|
|
| dest_id = normalize_paper_id(paper_id) or paper_id |
| dest = args.output_dir / f"{dest_id}.pdf" |
| if dest.is_symlink(): |
| try: |
| current = dest.resolve(strict=True) |
| except (OSError, RuntimeError): |
| current = None |
| if current is None or current != path.resolve(): |
| dest.unlink() |
| else: |
| matched += 1 |
| continue |
| elif dest.exists(): |
| matched += 1 |
| continue |
|
|
| if args.mode == "copy": |
| shutil.copy2(path, dest) |
| else: |
| |
| rel = Path(os.path.relpath(path, start=dest.parent)) |
| dest.symlink_to(rel) |
| matched += 1 |
|
|
| print(f"Matched PDFs: {matched}") |
| print(f"Missing PDFs: {len(missing)}") |
| if missing: |
| print("Missing IDs (first 20):", ", ".join(missing[:20])) |
|
|
| if args.report is not None: |
| args.report.parent.mkdir(parents=True, exist_ok=True) |
| args.report.write_text("\n".join(missing) + "\n", encoding="utf-8") |
| print(f"Wrote report to {args.report}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|