-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsi_merge.py
More file actions
1530 lines (1291 loc) · 57.8 KB
/
Copy pathsi_merge.py
File metadata and controls
1530 lines (1291 loc) · 57.8 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
"""
SI Merge — Automatically find, download, and merge Supplementary Information
into journal article PDFs with cross-reference links.
Usage (CLI):
python si_merge.py <article.pdf> [-o output.pdf] [--doi DOI]
Usage (library):
from si_merge import run_merge
result = run_merge(pdf_bytes, on_progress=my_callback)
"""
import argparse
import io
import os
import re
import sys
import tempfile
import urllib.parse
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
import fitz # PyMuPDF
fitz.TOOLS.mupdf_display_errors(False)
import requests
from bs4 import BeautifulSoup
USER_AGENT = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
CROSSREF_UA = "SI-Merger/1.0 (mailto:si-merger@example.com)"
ProgressCallback = Callable[[int, str, str], None] # (step, status, detail)
def _noop_progress(step: int, status: str, detail: str = "") -> None:
pass
# ---------------------------------------------------------------------------
# HTTP client — curl_cffi (bypasses Cloudflare) with requests fallback
# ---------------------------------------------------------------------------
_session: dict[str, object] = {}
_IMPERSONATE_PROFILES = ("chrome", "safari15_5")
def _get_session(profile: str = "chrome"):
"""Lazily create a persistent session for cookie/referer handling."""
if profile in _session:
return _session[profile]
try:
from curl_cffi import requests as cffi_requests
sess = cffi_requests.Session()
sess._impersonate = profile
_session[profile] = sess
return sess
except ImportError:
sess = requests.Session()
sess.headers.update({"User-Agent": USER_AGENT})
_session[profile] = sess
return sess
def _http_get(url: str, *, timeout: int = 30, allow_redirects: bool = True,
headers: dict | None = None, referer: str | None = None) -> requests.Response:
"""
GET with browser-like TLS fingerprint via curl_cffi.
Uses a persistent session to carry cookies across requests (needed for Wiley etc.).
When the primary profile (Chrome) is blocked (403), automatically retries with
alternative profiles (Safari) before giving up.
Falls back to plain requests if curl_cffi is unavailable.
"""
hdrs = dict(headers or {})
if referer:
hdrs["Referer"] = referer
try:
from curl_cffi import requests as cffi_requests
last_exc = None
for profile in _IMPERSONATE_PROFILES:
session = _get_session(profile)
if not isinstance(session, cffi_requests.Session):
break
try:
resp = session.get(
url, impersonate=profile, timeout=timeout,
allow_redirects=allow_redirects, headers=hdrs or None,
)
if resp.status_code != 403 or profile == _IMPERSONATE_PROFILES[-1]:
return resp
except Exception as e:
last_exc = e
if profile == _IMPERSONATE_PROFILES[-1]:
raise
else:
if last_exc:
raise last_exc
return resp # type: ignore[possibly-undefined]
except ImportError:
pass
session = _get_session("chrome")
if hdrs:
session.headers.update(hdrs)
return session.get(url, timeout=timeout, allow_redirects=allow_redirects)
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@dataclass
class SIFile:
url: str
label: str # e.g. "Supplementary Information", "Peer Review File"
local_path: str = ""
@dataclass
class SIReference:
"""A reference to SI content found in the main article text."""
text: str # matched text, e.g. "Supplementary Fig. S1"
page_idx: int # 0-based page in original article
rect: fitz.Rect | None = None
target_key: str = "" # normalized key, e.g. "figure_1"
@dataclass
class SIAnchor:
"""A heading/caption in the SI document that can be linked to."""
text: str
page_idx: int # 0-based page in SI document
rect: fitz.Rect | None = None
key: str = "" # normalized key, e.g. "figure_1"
# ---------------------------------------------------------------------------
# DOI Extraction
# ---------------------------------------------------------------------------
DOI_RE = re.compile(r'10\.\d{4,9}/[^\s,;\"\'>\]}{)]+', re.IGNORECASE)
# Matches DOIs split across lines: "10.1126/\nsciadv.abj5505" or "10.1126/ sciadv.abj5505"
DOI_SPLIT_RE = re.compile(r'(10\.\d{4,9})/\s+(\S+)', re.IGNORECASE)
def _clean_doi(raw: str) -> str:
"""Strip trailing junk that is not part of a DOI."""
doi = raw.split("&")[0] # remove URL query params like &ref=pdf
doi = doi.split("#")[0] # remove URL fragments
return doi.rstrip(".),")
def extract_doi_from_metadata(doc: fitz.Document) -> str | None:
"""Try to extract DOI from PDF metadata fields."""
meta = doc.metadata or {}
for key in ("subject", "title", "keywords", "creator", "producer"):
val = meta.get(key, "") or ""
m = DOI_RE.search(val)
if m:
return _clean_doi(m.group(0))
return None
def extract_doi_from_links(doc: fitz.Document) -> str | None:
"""Try to extract DOI from PDF hyperlink annotations (e.g. doi.org links)."""
for i in range(min(5, len(doc))):
for link in doc[i].get_links():
uri = link.get("uri", "")
if uri:
m = DOI_RE.search(uri)
if m:
return _clean_doi(m.group(0))
return None
def extract_doi_from_text(doc: fitz.Document, max_pages: int = 5) -> str | None:
"""Try to extract DOI from PDF text content.
Searches the first `max_pages` pages AND the last 2 pages (many publishers
put the DOI at the end of the article). Also handles DOIs split across
line breaks such as '10.1126/\\nsciadv.abj5505'.
"""
pages_to_check: list[int] = []
pages_to_check.extend(range(min(max_pages, len(doc))))
for offset in (1, 2):
idx = len(doc) - offset
if idx >= 0 and idx not in pages_to_check:
pages_to_check.append(idx)
for i in pages_to_check:
text = doc[i].get_text()
if not text.strip():
continue
m = DOI_RE.search(text)
if m:
return _clean_doi(m.group(0))
m2 = DOI_SPLIT_RE.search(text)
if m2:
return _clean_doi(f"{m2.group(1)}/{m2.group(2)}")
return None
def extract_doi(doc: fitz.Document) -> str | None:
return (extract_doi_from_metadata(doc)
or extract_doi_from_links(doc)
or extract_doi_from_text(doc))
# ---------------------------------------------------------------------------
# Article URL Resolution
# ---------------------------------------------------------------------------
def resolve_article_url(doi: str) -> str | None:
"""Resolve a DOI to the publisher landing page URL."""
try:
resp = _http_get(f"https://doi.org/{doi}", timeout=15, allow_redirects=True)
if resp.status_code == 200:
return resp.url
# Some publishers block bots but the redirect still provides the URL
if resp.url and resp.url != f"https://doi.org/{doi}":
return resp.url
except Exception:
pass
# Fallback: construct URL from doi.org redirect without following to final destination
try:
resp = requests.get(
f"https://doi.org/{doi}",
headers={"User-Agent": USER_AGENT},
allow_redirects=False,
timeout=10,
)
location = resp.headers.get("Location")
if location:
return location
except Exception:
pass
return None
def get_article_pdf_url(doi: str) -> str | None:
"""Get the direct PDF URL from CrossRef metadata."""
try:
resp = requests.get(
f"https://api.crossref.org/works/{doi}",
headers={"User-Agent": CROSSREF_UA},
timeout=15,
)
if resp.status_code == 200:
data = resp.json().get("message", {})
for link in data.get("link", []):
if link.get("content-type") == "application/pdf":
return link["URL"]
except requests.RequestException:
pass
return None
# ---------------------------------------------------------------------------
# Article PDF Download (for browser extension / DOI-based merge)
# ---------------------------------------------------------------------------
_PDF_URL_PATTERNS: dict[str, str] = {
"nature.com": "{article_url}.pdf",
"springer.com": "{article_url}.pdf",
"pubs.acs.org": "https://pubs.acs.org/doi/pdf/{doi}",
"onlinelibrary.wiley.com": "https://onlinelibrary.wiley.com/doi/pdfdirect/{doi}",
"science.org": "https://www.science.org/doi/pdf/{doi}",
"pnas.org": "https://www.pnas.org/doi/pdf/{doi}",
}
def download_article_pdf(
doi: str,
work_dir: str,
on_progress: ProgressCallback = _noop_progress,
) -> tuple[str, str]:
"""
Download the main article PDF given a DOI.
Returns (pdf_path, article_url).
Raises RuntimeError if the PDF cannot be obtained.
"""
on_progress(1, "started", f"Resolving DOI: {doi}")
article_url = resolve_article_url(doi)
if not article_url:
raise RuntimeError(f"Could not resolve DOI {doi} to an article URL.")
on_progress(1, "searching", f"Article: {article_url}")
pdf_url = None
# Strategy 1: citation_pdf_url meta tag
try:
resp = _http_get(article_url, timeout=20)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, "html.parser")
meta = soup.find("meta", attrs={"name": "citation_pdf_url"})
if meta and meta.get("content"):
pdf_url = meta["content"]
except Exception:
pass
# Strategy 2: publisher-specific URL patterns
if not pdf_url:
domain = urllib.parse.urlparse(article_url).netloc
for pub_domain, pattern in _PDF_URL_PATTERNS.items():
if pub_domain in domain:
pdf_url = pattern.format(article_url=article_url.rstrip("/"), doi=doi)
break
# Strategy 3: CrossRef link
if not pdf_url:
pdf_url = get_article_pdf_url(doi)
if not pdf_url:
raise RuntimeError(
f"Could not find a PDF download link for DOI {doi}. "
"The article may require institutional access."
)
on_progress(1, "downloading", f"Downloading article PDF...")
try:
resp = _http_get(pdf_url, timeout=60, allow_redirects=True)
except Exception as e:
raise RuntimeError(f"Failed to download article PDF: {e}")
if resp.status_code == 403:
raise RuntimeError(
"Publisher blocked the PDF download (HTTP 403). "
"The article likely requires institutional access. "
"Please download the PDF manually and use the web app."
)
if resp.status_code != 200:
raise RuntimeError(f"PDF download failed with status {resp.status_code}.")
content = resp.content
if not content[:5].startswith(b"%PDF"):
ctype = resp.headers.get("content-type", "")
if "html" in ctype.lower():
raise RuntimeError(
"Received an HTML page instead of a PDF. "
"The article likely requires institutional access."
)
pdf_path = os.path.join(work_dir, "article.pdf")
with open(pdf_path, "wb") as f:
f.write(content)
on_progress(1, "done", f"Article PDF downloaded ({len(content) // 1024} KB)")
return pdf_path, article_url
# ---------------------------------------------------------------------------
# SI Discovery — publisher-specific scrapers
# ---------------------------------------------------------------------------
def _scrape_springer_nature(soup: BeautifulSoup, base_url: str) -> list[SIFile]:
"""Scrape Springer Nature / Nature Communications SI links."""
results = []
si_section = soup.find("section", {"data-title": "Supplementary information"})
if not si_section:
for s in soup.find_all("section"):
heading = s.find(["h2", "h3"])
if heading and "supplementary" in heading.get_text().lower():
si_section = s
break
if si_section:
for link in si_section.find_all("a", href=True):
href = link["href"]
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
label = link.get_text(strip=True)
if any(ext in href.lower() for ext in [".pdf", ".doc", ".xlsx", ".zip"]):
results.append(SIFile(url=href, label=label))
return results
def _scrape_acs(soup: BeautifulSoup, base_url: str) -> list[SIFile]:
"""Scrape ACS Publications SI links."""
results = []
seen_urls = set()
for link in soup.find_all("a", href=True):
href = link["href"]
text = link.get_text(strip=True)
if "suppl_file" in href.lower() and href.lower().endswith(".pdf"):
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
if href not in seen_urls:
seen_urls.add(href)
label = text if text and text.lower() != "pdf" else "Supporting Information"
results.append(SIFile(url=href, label=label))
return results
def _scrape_elsevier(soup: BeautifulSoup, base_url: str) -> list[SIFile]:
"""Scrape Elsevier / ScienceDirect SI links."""
results = []
seen_urls = set()
# Method 1: find mmc links in page HTML
for link in soup.find_all("a", href=True):
href = link["href"]
text = link.get_text(strip=True)
if "mmc" in href.lower() and any(href.lower().endswith(e) for e in (".pdf", ".docx", ".doc", ".xlsx")):
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
if href not in seen_urls:
seen_urls.add(href)
results.append(SIFile(url=href, label=text or "Supplementary Material"))
# Method 2: ScienceDirect may hide SI behind JS. Probe CDN URL pattern.
if not results:
pii_match = re.search(r'/pii/([A-Z0-9]+)', base_url, re.IGNORECASE)
if pii_match:
pii = pii_match.group(1)
for n in range(1, 6):
url = f"https://ars.els-cdn.com/content/image/1-s2.0-{pii}-mmc{n}.pdf"
try:
resp = _http_get(url, timeout=10)
if resp.status_code == 200 and len(resp.content) > 1000:
ctype = resp.headers.get("content-type", "").lower()
if "pdf" in ctype or "octet" in ctype:
results.append(SIFile(url=url, label=f"Supplementary Material {n}"))
else:
break
else:
break
except Exception:
break
return results
def _scrape_pnas_science(soup: BeautifulSoup, base_url: str) -> list[SIFile]:
"""Scrape PNAS / Science (AAAS) SI links. Both use similar Atypon-based platforms."""
results = []
seen_urls = set()
for link in soup.find_all("a", href=True):
href = link["href"]
text = link.get_text(strip=True)
if "/doi/suppl/" in href and "suppl_file" in href:
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
if href not in seen_urls:
seen_urls.add(href)
label = text if text and text.lower() not in ("download", "pdf") else "Supplementary Material"
results.append(SIFile(url=href, label=label))
# Also check the supplementary materials section
supp_section = soup.find("section", class_=re.compile(r"core-supplementary-materials?"))
if supp_section:
for link in supp_section.find_all("a", href=True):
href = link["href"]
if href.startswith("/") or href.startswith("http"):
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
ext = _get_file_ext(href) or Path(urllib.parse.urlparse(href).path).suffix.lower()
if ext in SUPPORTED_SI_EXTENSIONS or "suppl_file" in href:
if href not in seen_urls:
seen_urls.add(href)
results.append(SIFile(url=href, label=link.get_text(strip=True) or "SI Appendix"))
return results
def _scrape_wiley(soup: BeautifulSoup, base_url: str) -> list[SIFile]:
"""Scrape Wiley Online Library SI links."""
results = []
seen_urls = set()
supported = {".pdf", ".doc", ".docx", ".xlsx", ".xls", ".zip"}
for link in soup.find_all("a", href=True):
href = link["href"]
text = link.get_text(strip=True)
if "downloadSupplement" in href or "suppl" in href.lower():
ext = Path(urllib.parse.urlparse(href).path).suffix.lower()
if ext in supported or "downloadSupplement" in href:
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
if href not in seen_urls:
seen_urls.add(href)
results.append(SIFile(url=href, label=text or "Supporting Information"))
return results
def _scrape_generic(soup: BeautifulSoup, base_url: str) -> list[SIFile]:
"""Fallback: look for any links with supplementary/SI keywords."""
results = []
seen_urls = set()
keywords = ["supplement", "supporting", "esm", "moesm", "si_file", "appendix",
"suppdata", "suppl_file", "electronic supplementary"]
file_exts = [".pdf", ".doc", ".docx", ".xlsx", ".xls", ".zip", ".csv"]
for link in soup.find_all("a", href=True):
href = link["href"]
text = link.get_text(strip=True)
combined = (href + " " + text).lower()
if any(kw in combined for kw in keywords):
if any(ext in href.lower() for ext in file_exts):
if not href.startswith("http"):
href = urllib.parse.urljoin(base_url, href)
if href not in seen_urls:
seen_urls.add(href)
results.append(SIFile(url=href, label=text or "Supplementary File"))
return results
PUBLISHER_SCRAPERS = {
"nature.com": _scrape_springer_nature,
"springer.com": _scrape_springer_nature,
"link.springer.com": _scrape_springer_nature,
"pubs.acs.org": _scrape_acs,
"sciencedirect.com": _scrape_elsevier,
"onlinelibrary.wiley.com": _scrape_wiley,
"pnas.org": _scrape_pnas_science,
"science.org": _scrape_pnas_science,
"rsc.org": _scrape_generic,
}
def _resolve_elsevier_redirect(url: str, soup: BeautifulSoup) -> str | None:
"""Follow Elsevier linkinghub meta-refresh redirect to ScienceDirect."""
meta = soup.find("meta", attrs={"http-equiv": re.compile(r"refresh", re.I)})
if meta:
content = meta.get("content", "")
m = re.search(r"Redirect=(https?[^&'\"]+)", content)
if m:
return urllib.parse.unquote(m.group(1))
return None
def find_si_links(article_url: str, on_progress: ProgressCallback = _noop_progress) -> list[SIFile]:
"""Scrape the article landing page for SI download links."""
on_progress(2, "searching", f"Scraping article page: {article_url}")
resp = _http_get(article_url, timeout=30)
if resp.status_code == 403:
on_progress(2, "warning", f"Publisher blocked access (HTTP 403). Trying alternative methods...")
return _fallback_si_discovery(article_url, on_progress)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
# Handle Elsevier linkinghub redirect pages
if "linkinghub.elsevier.com" in article_url:
redirect_url = _resolve_elsevier_redirect(article_url, soup)
if redirect_url:
on_progress(2, "searching", f"Following redirect to: {redirect_url}")
article_url = redirect_url
resp = _http_get(article_url, timeout=30)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
domain = urllib.parse.urlparse(article_url).netloc
for pub_domain, scraper in PUBLISHER_SCRAPERS.items():
if pub_domain in domain:
results = scraper(soup, article_url)
if results:
return results
return _scrape_generic(soup, article_url)
def _fallback_si_discovery(article_url: str, on_progress: ProgressCallback) -> list[SIFile]:
"""Try publisher-specific URL patterns when page scraping is blocked."""
domain = urllib.parse.urlparse(article_url).netloc
# Science / Science Advances / PNAS (Atypon platform)
if "science.org" in domain or "pnas.org" in domain:
doi_match = re.search(r'(10\.\d{4,}/\S+?)(?:[#?]|$)', article_url)
if doi_match:
doi = doi_match.group(1).rstrip("/")
on_progress(2, "fallback", "Constructing Science/PNAS SI URL from DOI pattern")
article_id = doi.split("/")[-1]
journal_prefix = ""
if "sciadv." in article_id or "science." in article_id:
journal_prefix = article_id.split(".")[0] + "."
slug = article_id if journal_prefix else article_id
candidates = []
for pattern in [
f"{slug}_sm.pdf", f"{slug}_SM.pdf",
f"{slug}-sm.pdf", f"{slug}-SM.pdf",
]:
candidates.append(
f"https://www.{'science.org' if 'science.org' in domain else 'pnas.org'}"
f"/doi/suppl/{doi}/suppl_file/{pattern}"
)
for url in candidates:
try:
resp = _http_get(url, timeout=15)
if _is_valid_file_response(resp, ".pdf"):
return [SIFile(url=url, label="Supplementary Materials")]
except Exception:
continue
base_url = f"https://www.{'science.org' if 'science.org' in domain else 'pnas.org'}/doi/suppl/{doi}/suppl_file/"
on_progress(2, "info",
f"SI likely exists but is protected by Cloudflare. "
f"Try the Chrome extension or manually download from the article page.")
# APS: supplemental material at /journal/supplemental/DOI
if "aps.org" in domain:
on_progress(2, "fallback", "Trying APS supplemental URL pattern")
path = urllib.parse.urlparse(article_url).path
doi_match = re.search(r'(10\.\d{4,}/\S+)', article_url)
if doi_match:
doi = doi_match.group(1)
journal_codes = {"PhysRevLett": "prl", "PhysRevB": "prb", "PhysRevX": "prx",
"PhysRevMaterials": "prmaterials", "PhysRevE": "pre",
"PhysRevA": "pra", "RevModPhys": "rmp"}
journal = doi.split("/")[1].split(".")[0]
code = journal_codes.get(journal, journal.lower())
suppl_url = f"https://journals.aps.org/{code}/supplemental/{doi}"
resp = _http_get(suppl_url, timeout=15)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, "html.parser")
results = []
for a in soup.find_all("a", href=True):
href = a["href"]
if any(ext in href.lower() for ext in [".pdf", ".doc", ".zip", ".tar"]):
if not href.startswith("http"):
href = urllib.parse.urljoin(suppl_url, href)
results.append(SIFile(url=href, label=a.get_text(strip=True) or "Supplemental Material"))
if results:
return results
on_progress(2, "info", "No supplemental material found for this APS article")
return []
# ---------------------------------------------------------------------------
# SI Download
# ---------------------------------------------------------------------------
SUPPORTED_SI_EXTENSIONS = {".pdf", ".doc", ".docx", ".xlsx", ".xls"}
def _get_file_ext(url: str) -> str:
"""Extract file extension from URL, checking both path and query parameters."""
parsed = urllib.parse.urlparse(url)
ext = Path(parsed.path).suffix.lower()
if ext in SUPPORTED_SI_EXTENSIONS:
return ext
# Check query parameters (e.g. Wiley: ?file=name.docx)
params = urllib.parse.parse_qs(parsed.query)
for key in ("file", "filename"):
for val in params.get(key, []):
ext = Path(val).suffix.lower()
if ext in SUPPORTED_SI_EXTENSIONS:
return ext
# Check the full URL string as fallback
for ext in SUPPORTED_SI_EXTENSIONS:
if ext in url.lower():
return ext
return ""
_DOCX_HTML_TEMPLATE = """<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
body {{ font-family: Arial, Helvetica, sans-serif; font-size: 11pt;
margin: 2cm; line-height: 1.5; }}
img {{ max-width: 100%; height: auto; page-break-inside: avoid; }}
table {{ border-collapse: collapse; width: 100%; margin: 0.8em 0;
page-break-inside: auto; }}
td, th {{ border: 1px solid #999; padding: 4px 8px; font-size: 10pt; }}
h1 {{ font-size: 16pt; }} h2 {{ font-size: 14pt; }} h3 {{ font-size: 12pt; }}
p {{ margin: 0.4em 0; }}
</style></head><body>{body}</body></html>"""
def _convert_to_pdf(input_path: str, output_path: str) -> bool:
"""Convert a non-PDF file (docx, doc, xlsx) to PDF.
Uses pure-Python mammoth + WeasyPrint (no local Office software needed).
Falls back to LibreOffice headless for formats mammoth cannot handle.
"""
import subprocess
ext = Path(input_path).suffix.lower()
if ext not in (".doc", ".docx", ".xlsx", ".xls"):
return False
# Strategy 1: mammoth + WeasyPrint (pure Python, no external software)
if ext == ".docx":
try:
import mammoth
from weasyprint import HTML
with open(input_path, "rb") as f:
result = mammoth.convert_to_html(f)
full_html = _DOCX_HTML_TEMPLATE.format(body=result.value)
HTML(string=full_html).write_pdf(output_path)
if os.path.isfile(output_path) and os.path.getsize(output_path) > 100:
return True
except ImportError:
pass
except Exception:
pass
# Strategy 2: LibreOffice headless (handles .doc, .xlsx, and .docx fallback)
for cmd in ["libreoffice", "soffice",
"/Applications/LibreOffice.app/Contents/MacOS/soffice"]:
try:
subprocess.run(
[cmd, "--headless", "--convert-to", "pdf", "--outdir",
str(Path(output_path).parent), input_path],
capture_output=True, timeout=180,
)
expected = Path(output_path).parent / (Path(input_path).stem + ".pdf")
if expected.is_file():
if str(expected) != output_path:
expected.rename(output_path)
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
return False
def _is_valid_file_response(resp, expected_ext: str) -> bool:
"""Check if an HTTP response actually contains the expected file, not HTML."""
content_type = resp.headers.get("content-type", "").lower()
if "text/html" in content_type:
return False
if expected_ext == ".pdf" and not resp.content[:5].startswith(b"%PDF-"):
return False
return True
def download_si_files(
si_files: list[SIFile], output_dir: str,
article_url: str = "",
on_progress: ProgressCallback = _noop_progress,
) -> list[SIFile]:
"""Download SI files, convert non-PDF formats, and update their local_path."""
os.makedirs(output_dir, exist_ok=True)
downloaded = []
for i, si in enumerate(si_files):
ext = _get_file_ext(si.url)
if ext not in SUPPORTED_SI_EXTENSIONS:
on_progress(3, "skipping", f"Unsupported format ({ext}): {si.label}")
continue
on_progress(3, "downloading", f"Downloading: {si.label}")
try:
resp = _http_get(si.url, timeout=120, referer=article_url or None)
resp.raise_for_status()
except Exception as e:
on_progress(3, "warning", f"Download failed for {si.label}: {e}")
on_progress(3, "info", f"SI URL: {si.url}")
continue
if not ext:
ext = ".pdf"
if not _is_valid_file_response(resp, ext):
on_progress(3, "warning",
f"Download blocked for {si.label} (publisher returned HTML instead of file). "
f"You can manually download the SI from: {si.url}")
continue
raw_path = os.path.join(output_dir, f"si_{i+1}_raw{ext}")
with open(raw_path, "wb") as f:
f.write(resp.content)
if ext == ".pdf":
final_path = raw_path
else:
on_progress(3, "converting", f"Converting {ext} to PDF...")
final_path = os.path.join(output_dir, f"si_{i+1}.pdf")
if not _convert_to_pdf(raw_path, final_path):
on_progress(3, "warning", f"Could not convert {si.label} to PDF (install LibreOffice or MS Word)")
continue
si.local_path = final_path
on_progress(3, "downloaded", f"Saved {si.label} ({len(resp.content) / 1024:.0f} KB)")
downloaded.append(si)
return downloaded
# ---------------------------------------------------------------------------
# Text Extraction (with fallback strategies)
# ---------------------------------------------------------------------------
def extract_text_direct(doc: fitz.Document) -> dict[int, str]:
"""Try direct text extraction from all pages. Returns {page_idx: text}."""
result = {}
for i in range(len(doc)):
text = doc[i].get_text()
if text.strip():
result[i] = text
return result
def extract_text_with_ocr(doc: fitz.Document) -> dict[int, str]:
"""Render pages to images and OCR. Returns {page_idx: text}."""
try:
import pytesseract
from PIL import Image
except ImportError:
print(" Warning: pytesseract/Pillow not installed, OCR unavailable")
return {}
result = {}
for i in range(len(doc)):
pix = doc[i].get_pixmap(dpi=200)
img = Image.open(io.BytesIO(pix.tobytes("png")))
text = pytesseract.image_to_string(img)
if text.strip():
result[i] = text
return result
def redownload_article_pdf(
doi: str, output_path: str, on_progress: ProgressCallback = _noop_progress,
) -> str | None:
"""Re-download the article PDF from the publisher for better text extraction."""
pdf_url = get_article_pdf_url(doi)
if not pdf_url:
return None
on_progress(4, "redownloading", f"Re-downloading article PDF from publisher")
resp = _http_get(pdf_url, timeout=60)
if resp.status_code == 200 and len(resp.content) > 1000:
with open(output_path, "wb") as f:
f.write(resp.content)
return output_path
return None
def get_article_text(
original_doc: fitz.Document, doi: str, work_dir: str,
on_progress: ProgressCallback = _noop_progress,
) -> tuple[fitz.Document, dict[int, str]]:
"""
Get text from the article, trying multiple strategies.
Returns (doc_to_use_for_merging, page_texts).
The returned doc may differ from original_doc if we re-downloaded.
"""
on_progress(4, "extracting", "Extracting text from article PDF")
texts = extract_text_direct(original_doc)
total_chars = sum(len(t) for t in texts.values())
if total_chars > 500:
on_progress(4, "extracted", f"Extracted {total_chars} chars from {len(texts)} pages")
return original_doc, texts
on_progress(4, "fallback", "Direct extraction insufficient, trying re-download")
redownloaded = redownload_article_pdf(doi, os.path.join(work_dir, "article_redownloaded.pdf"), on_progress)
if redownloaded:
new_doc = fitz.open(redownloaded)
texts = extract_text_direct(new_doc)
total_chars = sum(len(t) for t in texts.values())
if total_chars > 500:
on_progress(4, "extracted", f"Re-downloaded PDF: {total_chars} chars from {len(texts)} pages")
return new_doc, texts
on_progress(4, "ocr", "Text extraction failed, trying OCR")
texts = extract_text_with_ocr(original_doc)
total_chars = sum(len(t) for t in texts.values())
if total_chars > 100:
on_progress(4, "extracted", f"OCR extraction: {total_chars} chars from {len(texts)} pages")
else:
on_progress(4, "warning", "Could not extract text — cross-referencing will be limited")
return original_doc, texts
# ---------------------------------------------------------------------------
# SI Reference Detection & Mapping
# ---------------------------------------------------------------------------
# All patterns are matched with re.IGNORECASE.
# Patterns that appear in the main article text (ordered by specificity)
MAIN_TEXT_SI_PATTERNS = [
# Nature-style: "Supplementary Fig. S1", "Supplementary Figure S2a"
(r'supplementary\s+fig(?:ure|s?\.)\s*S?(\d+)([a-z]?)', "figure"),
(r'supplementary\s+tables?\s*S?(\d+)', "table"),
(r'supplementary\s+notes?\s*S?(\d+)', "note"),
(r'supplementary\s+movies?\s*S?(\d+)', "movie"),
(r'supplementary\s+(?:method|discussion|data)\w*', "section"),
# Standalone with S prefix (common across publishers)
(r'figures?\s+S(\d+)([a-z]?)', "figure"),
(r'figs?\.\s*S(\d+)([a-z]?)', "figure"),
(r'tables?\s+S(\d+)', "table"),
(r'movies?\s+S(\d+)', "movie"),
(r'notes?\s+S(\d+)', "note"),
(r'sections?\s+S(\d+)', "section"),
(r'schemes?\s+S(\d+)', "scheme"),
(r'equations?\s+S(\d+)', "equation"),
# "SI Appendix, Fig. S1" (PNAS style)
(r'SI\s+Appendix,?\s+fig(?:ure|s?\.)\s*S?(\d+)([a-z]?)', "figure"),
(r'SI\s+Appendix,?\s+tables?\s*S?(\d+)', "table"),
]
# Patterns that appear in the SI document as headings/captions
SI_HEADING_PATTERNS = [
# Nature-style: "Supplementary Figure 1"
(r'supplementary\s+figure\s+(\d+)', "figure"),
(r'supplementary\s+table\s+(\d+)', "table"),
(r'supplementary\s+note\s+(\d+)', "note"),
(r'supplementary\s+movie\s+(\d+)', "movie"),
(r'supplementary\s+method', "section_method"),
(r'supplementary\s+discussion', "section_discussion"),
(r'supplementary\s+data\s*(\d*)', "data"),
# "Figure S1", "Fig. S1", "Table S1" (Science, ACS, general style)
(r'fig(?:ure)?\s*\.?\s*S(\d+)', "figure"),
(r'table\s*S(\d+)', "table"),
(r'scheme\s+S(\d+)', "scheme"),
(r'equation\s+S(\d+)', "equation"),
(r'movie\s+S(\d+)', "movie"),
(r'note\s+S(\d+)', "note"),
# ACS section headings: "S1 DFT dataset" (standalone S-number at line start)
(r'(?:^|\n)\s*S(\d+)[\.\s]+[A-Z]', "section"),
]
def _normalize_key(category: str, number: str | None) -> str:
if number and number.isdigit():
return f"{category}_{number}"
return category
def _extract_number(m: re.Match) -> str:
"""Extract the first purely-numeric capture group from a regex match."""
if not m.lastindex:
return ""
for i in range(1, m.lastindex + 1):
g = m.group(i)
if g and g.isdigit():
return g
return ""
def find_si_references_in_text(
doc: fitz.Document, page_texts: dict[int, str]
) -> list[SIReference]:
"""Find all SI references in the main article with their positions."""
refs = []
seen = set()
for page_idx in sorted(page_texts.keys()):
page = doc[page_idx]
text = page_texts[page_idx]
text_flat = re.sub(r'\s+', ' ', text)
for pattern, category in MAIN_TEXT_SI_PATTERNS:
for m in re.finditer(pattern, text_flat, re.IGNORECASE):
full_match = m.group(0)
number = _extract_number(m)
key = _normalize_key(category, number)
dedup = (page_idx, key)
if dedup in seen:
continue
seen.add(dedup)
rects = page.search_for(full_match)
if not rects:
compact = re.sub(r'\s+', ' ', full_match)
rects = page.search_for(compact)
if not rects:
# Try a shorter search string (e.g. "Fig. S6" from "fig. S6")
short = re.sub(r'^supplementary\s+', '', full_match, flags=re.IGNORECASE).strip()
if short != full_match:
rects = page.search_for(short)
rect = rects[0] if rects else None
refs.append(SIReference(
text=full_match,
page_idx=page_idx,
rect=rect,
target_key=key,
))
return refs
def find_si_anchors(doc: fitz.Document) -> list[SIAnchor]:
"""Find headings/captions in the SI document.
Only keeps the *first* occurrence of each key so that forward links
jump to the caption rather than a later in-text mention.
"""
anchors = []
seen_keys = set()
for page_idx in range(len(doc)):
text = doc[page_idx].get_text()
text_flat = re.sub(r'\s+', ' ', text)
page = doc[page_idx]
for pattern, category in SI_HEADING_PATTERNS:
for m in re.finditer(pattern, text_flat, re.IGNORECASE | re.MULTILINE):
full_match = m.group(0).strip()
number = _extract_number(m)
key = _normalize_key(category, number)