Datasets:

Languages:
English
ArXiv:
License:
File size: 8,777 Bytes
7527970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cbe47d
 
 
 
 
7527970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from __future__ import annotations

# ruff: noqa: E402

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:
            # Relative symlink keeps the test folder portable.
            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()