Repository navigation
Expand file tree
/
Copy pathpapers.py
More file actions
executable file
·1499 lines (1267 loc) · 45.4 KB
/
Copy pathpapers.py
File metadata and controls
executable file
·1499 lines (1267 loc) · 45.4 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Import, classify, save, and search research paper PDFs."""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import os
import re
import shutil
import sqlite3
import sys
import tempfile
import textwrap
import unicodedata
import urllib.parse
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Iterable
SCRIPT_PATH = Path(__file__).resolve()
ROOT = SCRIPT_PATH.parent
def reexec_with_local_venv() -> None:
venv_python = ROOT / ".venv" / "bin" / "python"
venv_root = ROOT / ".venv"
if not venv_python.exists():
return
if Path(sys.prefix).resolve() == venv_root.resolve():
return
os.execv(str(venv_python), [str(venv_python), str(SCRIPT_PATH), *sys.argv[1:]])
reexec_with_local_venv()
try:
import requests
from bs4 import BeautifulSoup
except ImportError as exc: # pragma: no cover - exercised before deps exist
reexec_with_local_venv()
raise SystemExit(
"Missing dependencies. Create the local environment and install them with:\n"
" python3 -m venv .venv\n"
" .venv/bin/python -m pip install -r requirements.txt"
) from exc
try:
import pymupdf
except ImportError: # pragma: no cover - compatibility with older PyMuPDF imports
try:
import fitz as pymupdf
except ImportError as exc:
reexec_with_local_venv()
raise SystemExit(
"Missing PyMuPDF. Install dependencies inside the local environment with:\n"
" .venv/bin/python -m pip install -r requirements.txt"
) from exc
DB_PATH = ROOT / ".paper_index.sqlite"
DEFAULT_CATEGORIES = ("archaeology", "biology", "machine-learning")
REQUEST_TIMEOUT = (12, 90)
MAX_EXTRACTED_CHARS = 450_000
MAX_EXTRACTED_PAGES = 100
HEADERS = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/125.0 Safari/537.36 papers.py/1.0"
),
"Accept": "text/html,application/pdf,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
}
DEFAULT_KEYWORDS = {
"archaeology": [
"archaeology",
"archaeological",
"ancient dna",
"ancient genome",
"ancient genomes",
"ancient human",
"paleogenomic",
"palaeogenomic",
"radiocarbon",
"excavation",
"artifact",
"artefact",
"neolithic",
"paleolithic",
"palaeolithic",
"bronze age",
"iron age",
"hunter-gatherer",
"burial",
"osteological",
"isotopes",
"ceramics",
"aDNA",
],
"biology": [
"biology",
"biological",
"genetics",
"genome",
"genomic",
"genomes",
"dna",
"rna",
"protein",
"cell",
"cells",
"disease",
"evolution",
"natural selection",
"phenotype",
"microbiome",
"species",
"population genetics",
"molecular",
"immunology",
"metabolism",
"transcriptome",
],
"machine-learning": [
"machine learning",
"deep learning",
"neural network",
"neural networks",
"transformer",
"transformers",
"attention",
"gradient",
"model training",
"dataset",
"benchmark",
"language model",
"large language model",
"computer vision",
"reinforcement learning",
"classification accuracy",
"backpropagation",
"embedding",
"embeddings",
],
}
class PaperError(Exception):
"""Base error for user-facing failures."""
class AntiBotError(PaperError):
"""Raised when a site blocks scripted access with a bot challenge."""
class DownloadError(PaperError):
"""Raised when a PDF or page cannot be downloaded."""
@dataclass
class PaperMetadata:
title: str = ""
authors: list[str] = field(default_factory=list)
year: str = ""
abstract: str = ""
doi: str = ""
provider: str = ""
provider_id: str = ""
source_url: str = ""
pdf_url: str = ""
@dataclass
class SourceResolution:
source: str
provider: str = ""
provider_id: str = ""
source_url: str = ""
pdf_url: str = ""
local_path: Path | None = None
web_metadata: PaperMetadata = field(default_factory=PaperMetadata)
web_blocked: bool = False
def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
if not argv or argv[0] in {"-h", "--help"}:
print_main_help()
return 0
if argv[0] == "search":
return run_search(argv[1:])
if argv[0] == "all":
return run_all(argv[1:])
if argv[0] == "import":
argv = argv[1:]
return run_import(argv)
def print_main_help() -> None:
print(
textwrap.dedent(
"""\
usage:
./papers.py <url-or-local-pdf> [--category CATEGORY] [--dry-run]
./papers.py import <url-or-local-pdf> [--category CATEGORY] [--dry-run]
./papers.py search "query" [--limit N]
./papers.py all
Supported inputs:
direct PDF URL, local PDF path, arXiv, bioRxiv, and science.org links.
"""
)
)
def run_import(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog="./papers.py")
parser.add_argument("source", help="PDF URL, local PDF path, or supported paper page URL")
parser.add_argument("--category", help="Force a category and create it if needed")
parser.add_argument("--dry-run", action="store_true", help="Analyze but do not save or index")
args = parser.parse_args(argv)
if not args.dry_run:
ensure_project_dirs()
con = connect_db()
ensure_schema(con)
else:
con = None
try:
with tempfile.TemporaryDirectory(prefix="papers-") as tmp:
temp_dir = Path(tmp)
resolution = resolve_source(args.source, temp_dir)
pdf_path, final_pdf_url = obtain_pdf(resolution, temp_dir)
metadata, extracted_text = analyze_pdf(pdf_path, resolution, final_pdf_url)
profiles = load_category_profiles(con)
category, score_report, was_prompted = choose_category(
metadata,
extracted_text,
profiles,
con,
override=args.category,
dry_run=args.dry_run,
)
destination = build_destination_path(category, metadata)
file_hash = sha256_file(pdf_path)
if args.dry_run:
print_import_summary(
metadata=metadata,
category=category,
saved_path=destination,
score_report=score_report,
was_prompted=was_prompted,
dry_run=True,
)
return 0
existing = find_existing_by_hash(con, file_hash)
if existing:
print(f"Already imported: {existing['saved_path']}")
print(f"Category: {existing['category']}")
return 0
saved_path = save_pdf(pdf_path, destination)
index_paper(con, metadata, extracted_text, category, saved_path, file_hash)
con.commit()
print_import_summary(
metadata=metadata,
category=category,
saved_path=saved_path,
score_report=score_report,
was_prompted=was_prompted,
dry_run=False,
)
return 0
except KeyboardInterrupt:
print("\nCanceled.", file=sys.stderr)
return 130
except PaperError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
finally:
if con is not None:
con.close()
def run_search(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog="./papers.py search")
parser.add_argument("query", help="Search query")
parser.add_argument("--limit", type=int, default=10, help="Maximum results to show")
args = parser.parse_args(argv)
if not DB_PATH.exists():
print("No index exists yet. Import a paper first.")
return 0
con = connect_db()
try:
rows = search_index(con, args.query, args.limit)
finally:
con.close()
print_found_count(len(rows))
if not rows:
return 0
blocks = [format_result_block(row, index, len(rows)) for index, row in enumerate(rows, start=1)]
print("\n\n".join(blocks))
return 0
def run_all(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog="./papers.py all")
parser.add_argument("--page-size", type=int, default=25, help="Number of files to show per page")
args = parser.parse_args(argv)
page_size = max(args.page_size, 1)
if not DB_PATH.exists():
print_found_count(0)
return 0
con = connect_db()
try:
rows = list_all_papers(con)
finally:
con.close()
total = len(rows)
print_found_count(total)
if not rows:
return 0
start = 0
while start < total:
end = min(start + page_size, total)
page = rows[start:end]
blocks = [
format_result_block(row, index, total)
for index, row in enumerate(page, start=start + 1)
]
print("\n\n".join(blocks))
start = end
if start >= total:
break
if not sys.stdin.isatty():
print(f"\nShowing {start}/{total}. Re-run interactively to page through more results.")
break
next_count = min(page_size, total - start)
answer = input(f"\nShow next {next_count} results? [y/N]: ").strip().lower()
if answer not in {"y", "yes"}:
break
print()
return 0
def print_found_count(count: int) -> None:
result_word = "Result" if count == 1 else "Results"
print(f"\nFound {count} {result_word}\n")
def format_result_block(row: sqlite3.Row, index: int, total: int) -> str:
title = row["title"] or "(untitled)"
authors = format_authors(json.loads(row["authors"] or "[]"))
source_bits = [bit for bit in (row["provider"], row["provider_id"], row["doi"]) if bit]
source = " | ".join(source_bits)
block = [f"Result {index}/{total}:", f"{row['saved_path']}", f" {title}"]
if authors:
block.append(f" {authors}")
if source:
block.append(f" {source}")
block.append(f" category: {row['category']}")
return "\n".join(block)
def ensure_project_dirs() -> None:
for category in DEFAULT_CATEGORIES:
(ROOT / category).mkdir(exist_ok=True)
def connect_db() -> sqlite3.Connection:
con = sqlite3.connect(DB_PATH)
con.row_factory = sqlite3.Row
return con
def ensure_schema(con: sqlite3.Connection) -> None:
con.executescript(
"""
create table if not exists papers (
id integer primary key,
title text,
authors text,
year text,
abstract text,
doi text,
provider text,
provider_id text,
source_url text,
pdf_url text,
category text not null,
saved_path text not null unique,
file_sha256 text not null,
imported_at text not null
);
create table if not exists category_keywords (
category text primary key,
keywords text not null
);
create virtual table if not exists papers_fts using fts5(
title,
authors,
abstract,
body_text,
doi,
provider,
provider_id,
category,
saved_path
);
"""
)
for category, keywords in DEFAULT_KEYWORDS.items():
con.execute(
"""
insert into category_keywords(category, keywords)
values(?, ?)
on conflict(category) do nothing
""",
(category, json.dumps(keywords)),
)
con.commit()
def resolve_source(source: str, temp_dir: Path) -> SourceResolution:
source_path = Path(source).expanduser()
if source_path.exists():
if not source_path.is_file():
raise PaperError(f"Local path is not a file: {source_path}")
if source_path.suffix.lower() != ".pdf":
raise PaperError(f"Local path does not look like a PDF: {source_path}")
validate_pdf_file(source_path)
return SourceResolution(source=source, local_path=source_path, source_url=str(source_path))
if not is_url(source):
raise PaperError(f"Input is neither an existing file nor an HTTP URL: {source}")
parsed = urllib.parse.urlparse(source)
host = parsed.netloc.lower()
path = urllib.parse.unquote(parsed.path)
if "arxiv.org" in host:
return resolve_arxiv(source)
if "biorxiv.org" in host:
return resolve_biorxiv(source)
if host.endswith("science.org") or host.endswith(".science.org"):
return resolve_science(source)
github_resolution = resolve_github_pdf(source)
if github_resolution is not None:
return github_resolution
if path.lower().endswith(".pdf"):
return SourceResolution(source=source, source_url=source, pdf_url=source)
metadata = PaperMetadata(source_url=source)
try:
html = fetch_html(source)
metadata = parse_web_metadata(html, source)
except AntiBotError:
raise
except DownloadError:
pass
if metadata.pdf_url:
return SourceResolution(
source=source,
source_url=source,
pdf_url=metadata.pdf_url,
web_metadata=metadata,
)
raise PaperError(
"Could not find a PDF for this page. Provide a direct PDF URL or a local PDF path."
)
def resolve_github_pdf(url: str) -> SourceResolution | None:
parsed = urllib.parse.urlparse(url)
host = parsed.netloc.lower()
if host not in {"github.com", "www.github.com"}:
return None
path = urllib.parse.unquote(parsed.path).strip("/")
parts = [part for part in path.split("/") if part]
if len(parts) < 5 or parts[2] != "blob":
return None
owner, repo = parts[0], parts[1]
file_parts = parts[3:]
if not file_parts[-1].lower().endswith(".pdf"):
return None
raw_path = "/".join(urllib.parse.quote(part, safe="") for part in (owner, repo, *file_parts))
pdf_url = f"https://raw.githubusercontent.com/{raw_path}"
metadata = PaperMetadata(
provider="github",
provider_id=f"{owner}/{repo}",
source_url=url,
pdf_url=pdf_url,
)
return SourceResolution(
source=url,
provider="github",
provider_id=metadata.provider_id,
source_url=url,
pdf_url=pdf_url,
web_metadata=metadata,
)
def resolve_arxiv(url: str) -> SourceResolution:
parsed = urllib.parse.urlparse(url)
path = urllib.parse.unquote(parsed.path).strip("/")
arxiv_id = ""
if path.startswith("abs/"):
arxiv_id = path.removeprefix("abs/").removesuffix(".pdf")
elif path.startswith("pdf/"):
arxiv_id = path.removeprefix("pdf/").removesuffix(".pdf")
elif path:
arxiv_id = path.rsplit("/", 1)[-1].removesuffix(".pdf")
if not arxiv_id:
raise PaperError(f"Could not parse arXiv ID from URL: {url}")
source_url = f"https://arxiv.org/abs/{arxiv_id}"
pdf_url = f"https://arxiv.org/pdf/{arxiv_id}"
metadata = PaperMetadata(provider="arxiv", provider_id=arxiv_id, source_url=source_url, pdf_url=pdf_url)
try:
html = fetch_html(source_url)
metadata = merge_metadata(metadata, parse_web_metadata(html, source_url))
except PaperError:
pass
if not metadata.title or not metadata.abstract:
metadata = merge_metadata(metadata, fetch_arxiv_api_metadata(arxiv_id))
metadata.provider = "arxiv"
metadata.provider_id = arxiv_id
metadata.source_url = source_url
metadata.pdf_url = metadata.pdf_url or pdf_url
return SourceResolution(
source=url,
provider="arxiv",
provider_id=arxiv_id,
source_url=source_url,
pdf_url=metadata.pdf_url,
web_metadata=metadata,
)
def resolve_biorxiv(url: str) -> SourceResolution:
parsed = urllib.parse.urlparse(url)
path = urllib.parse.unquote(parsed.path)
provider_id = ""
match = re.search(r"/content/(.+?)(?:\.full\.pdf)?/?$", path)
if match:
provider_id = match.group(1).strip("/")
else:
provider_id = path.strip("/")
source_url = url
if ".full.pdf" in source_url:
source_url = source_url.replace(".full.pdf", "")
pdf_url = source_url.rstrip("/") + ".full.pdf"
metadata = PaperMetadata(
provider="biorxiv",
provider_id=provider_id,
source_url=source_url,
pdf_url=pdf_url,
)
if path.endswith(".full.pdf"):
return SourceResolution(
source=url,
provider="biorxiv",
provider_id=provider_id,
source_url=source_url,
pdf_url=pdf_url,
web_metadata=metadata,
)
try:
html = fetch_html(source_url)
metadata = merge_metadata(metadata, parse_web_metadata(html, source_url))
except AntiBotError:
return SourceResolution(
source=url,
provider="biorxiv",
provider_id=provider_id,
source_url=source_url,
pdf_url=pdf_url,
web_metadata=metadata,
web_blocked=True,
)
metadata.provider = "biorxiv"
metadata.provider_id = provider_id or metadata.provider_id
metadata.source_url = source_url
metadata.pdf_url = metadata.pdf_url or pdf_url
return SourceResolution(
source=url,
provider="biorxiv",
provider_id=metadata.provider_id,
source_url=source_url,
pdf_url=metadata.pdf_url,
web_metadata=metadata,
)
def resolve_science(url: str) -> SourceResolution:
parsed = urllib.parse.urlparse(url)
path = urllib.parse.unquote(parsed.path)
doi = ""
match = re.search(r"/doi/(?:pdf/)?(.+)$", path)
if match:
doi = match.group(1).strip("/")
if not doi:
raise PaperError(f"Could not parse Science DOI from URL: {url}")
source_url = f"https://www.science.org/doi/{doi}"
pdf_url = f"https://www.science.org/doi/pdf/{doi}"
metadata = PaperMetadata(provider="science", provider_id=doi, doi=doi, source_url=source_url, pdf_url=pdf_url)
if "/doi/pdf/" in path:
return SourceResolution(
source=url,
provider="science",
provider_id=doi,
source_url=source_url,
pdf_url=pdf_url,
web_metadata=metadata,
)
try:
html = fetch_html(source_url)
metadata = merge_metadata(metadata, parse_web_metadata(html, source_url))
except AntiBotError:
return SourceResolution(
source=url,
provider="science",
provider_id=doi,
source_url=source_url,
pdf_url=pdf_url,
web_metadata=metadata,
web_blocked=True,
)
metadata.provider = "science"
metadata.provider_id = doi
metadata.doi = metadata.doi or doi
metadata.source_url = source_url
metadata.pdf_url = metadata.pdf_url or pdf_url
return SourceResolution(
source=url,
provider="science",
provider_id=doi,
source_url=source_url,
pdf_url=metadata.pdf_url,
web_metadata=metadata,
)
def obtain_pdf(resolution: SourceResolution, temp_dir: Path) -> tuple[Path, str]:
if resolution.local_path is not None:
return resolution.local_path, resolution.pdf_url
if resolution.web_blocked:
return prompt_for_pdf_after_block(resolution, temp_dir)
if not resolution.pdf_url:
raise PaperError("No PDF URL was found for this input.")
target = temp_dir / "download.pdf"
try:
download_pdf(resolution.pdf_url, target)
return target, resolution.pdf_url
except AntiBotError:
return prompt_for_pdf_after_block(resolution, temp_dir)
def prompt_for_pdf_after_block(resolution: SourceResolution, temp_dir: Path) -> tuple[Path, str]:
if not sys.stdin.isatty():
raise AntiBotError(
"Anti-bot challenge detected. Re-run interactively to provide a direct PDF URL "
"or a local path to a manually downloaded PDF."
)
print("Anti-bot challenge detected for this source.")
direct_url = input(
"Please enter a direct PDF URL, or press Enter to provide a local PDF path: "
).strip()
if direct_url:
target = temp_dir / "manual-url.pdf"
try:
download_pdf(direct_url, target)
return target, direct_url
except AntiBotError:
print("That PDF URL also hit an anti-bot challenge.")
except PaperError as exc:
print(f"That PDF URL could not be used: {exc}")
while True:
local = input("Path to manually downloaded PDF: ").strip()
if not local:
raise PaperError("No PDF path provided.")
path = Path(local).expanduser()
if path.exists() and path.is_file():
validate_pdf_file(path)
return path, direct_url
print("That path does not exist or is not a file.")
def fetch_html(url: str) -> str:
try:
response = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
except requests.RequestException as exc:
raise DownloadError(f"Could not fetch page {url}: {exc}") from exc
body = response.content[:8192]
if is_anti_bot_response(response, body):
raise AntiBotError(f"Anti-bot challenge detected at {url}")
if response.status_code >= 400:
raise DownloadError(f"Could not fetch page {url}: HTTP {response.status_code}")
return response.text
def download_pdf(url: str, target: Path) -> None:
try:
with requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT, stream=True) as response:
first_chunks: list[bytes] = []
for chunk in response.iter_content(chunk_size=8192):
if chunk:
first_chunks.append(chunk)
break
first = b"".join(first_chunks)
if is_anti_bot_response(response, first):
raise AntiBotError(f"Anti-bot challenge detected while downloading {url}")
if response.status_code >= 400:
raise DownloadError(f"Could not download PDF {url}: HTTP {response.status_code}")
if not first.startswith(b"%PDF"):
content_type = response.headers.get("content-type", "")
snippet = first[:120].decode("utf-8", errors="ignore").replace("\n", " ")
raise DownloadError(
f"URL did not return a PDF. content-type={content_type!r} snippet={snippet!r}"
)
with target.open("wb") as fh:
fh.write(first)
for chunk in response.iter_content(chunk_size=1024 * 256):
if chunk:
fh.write(chunk)
except requests.RequestException as exc:
raise DownloadError(f"Could not download PDF {url}: {exc}") from exc
validate_pdf_file(target)
def is_anti_bot_response(response: requests.Response, body: bytes = b"") -> bool:
headers = {key.lower(): value.lower() for key, value in response.headers.items()}
server = headers.get("server", "")
if headers.get("cf-mitigated") == "challenge":
return True
if "cloudflare" in server and response.status_code in {403, 429, 503}:
return True
text = body[:8192].decode("utf-8", errors="ignore").lower()
challenge_markers = (
"cf-challenge",
"cloudflare",
"just a moment",
"attention required",
"captcha",
"challenge-platform",
)
return response.status_code in {403, 429, 503} and any(marker in text for marker in challenge_markers)
def validate_pdf_file(path: Path) -> None:
with path.open("rb") as fh:
if fh.read(5) != b"%PDF-":
raise PaperError(f"File is not a valid PDF: {path}")
def parse_web_metadata(html: str, url: str) -> PaperMetadata:
soup = BeautifulSoup(html, "html.parser")
meta: dict[str, list[str]] = {}
for tag in soup.find_all("meta"):
key = tag.get("name") or tag.get("property")
content = tag.get("content")
if not key or not content:
continue
meta.setdefault(key.lower(), []).append(clean_spaces(content))
def first(*keys: str) -> str:
for key in keys:
values = meta.get(key.lower())
if values:
return values[0]
return ""
authors = meta.get("citation_author", []) or meta.get("dc.creator", [])
pdf_url = first("citation_pdf_url")
if pdf_url:
pdf_url = urllib.parse.urljoin(url, pdf_url)
title = first("citation_title", "dc.title", "og:title", "twitter:title")
abstract = first("citation_abstract", "dc.description", "description", "og:description")
year = parse_year(first("citation_publication_date", "citation_online_date", "article:published_time", "dc.date"))
doi = first("citation_doi", "dc.identifier")
doi = doi.removeprefix("doi:").strip()
return PaperMetadata(
title=title,
authors=dedupe(authors),
year=year,
abstract=abstract,
doi=doi,
source_url=url,
pdf_url=pdf_url,
)
def fetch_arxiv_api_metadata(arxiv_id: str) -> PaperMetadata:
clean_id = re.sub(r"v\d+$", "", arxiv_id)
api_url = "https://export.arxiv.org/api/query?id_list=" + urllib.parse.quote(clean_id)
try:
response = requests.get(api_url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
except requests.RequestException:
return PaperMetadata()
if response.status_code >= 400:
return PaperMetadata()
try:
root = ET.fromstring(response.content)
except ET.ParseError:
return PaperMetadata()
ns = {"atom": "http://www.w3.org/2005/Atom"}
entry = root.find("atom:entry", ns)
if entry is None:
return PaperMetadata()
def atom_text(name: str) -> str:
node = entry.find(f"atom:{name}", ns)
return clean_spaces(node.text or "") if node is not None else ""
authors = [
clean_spaces(node.text or "")
for node in entry.findall("atom:author/atom:name", ns)
if clean_spaces(node.text or "")
]
return PaperMetadata(
title=atom_text("title"),
authors=authors,
abstract=atom_text("summary"),
year=parse_year(atom_text("published") or atom_text("updated")),
provider="arxiv",
provider_id=arxiv_id,
source_url=f"https://arxiv.org/abs/{arxiv_id}",
pdf_url=f"https://arxiv.org/pdf/{arxiv_id}",
)
def analyze_pdf(
pdf_path: Path,
resolution: SourceResolution,
final_pdf_url: str,
) -> tuple[PaperMetadata, str]:
pdf_metadata, extracted_text = extract_pdf(pdf_path)
metadata = merge_metadata(PaperMetadata(), resolution.web_metadata)
metadata.provider = metadata.provider or resolution.provider
metadata.provider_id = metadata.provider_id or resolution.provider_id
metadata.source_url = metadata.source_url or resolution.source_url or resolution.source
metadata.pdf_url = final_pdf_url or metadata.pdf_url or resolution.pdf_url
if not useful_title(metadata.title):
metadata.title = clean_spaces(pdf_metadata.get("title", ""))
if not useful_title(metadata.title):
metadata.title = guess_title_from_text(extracted_text)
if not metadata.authors:
metadata.authors = split_authors(pdf_metadata.get("author", ""))
if not metadata.year:
metadata.year = parse_year(pdf_metadata.get("creationDate", "") or pdf_metadata.get("modDate", ""))
if not metadata.year:
metadata.year = parse_year(extracted_text[:8000])
if not metadata.abstract:
metadata.abstract = extract_abstract(extracted_text)
if not metadata.title:
metadata.title = Path(pdf_path).stem
return metadata, extracted_text
def extract_pdf(pdf_path: Path) -> tuple[dict[str, str], str]:
try:
doc = pymupdf.open(pdf_path)
except Exception as exc:
raise PaperError(f"Could not open PDF: {pdf_path}: {exc}") from exc
try:
if getattr(doc, "needs_pass", False):
raise PaperError("Encrypted PDFs are not supported.")
metadata = dict(doc.metadata or {})
chunks: list[str] = []
total = 0
page_count = min(len(doc), MAX_EXTRACTED_PAGES)
for page_index in range(page_count):
page = doc.load_page(page_index)
text = page.get_text("text", sort=True) or ""
if not text:
continue
remaining = MAX_EXTRACTED_CHARS - total
if remaining <= 0:
break
chunks.append(text[:remaining])
total += min(len(text), remaining)
extracted = "\n".join(chunks)
finally:
doc.close()
if len(extracted.strip()) < 100:
raise PaperError(
"Could not extract enough text from this PDF. It may be scanned; OCR is not included in v1."
)
return metadata, extracted
def merge_metadata(base: PaperMetadata, incoming: PaperMetadata) -> PaperMetadata:
if incoming.title and not base.title:
base.title = incoming.title
if incoming.authors and not base.authors:
base.authors = incoming.authors
if incoming.year and not base.year:
base.year = incoming.year
if incoming.abstract and not base.abstract:
base.abstract = incoming.abstract
if incoming.doi and not base.doi:
base.doi = incoming.doi
if incoming.provider and not base.provider:
base.provider = incoming.provider
if incoming.provider_id and not base.provider_id:
base.provider_id = incoming.provider_id
if incoming.source_url and not base.source_url:
base.source_url = incoming.source_url
if incoming.pdf_url and not base.pdf_url:
base.pdf_url = incoming.pdf_url
return base
def load_category_profiles(con: sqlite3.Connection | None) -> dict[str, list[str]]:
profiles = {category: list(keywords) for category, keywords in DEFAULT_KEYWORDS.items()}
for directory in visible_category_dirs():
profiles.setdefault(directory, [])
if con is None:
return profiles
for row in con.execute("select category, keywords from category_keywords"):
try:
keywords = json.loads(row["keywords"])
except json.JSONDecodeError:
keywords = []
profiles.setdefault(row["category"], [])
profiles[row["category"]] = dedupe(profiles[row["category"]] + list(keywords))
return profiles
def visible_category_dirs() -> list[str]: