File size: 3,356 Bytes
5969b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
19ee463
5969b2a
 
 
 
 
 
 
 
 
 
 
 
 
19ee463
 
 
 
 
 
5969b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ee463
 
 
 
 
 
5969b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Download Protocol and SAP PDFs for each row of file.csv.

Outputs go to source/downloads/row_<#>/{protocol,sap}.pdf.
Skips rows with empty links and rows already downloaded.
"""

from __future__ import annotations

import csv
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from urllib.parse import urlparse

CSV_PATH = Path(__file__).parent / "file.csv"
OUT_ROOT = Path(__file__).parent / "downloads"
TIMEOUT = 60
RETRIES = 2
SLEEP_BETWEEN = 0.3

UA = (
    "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"
)


def paper_link_slug(link: str) -> str:
    path = urlparse((link or "").strip()).path.strip("/")
    parts = [p for p in path.split("/") if p]
    return "_".join(parts[-2:]) if len(parts) >= 2 else ""


def download(url: str, dest: Path) -> tuple[bool, str]:
    if dest.exists() and dest.stat().st_size > 0:
        return True, "exists"
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    last_err = ""
    for attempt in range(RETRIES + 1):
        try:
            with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
                data = resp.read()
            dest.write_bytes(data)
            return True, f"ok ({len(data)} bytes)"
        except urllib.error.HTTPError as e:
            last_err = f"HTTP {e.code}"
        except (urllib.error.URLError, TimeoutError) as e:
            last_err = f"network: {e}"
        except Exception as e:  # noqa: BLE001
            last_err = f"error: {e}"
        time.sleep(1 + attempt)
    return False, last_err


def main(start_row: int = 3) -> None:
    OUT_ROOT.mkdir(exist_ok=True)
    with CSV_PATH.open(newline="", encoding="utf-8") as fh:
        reader = csv.DictReader(fh)
        for row in reader:
            num_str = (row.get("#") or "").strip()
            if not num_str.isdigit():
                continue
            num = int(num_str)
            if num < start_row:
                continue

            protocol = (row.get("Study Protocol Link") or "").strip()
            sap = (row.get("Protocol+SAP / SAP Link") or "").strip()
            if not protocol and not sap:
                print(f"[{num}] skip: no links")
                continue

            slug = paper_link_slug(row.get("Paper Link") or "")
            if not slug:
                print(f"[{num}] skip: no usable Paper Link")
                continue

            row_dir = OUT_ROOT / slug
            row_dir.mkdir(exist_ok=True)

            if protocol:
                ok, msg = download(protocol, row_dir / "protocol.pdf")
                print(f"[{num}] protocol: {msg}")
                if not ok:
                    (row_dir / "protocol.error.txt").write_text(
                        f"{protocol}\n{msg}\n", encoding="utf-8"
                    )
                time.sleep(SLEEP_BETWEEN)

            if sap:
                ok, msg = download(sap, row_dir / "sap.pdf")
                print(f"[{num}] sap: {msg}")
                if not ok:
                    (row_dir / "sap.error.txt").write_text(
                        f"{sap}\n{msg}\n", encoding="utf-8"
                    )
                time.sleep(SLEEP_BETWEEN)


if __name__ == "__main__":
    start = int(sys.argv[1]) if len(sys.argv) > 1 else 3
    main(start_row=start)