File size: 8,687 Bytes
7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 7527970 5cbe47d 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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
from __future__ import annotations
# ruff: noqa: E402
import argparse
import csv
import re
import time
from pathlib import Path
from typing import Dict, Tuple
try:
from scripts.defextra_markers import normalize_paper_id
except ModuleNotFoundError as exc:
if exc.name != "scripts":
raise
import sys
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 normalize_paper_id
def _normalize_title(title: str) -> str:
return " ".join((title or "").lower().split())
def _load_csv(path: Path) -> list[dict]:
with path.open(encoding="utf-8", newline="") as handle:
return list(csv.DictReader(handle))
def _parse_missing_report(path: Path) -> Tuple[list[str], list[str]]:
missing_defs: list[str] = []
missing_ctxs: list[str] = []
if not path.exists():
return missing_defs, missing_ctxs
section = None
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line.startswith("Missing definitions"):
section = "def"
continue
if line.startswith("Missing contexts"):
section = "ctx"
continue
if not line.startswith("-"):
continue
item = line[1:].strip()
if section == "def":
missing_defs.append(item)
elif section == "ctx":
missing_ctxs.append(item)
return missing_defs, missing_ctxs
def _index_recent_pdfs(
pdf_dir: Path,
cutoff_ts: float,
) -> Dict[str, Path]:
index: Dict[str, Path] = {}
if not pdf_dir.exists():
return index
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 suffix in ("*.pdf", "*.PDF"):
for path in pdf_dir.rglob(suffix):
try:
if path.stat().st_mtime < cutoff_ts:
continue
except OSError:
continue
stem = path.stem
keys = {stem, stem.lower(), normalize_paper_id(stem)}
if stem.startswith("paper_"):
stripped = stem[len("paper_") :]
keys.update(
{stripped, stripped.lower(), normalize_paper_id(stripped)},
)
if stem.endswith("_fixed") or stem.endswith("-fixed"):
base = (
stem[: -len("_fixed")]
if stem.endswith("_fixed")
else stem[: -len("-fixed")]
)
if base:
keys.update({base, base.lower(), normalize_paper_id(base)})
match = arxiv_re.match(stem)
if match:
base = match.group("base")
keys.update({base, base.lower(), normalize_paper_id(base)})
match = version_re.match(stem)
if match:
base = match.group("base")
keys.update({base, base.lower(), normalize_paper_id(base)})
pii_match = pii_re.search(stem)
if pii_match:
pii = pii_match.group(1)
keys.update({pii, pii.lower(), normalize_paper_id(pii)})
for key in keys:
if key:
index.setdefault(key, path)
return index
def main() -> None:
parser = argparse.ArgumentParser(
description="Report DefExtra hydration coverage and missing spans.",
)
parser.add_argument(
"--legal-csv",
type=Path,
default=Path("results/paper_results/defextra_legal_tablefix.csv"),
help="Legal CSV used for hydration.",
)
parser.add_argument(
"--legal-report",
type=Path,
default=Path(
"results/paper_results/defextra_legal_tablefix_report.txt",
),
help="Report generated by prepare_defextra_legal.py.",
)
parser.add_argument(
"--hydrated-csv",
type=Path,
default=Path(
"results/paper_results/defextra_hydrated_tablefix_test.csv",
),
help="Hydrated CSV from hydrate_defextra.py.",
)
parser.add_argument(
"--pdf-dir",
type=Path,
default=Path("ManualPDFsGROBID/manual_pdfs/manual_pdfs"),
help="Directory with user PDFs (used to tag recent downloads).",
)
parser.add_argument(
"--recent-days",
type=int,
default=7,
help="How many days count as 'recent' for PDF downloads.",
)
parser.add_argument(
"--output",
type=Path,
default=None,
help="Optional report output path.",
)
args = parser.parse_args()
legal_rows = _load_csv(args.legal_csv)
hydrated_rows = (
_load_csv(args.hydrated_csv) if args.hydrated_csv.exists() else []
)
ref_ids = {
row.get("paper_id", "") for row in legal_rows if row.get("paper_id")
}
hyd_ids = {
row.get("paper_id", "") for row in hydrated_rows if row.get("paper_id")
}
missing_papers = sorted(ref_ids - hyd_ids)
missing_defs, missing_ctxs = _parse_missing_report(args.legal_report)
idx = {
(row.get("paper_id", ""), row.get("concept", "")): row
for row in legal_rows
}
implicit_defs = []
implicit_ctxs = []
for item in missing_defs:
try:
pid, concept = [p.strip() for p in item.split("|", 1)]
except ValueError:
continue
row = idx.get((pid, concept))
if (
row
and (row.get("definition_type") or "").strip().lower()
== "implicit"
):
implicit_defs.append(item)
for item in missing_ctxs:
try:
pid, concept = [p.strip() for p in item.split("|", 1)]
except ValueError:
continue
row = idx.get((pid, concept))
if (
row
and (row.get("definition_type") or "").strip().lower()
== "implicit"
):
implicit_ctxs.append(item)
cutoff_ts = time.time() - (args.recent_days * 86400)
recent_index = _index_recent_pdfs(args.pdf_dir, cutoff_ts)
recent_missing_defs = []
recent_missing_ctxs = []
recent_missing_papers = []
for pid in missing_papers:
if pid in recent_index or normalize_paper_id(pid) in recent_index:
recent_missing_papers.append(pid)
for item in missing_defs:
try:
pid, concept = [p.strip() for p in item.split("|", 1)]
except ValueError:
continue
if pid in recent_index or normalize_paper_id(pid) in recent_index:
recent_missing_defs.append(item)
for item in missing_ctxs:
try:
pid, concept = [p.strip() for p in item.split("|", 1)]
except ValueError:
continue
if pid in recent_index or normalize_paper_id(pid) in recent_index:
recent_missing_ctxs.append(item)
lines = []
lines.append(f"Missing papers (no hydrated rows): {len(missing_papers)}")
for pid in missing_papers:
lines.append(f"- {pid}")
lines.append("")
lines.append(
f"Missing definition spans marked implicit: {len(implicit_defs)}",
)
for item in implicit_defs:
lines.append(f"- {item}")
lines.append("")
lines.append(
f"Missing context spans marked implicit: {len(implicit_ctxs)}",
)
for item in implicit_ctxs:
lines.append(f"- {item}")
lines.append("")
lines.append(
f"Missing papers with recent PDFs (<= {args.recent_days} days): "
f"{len(recent_missing_papers)}",
)
for pid in recent_missing_papers:
lines.append(f"- {pid}")
lines.append("")
lines.append(
f"Missing definition spans with recent PDFs (<= {args.recent_days} days): "
f"{len(recent_missing_defs)}",
)
for item in recent_missing_defs:
lines.append(f"- {item}")
lines.append("")
lines.append(
f"Missing context spans with recent PDFs (<= {args.recent_days} days): "
f"{len(recent_missing_ctxs)}",
)
for item in recent_missing_ctxs:
lines.append(f"- {item}")
lines.append("")
output = "\n".join(lines) + "\n"
if args.output is not None:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(output, encoding="utf-8")
print(f"Wrote report to {args.output}")
else:
print(output)
if __name__ == "__main__":
main()
|